@open-pencil/scene-graph 0.15.1 → 0.16.0-beta.1

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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +596 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +573 -521
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2021 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1711 -661
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +343 -55
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. package/src/instance-overrides.test.ts +0 -67
package/src/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /* eslint-disable max-lines -- scene node contracts are kept together as the public graph type surface */
2
2
 
3
+ import type { ExportFormatId } from './export-format'
3
4
  import type { CanvasGuide } from './guides'
4
5
  import type { InstanceOverrideState } from './instance-overrides'
5
6
  import type { Color, Matrix, Rect, Vector } from './primitives'
@@ -32,6 +33,14 @@ export type SceneGraphEventHandlers = Partial<{
32
33
  ) => void
33
34
  }>
34
35
 
36
+ /** Hears about nodes as an edit adds and changes them, synchronously and before each change. */
37
+ export interface NodeChangeObserver {
38
+ /** A node is about to change and is still as it was. */
39
+ before: (node: SceneNode) => void
40
+ /** A node was just added. */
41
+ created: (node: SceneNode) => void
42
+ }
43
+
35
44
  export type DocumentColorSpace = 'srgb' | 'display-p3'
36
45
 
37
46
  export interface FigmaSourcePayload {
@@ -205,11 +214,9 @@ export interface SharedStyle {
205
214
  type: SharedStyleType
206
215
  }
207
216
 
208
- export interface Stroke {
209
- color: Color
217
+ /** A stroke is a paint with the geometry that decides where it is drawn. */
218
+ export interface Stroke extends Fill {
210
219
  weight: number
211
- opacity: number
212
- visible: boolean
213
220
  align: 'INSIDE' | 'CENTER' | 'OUTSIDE'
214
221
  cap?: StrokeCap
215
222
  join?: StrokeJoin
@@ -236,6 +243,22 @@ export type TextDecorationStyle = 'SOLID' | 'DOTTED' | 'WAVY'
236
243
  export type LeadingTrim = 'NONE' | 'CAP_HEIGHT'
237
244
  export type TextDirection = 'AUTO' | 'LTR' | 'RTL'
238
245
  export type LayoutDirection = 'AUTO' | 'LTR' | 'RTL'
246
+ /** Whether a paragraph is an item of a numbered list, a bulleted list, or no list. */
247
+ export type TextListType = 'NONE' | 'ORDERED' | 'UNORDERED'
248
+
249
+ /** How one paragraph of a text node (a line ending at a newline) sits in a list. */
250
+ /** Spacing a text sets for all its paragraphs and a paragraph can set for itself. */
251
+ export type TextParagraphSpacingField = 'listSpacing' | 'paragraphSpacing' | 'paragraphIndent'
252
+
253
+ export interface TextParagraphStyle {
254
+ listType: TextListType
255
+ /** Nesting level: 1–5 for list items; kept but not drawn for plain paragraphs. */
256
+ indentation: number
257
+ /** This paragraph's own spacing, in place of the text's; absent ones follow the text. */
258
+ listSpacing?: number
259
+ paragraphSpacing?: number
260
+ paragraphIndent?: number
261
+ }
239
262
 
240
263
  export interface FontVariation {
241
264
  axis: string
@@ -279,7 +302,10 @@ export interface ArcData {
279
302
  }
280
303
 
281
304
  export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'GRID'
305
+ /** A node's sizing along one axis; fill is stored on the child, see `layoutSizing`. */
282
306
  export type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'
307
+ /** Whether an auto-layout frame keeps its size or hugs its children along one of its axes. */
308
+ export type AxisSizingMode = 'FIXED' | 'HUG'
283
309
 
284
310
  export type GridTrackSizing = 'FIXED' | 'FR' | 'AUTO'
285
311
 
@@ -305,8 +331,6 @@ export interface PluginDataEntry {
305
331
  value: string
306
332
  }
307
333
 
308
- export type ExportFormatId = 'png' | 'jpg' | 'webp' | 'svg' | 'pdf'
309
-
310
334
  export interface ExportSetting {
311
335
  scale: number
312
336
  format: ExportFormatId
@@ -332,12 +356,19 @@ export interface TextPathData {
332
356
  }
333
357
 
334
358
  export interface DerivedTextGlyph {
359
+ /** UTF-16 source-text cluster start, when supplied by the shaping source. */
360
+ firstCharacter?: number
335
361
  commandsBlob: Uint8Array
336
362
  x: number
337
363
  y: number
338
364
  fontSize: number
339
365
  /** Figma Glyph.rotation — radians, not degrees. Zero for axis-aligned text. */
340
366
  rotation?: number
367
+ /**
368
+ * Horizontal advance in pixels at `fontSize`, before `scaleX`, when the shaping source gave
369
+ * one; where the glyph ends, so decorations stop at the text rather than the layer's edge.
370
+ */
371
+ advance?: number
341
372
  /**
342
373
  * Accumulated non-uniform resize scale (default 1). Paint order is
343
374
  * translate → scale(scaleX,Y) → rotate → scale(fontSize,-fontSize) so
@@ -405,6 +436,56 @@ export interface EnabledLibraryBinding {
405
436
  enabled: boolean
406
437
  }
407
438
 
439
+ /** The library a document publishes as. */
440
+ export interface SourceLibraryPublication {
441
+ libraryId: string
442
+ revisionId: string
443
+ name: string
444
+ catalogSource?: string
445
+ }
446
+
447
+ /** A reply in a canvas comment thread. */
448
+ export interface CommentReply {
449
+ id: string
450
+ author: string
451
+ /** The author's collaboration color when they wrote it, for their avatar. */
452
+ authorColor?: Color
453
+ /** Markdown: bold, italic, strikethrough, links and lists. */
454
+ text: string
455
+ createdAt: string
456
+ deleted?: boolean
457
+ }
458
+
459
+ /** A canvas comment thread, kept in the document's root plugin data. */
460
+ export interface CommentThread {
461
+ id: string
462
+ pageId: string
463
+ /** Page name when the pin was placed, for readers of the raw data. */
464
+ pageName?: string
465
+ /** Top-level layer under the pin; the pin follows it when it moves. */
466
+ nodeId?: string | null
467
+ nodeName?: string | null
468
+ /** Offset from the layer's top-left corner, in canvas units. */
469
+ offsetX?: number
470
+ offsetY?: number
471
+ /** Canvas position when the pin was last saved; used when the layer is gone. */
472
+ x: number
473
+ y: number
474
+ author: string
475
+ /** The author's collaboration color when they wrote it, for their avatar. */
476
+ authorColor?: Color
477
+ /** Markdown: bold, italic, strikethrough, links and lists. */
478
+ text: string
479
+ createdAt: string
480
+ /** Bumped on every change. */
481
+ updatedAt: string
482
+ resolved: boolean
483
+ resolvedAt?: string | null
484
+ /** Deleted threads stay as tombstones so a stale copy cannot bring them back. */
485
+ deleted?: boolean
486
+ replies: CommentReply[]
487
+ }
488
+
408
489
  export interface SceneNode {
409
490
  id: string
410
491
  type: NodeType
@@ -469,6 +550,19 @@ export interface SceneNode {
469
550
  lineHeight: number | null
470
551
  letterSpacing: number
471
552
  maxLines: number | null
553
+ /**
554
+ * One entry per paragraph of `text`, in order. Missing entries are plain paragraphs, so text
555
+ * without lists keeps this empty.
556
+ */
557
+ textParagraphs: TextParagraphStyle[]
558
+ /** Space after a list item followed by another; a paragraph's own value comes first. */
559
+ listSpacing: number
560
+ /** Space after a paragraph other than between two list items. */
561
+ paragraphSpacing: number
562
+ /** Indent of the first line of each plain paragraph. */
563
+ paragraphIndent: number
564
+ /** Whether list markers hang outside the text box instead of indenting the items. */
565
+ hangingList: boolean
472
566
 
473
567
  styleRuns: StyleRun[]
474
568
  fontVariations: FontVariation[]
@@ -482,8 +576,8 @@ export interface SceneNode {
482
576
  layoutWrap: LayoutWrap
483
577
  primaryAxisAlign: LayoutAlign
484
578
  counterAxisAlign: LayoutCounterAlign
485
- primaryAxisSizing: LayoutSizing
486
- counterAxisSizing: LayoutSizing
579
+ primaryAxisSizing: AxisSizingMode
580
+ counterAxisSizing: AxisSizingMode
487
581
  itemSpacing: number
488
582
  counterAxisSpacing: number
489
583
  paddingTop: number
@@ -497,7 +591,7 @@ export interface SceneNode {
497
591
 
498
592
  vectorNetwork: VectorNetwork | null
499
593
  handleMirroring: HandleMirroring
500
- booleanOperation?: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'
594
+ booleanOperation: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE' | undefined
501
595
  fillGeometry: GeometryPath[]
502
596
  strokeGeometry: GeometryPath[]
503
597
 
@@ -513,12 +607,25 @@ export interface SceneNode {
513
607
  borderLeftWeight: number
514
608
  independentStrokeWeights: boolean
515
609
 
610
+ /**
611
+ * The weight and alignment a node keeps for its strokes, as Figma keeps them on the node: they
612
+ * last while it has no strokes, and a stroke added to it takes them. Each stroke still carries
613
+ * its own `weight` and `align`, which win while the node has strokes.
614
+ */
615
+ strokeWeight: number
616
+ strokeAlign: Stroke['align']
617
+
516
618
  strokeMiterLimit: number
517
619
 
518
620
  minWidth: number | null
519
621
  maxWidth: number | null
520
622
  minHeight: number | null
521
623
  maxHeight: number | null
624
+ /**
625
+ * The size whose proportions the layer keeps, as Figma stores it: the width and height it had
626
+ * when the ratio was locked, not a reduced ratio. Null leaves the proportions free.
627
+ */
628
+ targetAspectRatio: Vector | null
522
629
 
523
630
  isMask: boolean
524
631
  maskType: MaskType
@@ -556,11 +663,22 @@ export interface SceneNode {
556
663
  librarySource: LibraryAssetSource | null
557
664
  isPublishable: boolean
558
665
  isSymbolPublishable: boolean
666
+ /**
667
+ * On an instance inside a component: its properties show on instances of that component,
668
+ * as Figma's `isExposedInstance`.
669
+ */
670
+ isExposedInstance: boolean
559
671
  symbolDescription: string
560
672
  symbolLinks: SymbolLink[]
561
673
  variantPropSpecs: VariantPropSpec[]
562
674
 
563
675
  boundVariables: Record<string, string>
676
+ /** Multipliers from bound numeric values to this occurrence's scene units. */
677
+ variableBindingScales: Partial<Record<string, number>>
678
+ /** Numeric units for new declarations owned by this node's occurrence scope. */
679
+ variableAssignmentScales: Partial<Record<string, number>>
680
+ /** Explicit coordinate scale relative to the containing component definition. */
681
+ componentScale: number
564
682
  variableModes: VariableModeMap
565
683
  exportSettings: ExportSetting[]
566
684
 
@@ -580,15 +698,30 @@ export interface SceneNode {
580
698
  textPathBox: Rect | null
581
699
  }
582
700
 
583
- export type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP'
701
+ export type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP' | 'SLOT'
584
702
 
585
- export type ComponentPropertyReferenceField = 'VISIBLE' | 'TEXT' | 'INSTANCE_SWAP'
703
+ /** `SLOT_CONTENT` marks a frame whose children are the slot's content. */
704
+ export type ComponentPropertyReferenceField = 'VISIBLE' | 'TEXT' | 'INSTANCE_SWAP' | 'SLOT_CONTENT'
586
705
 
587
706
  export interface ComponentPropertyReference {
588
707
  propertyId: string
589
708
  field: ComponentPropertyReferenceField
590
709
  }
591
710
 
711
+ /** Guidance for a slot property; Figma reports a breach but still accepts the content. */
712
+ export interface SlotSettings {
713
+ minChildren?: number
714
+ maxChildren?: number
715
+ allowPreferredValuesOnly: boolean
716
+ displayEmptyByDefault: boolean
717
+ /** Content added to the slot fills its counter axis. */
718
+ stretchChildOnInsert: boolean
719
+ }
720
+
721
+ /**
722
+ * For a `SLOT` property, an instance assignment (whatever its value) means the instance owns
723
+ * that slot's content: the slot frame's children in the instance, which component sync keeps.
724
+ */
592
725
  export interface ComponentPropertyDefinition {
593
726
  id: string
594
727
  name: string
@@ -596,12 +729,58 @@ export interface ComponentPropertyDefinition {
596
729
  defaultValue: string
597
730
  variantOptions?: string[]
598
731
  preferredValues?: string[]
732
+ description?: string
733
+ slotSettings?: SlotSettings
599
734
  }
600
735
 
601
736
  export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'
602
737
  export type VariableValue = Color | number | string | boolean | { aliasId: string }
603
738
  export type VariableModeMap = Record<string, string>
604
739
 
740
+ /** Property pickers a variable is offered in, as Figma names them. */
741
+ export const VARIABLE_SCOPES = [
742
+ 'ALL_SCOPES',
743
+ 'TEXT_CONTENT',
744
+ 'CORNER_RADIUS',
745
+ 'WIDTH_HEIGHT',
746
+ 'GAP',
747
+ 'ALL_FILLS',
748
+ 'FRAME_FILL',
749
+ 'SHAPE_FILL',
750
+ 'TEXT_FILL',
751
+ 'STROKE',
752
+ 'STROKE_FLOAT',
753
+ 'EFFECT_FLOAT',
754
+ 'EFFECT_COLOR',
755
+ 'OPACITY',
756
+ 'FONT_STYLE',
757
+ 'FONT_FAMILY',
758
+ 'FONT_SIZE',
759
+ 'LINE_HEIGHT',
760
+ 'LETTER_SPACING',
761
+ 'PARAGRAPH_SPACING',
762
+ 'PARAGRAPH_INDENT',
763
+ 'FONT_VARIATIONS',
764
+ 'TRANSFORM'
765
+ ] as const
766
+ export type VariableScope = (typeof VARIABLE_SCOPES)[number]
767
+
768
+ export const CODE_SYNTAX_PLATFORMS = ['WEB', 'ANDROID', 'iOS'] as const
769
+ export type CodeSyntaxPlatform = (typeof CODE_SYNTAX_PLATFORMS)[number]
770
+
771
+ /**
772
+ * The CSS unit a numeric token is written in. Lengths (`px`, `rem`) stay in canvas pixels in
773
+ * the document and convert only when written as CSS; the other units store the number as written.
774
+ */
775
+ export const TOKEN_UNITS = ['none', 'px', 'rem', '%', 'ms', 's', 'deg'] as const
776
+ export type TokenUnit = (typeof TOKEN_UNITS)[number]
777
+
778
+ /** A mode value authored as raw CSS. `resolved` is the number the canvas drew for it. */
779
+ export interface TokenExpression {
780
+ css: string
781
+ resolved: number
782
+ }
783
+
605
784
  export interface Variable {
606
785
  id: string
607
786
  name: string
@@ -610,6 +789,18 @@ export interface Variable {
610
789
  valuesByMode: Record<string, VariableValue>
611
790
  description: string
612
791
  hiddenFromPublishing: boolean
792
+ /** Absent means every scope. */
793
+ scopes?: VariableScope[]
794
+ /**
795
+ * Per-platform code snippets, as Figma's Dev Mode shows them. A `WEB` snippet of `--x` or
796
+ * `var(--x)` names the token's CSS custom property; otherwise the name is derived.
797
+ */
798
+ codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>
799
+ /** FLOAT only. Absent means inferred when written as CSS. */
800
+ unit?: TokenUnit
801
+ /** Raw CSS by mode id, for values a number cannot express (`clamp()`, `calc()`). */
802
+ expressions?: Record<string, TokenExpression>
803
+ pluginData?: PluginDataEntry[]
613
804
  /** Published library key (from NodeChange.key). Used for assetRef resolution in colorVar. */
614
805
  key?: string
615
806
  /** Published library version (from NodeChange.version). Used for assetRef resolution in colorVar. */
@@ -624,12 +815,31 @@ export type NumericNodeProperty = {
624
815
  export interface VariableCollectionMode {
625
816
  modeId: string
626
817
  name: string
818
+ /**
819
+ * Where the mode applies in CSS: a selector (`[data-theme="dark"]`, `.compact`) or an
820
+ * at-rule prelude (`@media (max-width: 640px)`). Absent means the default for its axis.
821
+ */
822
+ condition?: string
627
823
  }
628
824
 
629
825
  export interface VariableCollection {
630
826
  id: string
631
827
  name: string
828
+ /** The default mode comes first, as in Figma. */
632
829
  modes: VariableCollectionMode[]
633
830
  defaultModeId: string
634
831
  variableIds: string[]
832
+ /**
833
+ * The attribute that switches a mode with no condition of its own, `data-theme` for
834
+ * `[data-theme="dark"]`. Absent means one named after the collection.
835
+ */
836
+ modeAttribute?: string
837
+ pluginData?: PluginDataEntry[]
838
+ }
839
+
840
+ /** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */
841
+ export const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\w-]*$/
842
+
843
+ export function isModeAttributeName(name: string): boolean {
844
+ return name.length <= 100 && MODE_ATTRIBUTE_PATTERN.test(name)
635
845
  }
package/src/undo.ts CHANGED
@@ -17,12 +17,14 @@ interface UndoBatch {
17
17
  coalesceKey?: string
18
18
  }
19
19
 
20
- const DEFAULT_HISTORY_LIMIT = 200
20
+ /** How many edits undo keeps by default. */
21
+ export const DEFAULT_HISTORY_LIMIT = 200
21
22
 
22
23
  export class UndoManager {
23
24
  private undoStack: UndoEntry[] = []
24
25
  private redoStack: UndoEntry[] = []
25
26
  private batches: UndoBatch[] = []
27
+ private readonly settlers = new Set<() => void>()
26
28
  private readonly limit: number
27
29
  private readonly onChange: (() => void) | undefined
28
30
 
@@ -53,7 +55,31 @@ export class UndoManager {
53
55
  this.pushUndoEntry(entry)
54
56
  }
55
57
 
58
+ /**
59
+ * Records an entry as a step of its own, outside the batches being built, such as an agent's
60
+ * edit made while a colour picker is open. Batches settle first, so the step follows the
61
+ * changes they hold so far.
62
+ */
63
+ pushStep(entry: UndoEntry): void {
64
+ this.settle()
65
+ this.pushUndoEntry(entry)
66
+ }
67
+
68
+ /**
69
+ * Registers a hook that commits an edit still being coalesced, such as a run of picker changes.
70
+ * Undo and redo run every hook first, so they act on the newest change.
71
+ */
72
+ onBeforeHistory(settle: () => void): () => void {
73
+ this.settlers.add(settle)
74
+ return () => this.settlers.delete(settle)
75
+ }
76
+
77
+ private settle() {
78
+ for (const settle of this.settlers) settle()
79
+ }
80
+
56
81
  undo(): string | null {
82
+ this.settle()
57
83
  const entry = this.undoStack.pop()
58
84
  if (!entry) return null
59
85
  entry.inverse()
@@ -63,6 +89,7 @@ export class UndoManager {
63
89
  }
64
90
 
65
91
  redo(): string | null {
92
+ this.settle()
66
93
  const entry = this.redoStack.pop()
67
94
  if (!entry) return null
68
95
  entry.forward()
@@ -119,14 +146,39 @@ export class UndoManager {
119
146
  return this.batches.length > 0
120
147
  }
121
148
 
149
+ /** Committed history, or changes in an open batch that a settling hook commits first. */
122
150
  get canUndo(): boolean {
123
- return this.undoStack.length > 0
151
+ if (this.undoStack.length > 0) return true
152
+ return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0)
124
153
  }
125
154
 
126
155
  get canRedo(): boolean {
127
156
  return this.redoStack.length > 0
128
157
  }
129
158
 
159
+ /**
160
+ * The entry `depth` steps below the top of the undo stack, so a caller that pushed entries
161
+ * can tell whether they are still the most recent ones.
162
+ */
163
+ peekUndo(depth = 0): UndoEntry | undefined {
164
+ return this.undoStack.at(-1 - depth)
165
+ }
166
+
167
+ /** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */
168
+ peekRedo(depth = 0): UndoEntry | undefined {
169
+ return this.redoStack.at(-1 - depth)
170
+ }
171
+
172
+ /**
173
+ * Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it
174
+ * left the history, trimmed or dropped when an edit cleared Redo.
175
+ */
176
+ stateOf(entry: UndoEntry): 'applied' | 'undone' | null {
177
+ if (this.undoStack.includes(entry)) return 'applied'
178
+ if (this.redoStack.includes(entry)) return 'undone'
179
+ return null
180
+ }
181
+
130
182
  get undoLabel(): string | null {
131
183
  return this.undoStack.at(-1)?.label ?? null
132
184
  }
@@ -0,0 +1,186 @@
1
+ import { copyFills, copyStrokes } from '../copy'
2
+ import type { SceneGraph } from '../index'
3
+ import { hasInstanceOverride } from '../instances'
4
+ import type { Color } from '../primitives'
5
+ import type { Fill, SceneNode, Stroke } from '../types'
6
+ import type { VariableModeFallback } from '../variables'
7
+ import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
8
+ export { isNumericVariableBindingField } from './fields'
9
+
10
+ /** New declarations belong to the outermost occurrence, bounded by a component definition. */
11
+ export function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {
12
+ let owner = node
13
+ let current: SceneNode | undefined = node
14
+ while (current) {
15
+ if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break
16
+ if (current.type === 'INSTANCE') owner = current
17
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
18
+ }
19
+ return owner
20
+ }
21
+
22
+ export function assignVariableBindingUnits(
23
+ graph: SceneGraph,
24
+ node: SceneNode,
25
+ field: string
26
+ ): void {
27
+ if (!isNumericVariableBindingField(field)) return
28
+ const owner = variableBindingOwner(graph, node)
29
+ node.variableBindingScales = {
30
+ ...node.variableBindingScales,
31
+ [field]: owner.variableAssignmentScales[field] ?? 1
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
37
+ * whose stored value differs. A width or height an instance overrides keeps its own value.
38
+ */
39
+ export function resolvedNumericBindings(
40
+ graph: SceneGraph,
41
+ node: SceneNode,
42
+ fallback: VariableModeFallback = 'active'
43
+ ): Partial<SceneNode> {
44
+ const updates: Partial<SceneNode> = {}
45
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
46
+ if (!NUMERIC_FIELDS.has(field)) continue
47
+ if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))
48
+ continue
49
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
50
+ if (value === undefined || !Number.isFinite(value)) continue
51
+ const scale = node.variableBindingScales[field] ?? 1
52
+ const effective = value * scale
53
+ if (!Number.isFinite(effective)) continue
54
+ const next = field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective
55
+ if (node[field as keyof SceneNode] !== next) Object.assign(updates, { [field]: next })
56
+ }
57
+ return updates
58
+ }
59
+
60
+ /**
61
+ * The text and visibility a node's string and boolean bindings resolve to in its mode, for the
62
+ * fields whose stored value differs. Text or visibility an instance overrides, which typing in a
63
+ * layer or toggling its eye records, keeps its own value, as an overridden width or height does.
64
+ * A bound font family is left as stored: changing it needs the font loaded, which resolving a
65
+ * binding cannot do.
66
+ */
67
+ export function resolvedValueBindings(
68
+ graph: SceneGraph,
69
+ node: SceneNode,
70
+ fallback: VariableModeFallback = 'active'
71
+ ): Partial<SceneNode> {
72
+ const updates: Partial<SceneNode> = {}
73
+ const resolve = (field: 'text' | 'visible') => {
74
+ const variableId = node.boundVariables[field]
75
+ if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefined
76
+ return graph.resolveVariableForNode(node.id, variableId, fallback)
77
+ }
78
+ const text = node.type === 'TEXT' ? resolve('text') : undefined
79
+ if (typeof text === 'string' && text !== node.text) updates.text = text
80
+ const visible = resolve('visible')
81
+ if (typeof visible === 'boolean' && visible !== node.visible) updates.visible = visible
82
+ return updates
83
+ }
84
+
85
+ /**
86
+ * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
87
+ * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
88
+ */
89
+ function applyBoundColor(paint: Fill | Stroke, color: Color): void {
90
+ paint.color = { ...color, a: 1 }
91
+ paint.opacity = color.a
92
+ }
93
+
94
+ /** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */
95
+ export function resolvedPaintBindings(
96
+ graph: SceneGraph,
97
+ node: SceneNode,
98
+ fallback: VariableModeFallback = 'active'
99
+ ): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {
100
+ // Most nodes bind nothing, so no copy is made until a paint binding is actually found.
101
+ const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}
102
+ for (const field in node.boundVariables) {
103
+ if (!field.endsWith('/color')) continue
104
+ const match = /^(fills|strokes)\/(\d+)\/color$/.exec(field)
105
+ if (!match) continue
106
+ const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)
107
+ const index = Number(match[2])
108
+ if (!color) continue
109
+ if (match[1] === 'fills') {
110
+ if (!node.fills[index]) continue
111
+ changes.fills ??= copyFills(node.fills)
112
+ applyBoundColor(changes.fills[index], color)
113
+ } else {
114
+ if (!node.strokes[index]) continue
115
+ changes.strokes ??= copyStrokes(node.strokes)
116
+ applyBoundColor(changes.strokes[index], color)
117
+ }
118
+ }
119
+ return changes
120
+ }
121
+
122
+ /**
123
+ * The layers a reconcile looks at: those bound to these variables, directly or through a variable
124
+ * aliasing them, or the layers in these subtrees. Without a scope, every layer.
125
+ */
126
+ export type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }
127
+
128
+ /** These variables and every variable that aliases one of them, at any depth and in any mode. */
129
+ export function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {
130
+ const found = new Set(ids)
131
+ let grew = true
132
+ while (grew) {
133
+ grew = false
134
+ for (const variable of graph.variables.values()) {
135
+ if (found.has(variable.id)) continue
136
+ const aliases = Object.values(variable.valuesByMode).some(
137
+ (value) => typeof value === 'object' && 'aliasId' in value && found.has(value.aliasId)
138
+ )
139
+ if (aliases) {
140
+ found.add(variable.id)
141
+ grew = true
142
+ }
143
+ }
144
+ }
145
+ return found
146
+ }
147
+
148
+ function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {
149
+ const nodes: SceneNode[] = []
150
+ const pending = [...roots]
151
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
152
+ const node = graph.getNode(id)
153
+ if (!node) continue
154
+ nodes.push(node)
155
+ pending.push(...node.childIds)
156
+ }
157
+ return nodes
158
+ }
159
+
160
+ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {
161
+ if (!scope) return graph.getAllNodes()
162
+ if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)
163
+ const variables = variablesResolvingThrough(graph, scope.variables)
164
+ return [...graph.getAllNodes()].filter((node) =>
165
+ Object.values(node.boundVariables).some((id) => variables.has(id))
166
+ )
167
+ }
168
+
169
+ /**
170
+ * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
171
+ * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
172
+ * values differ from their bindings elsewhere in the document are left as saved.
173
+ */
174
+ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {
175
+ const changed: string[] = []
176
+ for (const node of scopedNodes(graph, scope)) {
177
+ const updates = {
178
+ ...resolvedNumericBindings(graph, node),
179
+ ...resolvedValueBindings(graph, node)
180
+ }
181
+ if (Object.keys(updates).length === 0) continue
182
+ graph.updateNode(node.id, updates)
183
+ changed.push(node.id)
184
+ }
185
+ return changed
186
+ }