@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
@@ -5,6 +5,7 @@ import {
5
5
  DEFAULT_STROKE_WEIGHT
6
6
  } from './constants'
7
7
  import { normalizeEffects } from './effects'
8
+ import { EMPTY_LIST, EMPTY_RECORD, shareEmptyNodeValues } from './empty-values'
8
9
  import { createInstanceOverrideState } from './instances/overrides'
9
10
  import { NO_LETTER_SPACING } from './text/lengths'
10
11
  import type { NodeType, SceneNode, SourceMetadata } from './types'
@@ -14,18 +15,19 @@ export function createDefaultSourceMetadata(): SourceMetadata {
14
15
  format: null,
15
16
  id: null,
16
17
  orderKey: null,
17
- editedFields: [],
18
+ editedFields: EMPTY_LIST,
18
19
  fig: {
19
20
  rawSize: null,
20
21
  rawTransform: null,
21
- rawNodeFields: {},
22
+ rawNodeFields: EMPTY_RECORD,
22
23
  layout: null,
23
- symbolOverrides: [],
24
- componentPropAssignments: [],
25
- derivedSymbolData: [],
24
+ symbolOverrides: EMPTY_LIST,
25
+ componentPropAssignments: EMPTY_LIST,
26
+ derivedSymbolData: EMPTY_LIST,
26
27
  derivedSymbolDataLayoutVersion: null,
27
28
  uniformScaleFactor: null
28
- }
29
+ },
30
+ drawio: null
29
31
  }
30
32
  }
31
33
 
@@ -100,7 +102,10 @@ export function createDefaultNode(
100
102
  type: NodeType,
101
103
  overrides: Partial<SceneNode> = {}
102
104
  ): SceneNode {
103
- const node = {
105
+ // A literal ending in a spread is built one field at a time, and V8 keeps an object given this
106
+ // many fields that way in dictionary mode, about 3 KB more per layer; a spread copy of a
107
+ // finished literal keeps fast fields, in JavaScriptCore as well.
108
+ const defaults = {
104
109
  id: generateId(),
105
110
  type,
106
111
  name: type.charAt(0) + type.slice(1).toLowerCase(),
@@ -114,11 +119,13 @@ export function createDefaultNode(
114
119
  source: createDefaultSourceMetadata(),
115
120
  derivedLayout: null,
116
121
  fills:
117
- type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],
118
- strokes: [],
119
- effects: [],
120
- layoutGrids: [],
121
- guides: [],
122
+ type === 'TEXT'
123
+ ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }]
124
+ : EMPTY_LIST,
125
+ strokes: EMPTY_LIST,
126
+ effects: EMPTY_LIST,
127
+ layoutGrids: EMPTY_LIST,
128
+ guides: EMPTY_LIST,
122
129
  fillStyleId: null,
123
130
  strokeStyleId: null,
124
131
  textStyleId: null,
@@ -136,6 +143,8 @@ export function createDefaultNode(
136
143
  visible: true,
137
144
  locked: false,
138
145
  clipsContent: false,
146
+ overflowDirection: 'NONE',
147
+ scrollBehavior: 'SCROLLS',
139
148
  text: '',
140
149
  fontSize: 14,
141
150
  fontFamily: DEFAULT_FONT_FAMILY,
@@ -155,8 +164,8 @@ export function createDefaultNode(
155
164
  layoutAlignSelf: 'AUTO',
156
165
  vectorNetwork: null,
157
166
  handleMirroring: 'NONE',
158
- fillGeometry: [],
159
- strokeGeometry: [],
167
+ fillGeometry: EMPTY_LIST,
168
+ strokeGeometry: EMPTY_LIST,
160
169
  arcData: null,
161
170
  textAlignVertical: 'TOP',
162
171
  textAutoResize: 'NONE',
@@ -164,24 +173,24 @@ export function createDefaultNode(
164
173
  textDecoration: 'NONE',
165
174
  textDecorationStyle: 'SOLID',
166
175
  textDecorationThickness: null,
167
- textDecorationFills: [],
176
+ textDecorationFills: EMPTY_LIST,
168
177
  textDecorationSkipInk: true,
169
178
  textUnderlineOffset: null,
170
179
  maxLines: null,
171
- textParagraphs: [],
180
+ textParagraphs: EMPTY_LIST,
172
181
  listSpacing: 0,
173
182
  paragraphSpacing: 0,
174
183
  paragraphIndent: 0,
175
184
  hangingList: false,
176
- styleRuns: [],
177
- fontVariations: [],
185
+ styleRuns: EMPTY_LIST,
186
+ fontVariations: EMPTY_LIST,
178
187
  opticalSizeFromFontSize: true,
179
- fontFeatures: [],
188
+ fontFeatures: EMPTY_LIST,
180
189
  horizontalConstraint: 'MIN',
181
190
  verticalConstraint: 'MIN',
182
191
  strokeCap: 'NONE',
183
192
  strokeJoin: 'MITER',
184
- dashPattern: [],
193
+ dashPattern: EMPTY_LIST,
185
194
  borderTopWeight: 0,
186
195
  borderRightWeight: 0,
187
196
  borderBottomWeight: 0,
@@ -200,14 +209,14 @@ export function createDefaultNode(
200
209
  connectorLineType: 'ELBOWED',
201
210
  connectorStartCap: 'ROUND',
202
211
  connectorEndCap: 'ARROW_LINES',
203
- connectorControlPoints: [],
212
+ connectorControlPoints: EMPTY_LIST,
204
213
  connectorCurveHandles: null,
205
214
  connectorLabelPosition: null,
206
215
  isMask: false,
207
216
  maskType: 'ALPHA',
208
217
  maskIsOutline: false,
209
- gridTemplateColumns: [],
210
- gridTemplateRows: [],
218
+ gridTemplateColumns: EMPTY_LIST,
219
+ gridTemplateRows: EMPTY_LIST,
211
220
  gridColumnGap: 0,
212
221
  gridRowGap: 0,
213
222
  gridPosition: null,
@@ -224,10 +233,10 @@ export function createDefaultNode(
224
233
  shapeTruncates: false,
225
234
  componentId: null,
226
235
  instanceOverrides: createInstanceOverrideState(),
227
- componentPropertyDefinitions: [],
228
- componentPropertyReferences: [],
229
- componentPropertyAssignments: {},
230
- componentPropertyValues: {},
236
+ componentPropertyDefinitions: EMPTY_LIST,
237
+ componentPropertyReferences: EMPTY_LIST,
238
+ componentPropertyAssignments: EMPTY_RECORD,
239
+ componentPropertyValues: EMPTY_RECORD,
231
240
  componentKey: null,
232
241
  sourceLibraryKey: null,
233
242
  publishId: null,
@@ -239,18 +248,18 @@ export function createDefaultNode(
239
248
  isSymbolPublishable: false,
240
249
  isExposedInstance: false,
241
250
  symbolDescription: '',
242
- symbolLinks: [],
243
- variantPropSpecs: [],
244
- boundVariables: {},
245
- variableBindingScales: {},
246
- variableAssignmentScales: {},
251
+ symbolLinks: EMPTY_LIST,
252
+ variantPropSpecs: EMPTY_LIST,
253
+ boundVariables: EMPTY_RECORD,
254
+ variableBindingScales: EMPTY_RECORD,
255
+ variableAssignmentScales: EMPTY_RECORD,
247
256
  componentScale: 1,
248
- variableModes: {},
249
- exportSettings: [],
257
+ variableModes: EMPTY_RECORD,
258
+ exportSettings: EMPTY_LIST,
250
259
  status: null,
251
- pluginData: [],
252
- pluginRelaunchData: [],
253
- prototypeReactions: [],
260
+ pluginData: EMPTY_LIST,
261
+ pluginRelaunchData: EMPTY_LIST,
262
+ prototypeReactions: EMPTY_LIST,
254
263
  internalOnly: false,
255
264
  flipX: false,
256
265
  flipY: false,
@@ -259,10 +268,11 @@ export function createDefaultNode(
259
268
  derivedTextHeight: null,
260
269
  textPathData: null,
261
270
  textPathBox: null,
262
- booleanOperation: undefined,
263
- ...overrides
271
+ booleanOperation: undefined
264
272
  } satisfies CompleteNodeFields
273
+ const node: SceneNode = { ...defaults, ...overrides }
265
274
  node.effects = normalizeEffects(node.effects)
275
+ shareEmptyNodeValues(node, Object.keys(overrides))
266
276
  return node
267
277
  }
268
278
 
@@ -5,6 +5,7 @@ import { behaviourSchema } from '../behaviours/schema'
5
5
  import { browserNodeSchema } from '../browser-node/schema'
6
6
  import type { OkHCLPayload } from '../color/okhcl'
7
7
  import { commentThreadsSchema } from '../comments/schema'
8
+ import { designMemorySchema } from '../design-memory/schema'
8
9
  import { clampExportQuality, isExportFormatId, type ExportFormatId } from '../export-format'
9
10
  import { clampExportScale } from '../export-scale'
10
11
  import { FIG_COMPRESSIONS } from '../fig-compression'
@@ -13,6 +14,7 @@ import type { Color, Rect, Vector } from '../primitives'
13
14
  import { scriptNodeSchema } from '../script/schema'
14
15
  import { shaderPaintSchema } from '../shaders/schema'
15
16
  import { nodeStatusSchema, statusWorkflowSchema } from '../statuses/schema'
17
+ import { tokenSourcesSchema } from '../token-sources/schema'
16
18
  import {
17
19
  MODE_ATTRIBUTE_PATTERN,
18
20
  TOKEN_UNITS,
@@ -25,6 +27,7 @@ import {
25
27
  type TextDirection,
26
28
  type TokenUnit
27
29
  } from '../types'
30
+ import { variationSetSchema, variationStandInSchema } from '../variations/schema'
28
31
  import {
29
32
  jsonPluginDataField,
30
33
  textPluginDataField,
@@ -249,6 +252,10 @@ export const PAIRDRAW_PLUGIN_DATA = {
249
252
  comments: jsonPluginDataField('comments', 'bookkeeping', commentThreadsSchema),
250
253
  /** The statuses layers can be in, on the DOCUMENT node. */
251
254
  statuses: jsonPluginDataField('statuses', 'bookkeeping', statusWorkflowSchema),
255
+ /** The code the document's variables are linked to, on the DOCUMENT node. */
256
+ tokenSources: jsonPluginDataField('tokenSources', 'bookkeeping', tokenSourcesSchema),
257
+ /** The design rules agents follow in the document, on the DOCUMENT node. */
258
+ designMemory: jsonPluginDataField('designMemory', 'bookkeeping', designMemorySchema),
252
259
  /** How tightly the document's `.fig` data is compressed, on the DOCUMENT node. */
253
260
  figCompression: textPluginDataField('figCompression', 'bookkeeping', FIG_COMPRESSIONS),
254
261
  /** A layer's status, any state of the workflow; Figma's `sectionStatusInfo` knows only two. */
@@ -289,7 +296,17 @@ export const PAIRDRAW_PLUGIN_DATA = {
289
296
  * A snapshot of one page: its address, viewport, and when it was refreshed. The picture is
290
297
  * the layer's image fill. An address that is not an http or https page does not decode.
291
298
  */
292
- browserNode: jsonPluginDataField('browserNode', 'content', browserNodeSchema)
299
+ browserNode: jsonPluginDataField('browserNode', 'content', browserNodeSchema),
300
+ /**
301
+ * On a section, that its children are variations of another layer: which one, and how that
302
+ * layer looked when they were made. A copy of the section is an ordinary section.
303
+ */
304
+ variationSet: jsonPluginDataField('variationSet', 'bookkeeping', variationSetSchema),
305
+ /**
306
+ * On a layer of a version, the main component or component set of the original it stands in
307
+ * for, so a pick keeps that component rather than pairing it by name.
308
+ */
309
+ variationStandIn: jsonPluginDataField('variationStandIn', 'bookkeeping', variationStandInSchema)
293
310
  } satisfies Record<string, PluginDataKey>
294
311
 
295
312
  const NOT_CONTENT = Object.values(PAIRDRAW_PLUGIN_DATA).filter((field) => field.role !== 'content')
package/src/preview.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { normalizeEffects } from './effects'
2
+ import { shareEmptyNodeValues } from './empty-values'
2
3
  import { textCacheInvalidationChanges } from './text/picture'
3
4
  import type { SceneNode } from './types'
4
5
  import { normalizeVectorNetwork } from './vector-network'
@@ -80,5 +81,6 @@ export function updateNodePreview(
80
81
  beforeUpdate?.(node, normalizedChanges)
81
82
  graph.positionPreviewVersion++
82
83
  Object.assign(node, normalizedChanges)
84
+ shareEmptyNodeValues(node, Object.keys(normalizedChanges))
83
85
  return normalizedChanges
84
86
  }
@@ -52,8 +52,13 @@ function scaledStrokes(strokes: readonly Stroke[], scale: number): Stroke[] {
52
52
  function scaledEffects(effects: readonly Effect[], scale: number): Effect[] {
53
53
  return effects.map((effect) => {
54
54
  const copy = structuredClone(effect)
55
- // A shader effect has no geometry of its own; only a shadow's measures follow the layer.
56
- if (copy.type === 'SHADER') return copy
55
+ // A shader effect has no geometry of its own, and a noise's grain keeps its size.
56
+ if (copy.type === 'SHADER' || copy.type === 'NOISE') return copy
57
+ // A texture roughens the edges by its radius; its grain keeps its size too.
58
+ if (copy.type === 'TEXTURE') {
59
+ copy.radius *= scale
60
+ return copy
61
+ }
57
62
  copy.offset = { x: copy.offset.x * scale, y: copy.offset.y * scale }
58
63
  copy.radius *= scale
59
64
  copy.spread *= scale
@@ -0,0 +1,104 @@
1
+ import * as v from 'valibot'
2
+
3
+ import type { SceneGraph } from '../graph'
4
+ import { readPluginData, withPluginData } from '../plugin-data/field'
5
+ import { PAIRDRAW_PLUGIN_DATA } from '../plugin-data/fields'
6
+ import type { PluginDataEntry } from '../types'
7
+ import { relativeTokenPathSchema, type TokenSource } from './schema'
8
+
9
+ const { tokenSources } = PAIRDRAW_PLUGIN_DATA
10
+
11
+ /**
12
+ * The code a document's variables are linked to, with what it held at the last sync. The links
13
+ * live in Pairdraw's plugin data on the document node, so they travel with the `.fig` file and
14
+ * Figma ignores them; where each file is on this computer stays with the app, not the document.
15
+ */
16
+ export function readTokenSources(graph: SceneGraph): TokenSource[] {
17
+ return readPluginData(graph.getNode(graph.rootId)?.pluginData, tokenSources) ?? []
18
+ }
19
+
20
+ /**
21
+ * The links with their snapshots keyed by the graph's variable and mode ids. A format that keys
22
+ * variables and modes by name, such as `.pen`, gives them new ids when it reads them back; the
23
+ * names the file stored when it was saved, or the last sync's where the file recorded none, find
24
+ * them again. `names` and the snapshot's token identities are kept as they were. Links whose
25
+ * variables are all gone are left as they are.
26
+ */
27
+ export function rekeyTokenSources(
28
+ graph: SceneGraph,
29
+ sources: readonly TokenSource[]
30
+ ): TokenSource[] {
31
+ const collectionsByName = new Map(
32
+ [...graph.variableCollections.values()].map((collection) => [collection.name, collection])
33
+ )
34
+ const variablesByKey = new Map<string, string>()
35
+ for (const variable of graph.variables.values()) {
36
+ const collection = graph.variableCollections.get(variable.collectionId)
37
+ if (collection) variablesByKey.set(`${collection.name}/${variable.name}`, variable.id)
38
+ }
39
+ const currentModeId = (collectionName: string, modeId: string, modes: TokenSource['modes']) => {
40
+ const name = modes?.[collectionName]?.[modeId]
41
+ if (name === undefined) return modeId
42
+ const mode = collectionsByName.get(collectionName)?.modes.find((entry) => entry.name === name)
43
+ return mode?.modeId ?? modeId
44
+ }
45
+ return sources.map((source) => {
46
+ const ids = new Map<string, string>()
47
+ for (const [id, key] of Object.entries(source.currentNames ?? source.names ?? {})) {
48
+ const current = variablesByKey.get(key)
49
+ if (current !== undefined) ids.set(id, current)
50
+ }
51
+ if (ids.size === 0) return source
52
+ const collectionOf = (id: string) => {
53
+ const variable = graph.variables.get(id)
54
+ return variable ? graph.variableCollections.get(variable.collectionId)?.name : undefined
55
+ }
56
+ const snapshot: TokenSource['snapshot'] = {}
57
+ for (const [oldId, values] of Object.entries(source.snapshot)) {
58
+ const id = ids.get(oldId) ?? oldId
59
+ const collection = collectionOf(id)
60
+ const entry: Record<string, string> = {}
61
+ for (const [modeId, signature] of Object.entries(values)) {
62
+ entry[collection ? currentModeId(collection, modeId, source.modes) : modeId] = signature
63
+ }
64
+ snapshot[id] = { ...snapshot[id], ...entry }
65
+ }
66
+ const names = Object.fromEntries(
67
+ Object.entries(source.names ?? {}).map(([id, key]) => [ids.get(id) ?? id, key])
68
+ )
69
+ const modes = source.modes
70
+ ? Object.fromEntries(
71
+ Object.entries(source.modes).map(([collectionName, byMode]) => [
72
+ collectionName,
73
+ Object.fromEntries(
74
+ Object.entries(byMode).map(([modeId, name]) => [
75
+ currentModeId(collectionName, modeId, source.modes),
76
+ name
77
+ ])
78
+ )
79
+ ])
80
+ )
81
+ : undefined
82
+ return { ...source, snapshot, names, ...(modes ? { modes } : {}) }
83
+ })
84
+ }
85
+
86
+ /**
87
+ * The document node's plugin data holding `sources` in place of its links, for an edit that
88
+ * writes them, undoably or not, as one change to the node.
89
+ */
90
+ export function tokenSourcesPluginData(
91
+ graph: SceneGraph,
92
+ sources: readonly TokenSource[]
93
+ ): PluginDataEntry[] {
94
+ // A path that is not relative would make the reader drop the whole link; the link keeps going
95
+ // by its name instead.
96
+ const stored = sources.map(({ path, ...source }) =>
97
+ path !== undefined && v.is(relativeTokenPathSchema, path) ? { ...source, path } : source
98
+ )
99
+ return withPluginData(
100
+ graph.getNode(graph.rootId)?.pluginData ?? [],
101
+ tokenSources,
102
+ stored.length > 0 ? stored : undefined
103
+ )
104
+ }
@@ -0,0 +1,2 @@
1
+ export * from './document'
2
+ export * from './schema'
@@ -0,0 +1,59 @@
1
+ import * as v from 'valibot'
2
+
3
+ /**
4
+ * A path from the document's folder, never one that names a place on its own: no leading `/` or
5
+ * `\\` (POSIX roots, UNC shares), no `~` (a home folder), and no drive letter or URL scheme such
6
+ * as `C:` or `file:`.
7
+ */
8
+ export const relativeTokenPathSchema = v.pipe(
9
+ v.string(),
10
+ v.nonEmpty(),
11
+ v.maxLength(1024),
12
+ v.check(
13
+ (path) => !/^(?:[/\\~]|[a-z][\w+.-]*:)/i.test(path),
14
+ 'A linked path is relative to the document'
15
+ )
16
+ )
17
+
18
+ const tokenSourceSchema = v.object({
19
+ id: v.pipe(v.string(), v.nonEmpty(), v.maxLength(64)),
20
+ /** A stylesheet, a project folder, or W3C design token files. */
21
+ kind: v.picklist(['css', 'folder', 'dtcg']),
22
+ /** The file or folder name, for people. */
23
+ name: v.pipe(v.string(), v.maxLength(256)),
24
+ /** Where it is from the document's folder, when the document has one. */
25
+ path: v.optional(relativeTokenPathSchema),
26
+ syncedAt: v.optional(v.pipe(v.string(), v.isoTimestamp())),
27
+ /** What the code held at the last sync: a value signature by variable id and mode id. */
28
+ snapshot: v.record(v.string(), v.record(v.string(), v.string())),
29
+ /**
30
+ * The token each variable was at the last sync, `Collection/name` by variable id, so a variable
31
+ * deleted on the canvas is known when the code still has it.
32
+ */
33
+ names: v.optional(v.record(v.string(), v.string())),
34
+ /**
35
+ * The names the document held when it was saved, `Collection/name` by variable id. A format that
36
+ * keys variables by name gives them new ids when it reads them back; this finds a renamed
37
+ * variable's new id while `names` keeps the token it was at the last sync.
38
+ */
39
+ currentNames: v.optional(v.record(v.string(), v.string())),
40
+ /**
41
+ * The mode names the document holds, by collection name and mode id. A format that keys variables
42
+ * and modes by name gives them new ids when it reads them back, and this maps the snapshot onto
43
+ * those.
44
+ */
45
+ modes: v.optional(v.record(v.string(), v.record(v.string(), v.string())))
46
+ })
47
+
48
+ export type TokenSource = v.InferOutput<typeof tokenSourceSchema>
49
+
50
+ /** The code a document's variables are linked to; entries that cannot be read are left out. */
51
+ export const tokenSourcesSchema: v.GenericSchema<unknown, TokenSource[]> = v.pipe(
52
+ v.array(v.unknown()),
53
+ v.transform((items) =>
54
+ items.flatMap((item) => {
55
+ const parsed = v.safeParse(tokenSourceSchema, item)
56
+ return parsed.success ? [parsed.output] : []
57
+ })
58
+ )
59
+ )
package/src/types.ts CHANGED
@@ -64,12 +64,31 @@ export interface FigmaSourcePayload {
64
64
  uniformScaleFactor: number | null
65
65
  }
66
66
 
67
+ /**
68
+ * An edge as its draw.io file wrote it: the style pairs and geometry the author set. A connector
69
+ * read from a file keeps them so saving an unedited edge writes back what draw.io had, instead of
70
+ * re-routing it.
71
+ */
72
+ export interface DrawIOEdgeSource {
73
+ /** The style's names and its pairs, in the order the file wrote them. */
74
+ styleNames: string[]
75
+ styleValues: Partial<Record<string, string>>
76
+ /** The label's place along the edge, as the geometry's `x`. */
77
+ labelX: number
78
+ /** Bend points and free ends, in the edge's parent's axes. */
79
+ points: Vector[]
80
+ sourcePoint: Vector | null
81
+ targetPoint: Vector | null
82
+ }
83
+
67
84
  export interface SourceMetadata {
68
85
  format: 'fig' | null
69
86
  id: string | null
70
87
  orderKey: string | null
71
88
  editedFields: string[]
72
89
  fig: FigmaSourcePayload
90
+ /** The edge cell a connector was read from, kept until the connector is edited. */
91
+ drawio?: DrawIOEdgeSource | null
73
92
  }
74
93
 
75
94
  export type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'
@@ -217,7 +236,7 @@ export interface Fill {
217
236
  imageTransform?: GradientTransform
218
237
  /** Clockwise turn of a Fill, Fit or Tile image, in multiples of 90°; a crop holds its own. */
219
238
  imageRotation?: number
220
- /** An image's adjustments, kept and saved; the canvas does not draw them. */
239
+ /** An image's adjustments, in Figma's plugin API units. */
221
240
  filters?: ImageFilters
222
241
  sourceNodeId?: string
223
242
  scale?: number
@@ -279,7 +298,7 @@ export interface Stroke extends Fill {
279
298
  dashPattern?: number[]
280
299
  }
281
300
 
282
- export type Effect = ShadowEffect | ShaderEffect
301
+ export type Effect = ShadowEffect | ShaderEffect | NoiseEffect | TextureEffect
283
302
 
284
303
  export interface ShadowEffect {
285
304
  type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'
@@ -292,6 +311,50 @@ export interface ShadowEffect {
292
311
  showShadowBehindNode?: boolean
293
312
  }
294
313
 
314
+ /**
315
+ * A Noise effect's grain, in Figma's plugin terms: `MONOTONE` grains in the effect's colour,
316
+ * `DUOTONE` in it and `secondaryColor`, `MULTITONE` in many colours at `opacity`. `noiseSize` is a
317
+ * grain's size in px, which Figma keeps within 0 to 100, and `density` how much of the layer the
318
+ * grains cover, 0 to 1. `seed` picks the pattern; Figma's plugin API neither shows nor sets it.
319
+ */
320
+ export interface NoiseEffectParams {
321
+ noiseType: NoiseType
322
+ noiseSize: Vector
323
+ density: number
324
+ secondaryColor?: Color
325
+ opacity?: number
326
+ seed?: number
327
+ }
328
+
329
+ /**
330
+ * A Texture effect's grain, which roughens the layer's edges: `noiseSize` is the grain's size in
331
+ * px, within 0 to 100 as Figma keeps it, and `clipToShape` keeps the roughened layer inside its
332
+ * own outline. The effect's `radius` is how far the grain moves the edges. `.fig` files name the
333
+ * effect `GRAIN`.
334
+ */
335
+ export interface TextureEffectParams {
336
+ noiseSize: Vector
337
+ clipToShape: boolean
338
+ seed?: number
339
+ }
340
+
341
+ export interface NoiseEffect {
342
+ type: 'NOISE'
343
+ color: Color
344
+ visible: boolean
345
+ blendMode?: BlendMode
346
+ noise: NoiseEffectParams
347
+ }
348
+
349
+ export interface TextureEffect {
350
+ type: 'TEXTURE'
351
+ color: Color
352
+ radius: number
353
+ visible: boolean
354
+ blendMode?: BlendMode
355
+ texture: TextureEffectParams
356
+ }
357
+
295
358
  /** A layer post-processed by shader code the user wrote; the layer is the `pencil:object` sample. */
296
359
  export interface ShaderEffect {
297
360
  type: 'SHADER'
@@ -667,17 +730,47 @@ export interface CommentThread {
667
730
  replies: CommentReply[]
668
731
  }
669
732
 
670
- /** How a prototype reaction starts, as `.fig` keeps `PrototypeEvent.interactionType`. */
671
- export type PrototypeTriggerType = 'ON_CLICK' | 'AFTER_TIMEOUT'
733
+ /**
734
+ * How a prototype reaction starts, as `.fig` keeps `PrototypeEvent.interactionType`: a click, the
735
+ * pointer held over the layer (`ON_HOVER`, While hovering) or pressed on it (`ON_PRESS`, While
736
+ * pressing), which undo themselves when it leaves or lifts, the pointer entering or leaving it,
737
+ * or a delay.
738
+ */
739
+ export type PrototypeTriggerType =
740
+ | 'ON_CLICK'
741
+ | 'ON_HOVER'
742
+ | 'ON_PRESS'
743
+ | 'MOUSE_ENTER'
744
+ | 'MOUSE_LEAVE'
745
+ | 'AFTER_TIMEOUT'
672
746
 
673
747
  /** What a reaction does, as `.fig` keeps `ConnectionType` on `PrototypeAction`. */
674
748
  export type PrototypeActionType = 'NODE' | 'BACK' | 'CLOSE'
675
749
 
676
- /** Whether an action moves to a frame or opens it over the screen, as `NavigationType`. */
677
- export type PrototypeNavigationType = 'NAVIGATE' | 'OVERLAY'
750
+ /**
751
+ * What a node action does with its node, as `NavigationType`: move to a frame, open it over the
752
+ * screen, show another variant of the instance's set (Figma's Change to, `SWAP_STATE` in `.fig`),
753
+ * or scroll the layer into view.
754
+ */
755
+ export type PrototypeNavigationType = 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO'
756
+
757
+ /** Which way a frame's content scrolls in play, as Figma's `overflowDirection`. */
758
+ export type OverflowDirection = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'BOTH'
678
759
 
679
- /** How a reaction animates between frames, as `TransitionType` keeps them. */
680
- export type PrototypeTransitionType = 'INSTANT' | 'DISSOLVE'
760
+ /**
761
+ * How a layer moves when its parent frame scrolls in play: with the content, fixed in the frame,
762
+ * or scrolled until it reaches the frame's top/left edge and then stuck there.
763
+ */
764
+ export type ScrollBehavior = 'SCROLLS' | 'FIXED' | 'STICKY_SCROLLS'
765
+
766
+ /**
767
+ * How a reaction animates between frames, as `TransitionType` keeps them: a cut, a crossfade, or
768
+ * Smart animate, which moves the layers two frames share by name and fades the rest.
769
+ */
770
+ export type PrototypeTransitionType = 'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE'
771
+
772
+ /** How a transition eases, by the names Figma's plugin API gives its presets. */
773
+ export type PrototypeEasingType = 'LINEAR' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_AND_OUT'
681
774
 
682
775
  /** Where an overlay sits over the screen, as `OverlayPositionType`. */
683
776
  export type PrototypeOverlayPositionType =
@@ -689,16 +782,21 @@ export type PrototypeOverlayPositionType =
689
782
  | 'BOTTOM_CENTER'
690
783
  | 'BOTTOM_RIGHT'
691
784
 
692
- /** How a reaction animates, and how long it takes in seconds. */
785
+ /** How a reaction animates, how long it takes in seconds, and how it eases. */
693
786
  export interface PrototypeTransition {
694
787
  type: PrototypeTransitionType
695
788
  duration: number
789
+ /** Absent eases as Figma's default does, `DEFAULT_PROTOTYPE_EASING`. */
790
+ easing?: PrototypeEasingType
696
791
  }
697
792
 
698
- /** A reaction's move to another frame, or the overlay it opens. */
793
+ /** A reaction's move to another frame, the overlay it opens, the variant or layer it shows. */
699
794
  export interface PrototypeNodeAction {
700
795
  type: 'NODE'
701
- /** The frame the action shows; `null` keeps the connection when its target is gone. */
796
+ /**
797
+ * The frame the action shows, the variant a Change to shows, or the layer a Scroll to brings
798
+ * into view; `null` keeps the connection when its target is gone.
799
+ */
702
800
  nodeId: string | null
703
801
  navigation: PrototypeNavigationType
704
802
  transition: PrototypeTransition
@@ -718,10 +816,10 @@ export interface PrototypeCloseAction {
718
816
 
719
817
  export type PrototypeAction = PrototypeNodeAction | PrototypeBackAction | PrototypeCloseAction
720
818
 
721
- /** What starts a reaction, and after how long an AFTER_TIMEOUT does. */
819
+ /** What starts a reaction, and after how long an AFTER_TIMEOUT or mouse enter or leave does. */
722
820
  export interface PrototypeTrigger {
723
821
  type: PrototypeTriggerType
724
- /** AFTER_TIMEOUT only: the seconds before the reaction runs. */
822
+ /** AFTER_TIMEOUT, MOUSE_ENTER and MOUSE_LEAVE: the seconds before the reaction runs. */
725
823
  delay: number
726
824
  }
727
825
 
@@ -775,6 +873,10 @@ export interface SceneNode {
775
873
  visible: boolean
776
874
  locked: boolean
777
875
  clipsContent: boolean
876
+ /** Which way the frame's content scrolls in play; a nested frame scrolls only while it clips. */
877
+ overflowDirection: OverflowDirection
878
+ /** How this layer moves while its parent frame scrolls in play. */
879
+ scrollBehavior: ScrollBehavior
778
880
 
779
881
  blendMode: BlendMode
780
882