@pairdraw/scene-graph 0.20.0 → 0.21.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 (145) hide show
  1. package/dist/color/index.d.ts +28 -7
  2. package/dist/color/index.d.ts.map +1 -1
  3. package/dist/color/index.js +40 -15
  4. package/dist/color/index.js.map +1 -1
  5. package/dist/color/management.d.ts +19 -6
  6. package/dist/color/management.d.ts.map +1 -1
  7. package/dist/color/management.js +56 -1
  8. package/dist/color/management.js.map +1 -1
  9. package/dist/color/profile.d.ts +32 -0
  10. package/dist/color/profile.d.ts.map +1 -0
  11. package/dist/color/profile.js +140 -0
  12. package/dist/color/profile.js.map +1 -0
  13. package/dist/comments/index.d.ts +2 -2
  14. package/dist/comments/index.js +2 -2
  15. package/dist/comments/merge.d.ts.map +1 -1
  16. package/dist/comments/merge.js +1 -0
  17. package/dist/comments/merge.js.map +1 -1
  18. package/dist/comments/schema.d.ts +3 -1
  19. package/dist/comments/schema.d.ts.map +1 -1
  20. package/dist/comments/schema.js +19 -2
  21. package/dist/comments/schema.js.map +1 -1
  22. package/dist/comments/threads.d.ts +3 -1
  23. package/dist/comments/threads.d.ts.map +1 -1
  24. package/dist/comments/threads.js +2 -1
  25. package/dist/comments/threads.js.map +1 -1
  26. package/dist/components/properties.d.ts.map +1 -1
  27. package/dist/components/properties.js +7 -7
  28. package/dist/components/properties.js.map +1 -1
  29. package/dist/css/shadows.d.ts +2 -2
  30. package/dist/css/shadows.d.ts.map +1 -1
  31. package/dist/css/shadows.js +4 -4
  32. package/dist/css/shadows.js.map +1 -1
  33. package/dist/css/values.d.ts +7 -2
  34. package/dist/css/values.d.ts.map +1 -1
  35. package/dist/css/values.js +8 -4
  36. package/dist/css/values.js.map +1 -1
  37. package/dist/empty-values.js +9 -0
  38. package/dist/empty-values.js.map +1 -1
  39. package/dist/graph.d.ts +4 -0
  40. package/dist/graph.d.ts.map +1 -1
  41. package/dist/graph.js +11 -2
  42. package/dist/graph.js.map +1 -1
  43. package/dist/images.d.ts +3 -2
  44. package/dist/images.d.ts.map +1 -1
  45. package/dist/images.js +18 -2
  46. package/dist/images.js.map +1 -1
  47. package/dist/index.d.ts +2 -2
  48. package/dist/instances/copies.js +2 -1
  49. package/dist/instances/copies.js.map +1 -1
  50. package/dist/instances/index.d.ts.map +1 -1
  51. package/dist/instances/index.js +12 -11
  52. package/dist/instances/index.js.map +1 -1
  53. package/dist/instances/overrides.d.ts +15 -1
  54. package/dist/instances/overrides.d.ts.map +1 -1
  55. package/dist/instances/overrides.js +37 -1
  56. package/dist/instances/overrides.js.map +1 -1
  57. package/dist/instances/swap-overrides.js +3 -3
  58. package/dist/instances/swap-overrides.js.map +1 -1
  59. package/dist/instances/sync.js +9 -7
  60. package/dist/instances/sync.js.map +1 -1
  61. package/dist/node-defaults.js +2 -2
  62. package/dist/node-defaults.js.map +1 -1
  63. package/dist/plugin-data/fields.d.ts +15 -0
  64. package/dist/plugin-data/fields.d.ts.map +1 -1
  65. package/dist/plugin-data/fields.js +15 -23
  66. package/dist/plugin-data/fields.js.map +1 -1
  67. package/dist/plugin-data/index.d.ts +2 -2
  68. package/dist/plugin-data/index.js +2 -2
  69. package/dist/plugin-data/schema.d.ts +6 -1
  70. package/dist/plugin-data/schema.d.ts.map +1 -1
  71. package/dist/plugin-data/schema.js +24 -1
  72. package/dist/plugin-data/schema.js.map +1 -1
  73. package/dist/shaders/animation.d.ts +21 -0
  74. package/dist/shaders/animation.d.ts.map +1 -0
  75. package/dist/shaders/animation.js +25 -0
  76. package/dist/shaders/animation.js.map +1 -0
  77. package/dist/shaders/index.d.ts +2 -1
  78. package/dist/shaders/index.js +2 -1
  79. package/dist/slots/content.d.ts.map +1 -1
  80. package/dist/slots/content.js +4 -4
  81. package/dist/slots/content.js.map +1 -1
  82. package/dist/statuses/index.d.ts +2 -2
  83. package/dist/statuses/index.js +2 -2
  84. package/dist/statuses/workflow.d.ts +3 -1
  85. package/dist/statuses/workflow.d.ts.map +1 -1
  86. package/dist/statuses/workflow.js +6 -2
  87. package/dist/statuses/workflow.js.map +1 -1
  88. package/dist/transfer/variables.d.ts.map +1 -1
  89. package/dist/transfer/variables.js +1 -1
  90. package/dist/transfer/variables.js.map +1 -1
  91. package/dist/types.d.ts +34 -2
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/types.js.map +1 -1
  94. package/dist/variables/bindings.d.ts +6 -5
  95. package/dist/variables/bindings.d.ts.map +1 -1
  96. package/dist/variables/bindings.js +24 -16
  97. package/dist/variables/bindings.js.map +1 -1
  98. package/dist/variables/formula/index.d.ts.map +1 -1
  99. package/dist/variables/formula/index.js +12 -6
  100. package/dist/variables/formula/index.js.map +1 -1
  101. package/dist/variables/index.d.ts +14 -1
  102. package/dist/variables/index.d.ts.map +1 -1
  103. package/dist/variables/index.js +38 -10
  104. package/dist/variables/index.js.map +1 -1
  105. package/dist/variables/paints.d.ts +9 -8
  106. package/dist/variables/paints.d.ts.map +1 -1
  107. package/dist/variables/paints.js +35 -26
  108. package/dist/variables/paints.js.map +1 -1
  109. package/dist/variables/resolver.d.ts +45 -0
  110. package/dist/variables/resolver.d.ts.map +1 -0
  111. package/dist/variables/resolver.js +106 -0
  112. package/dist/variables/resolver.js.map +1 -0
  113. package/package.json +1 -1
  114. package/src/color/index.ts +43 -9
  115. package/src/color/management.ts +54 -1
  116. package/src/color/profile.ts +131 -0
  117. package/src/comments/merge.ts +3 -0
  118. package/src/comments/schema.ts +32 -2
  119. package/src/comments/threads.ts +5 -2
  120. package/src/components/properties.ts +13 -7
  121. package/src/css/shadows.ts +8 -5
  122. package/src/css/values.ts +12 -5
  123. package/src/empty-values.ts +16 -0
  124. package/src/graph.ts +13 -1
  125. package/src/images.ts +27 -3
  126. package/src/instances/copies.ts +2 -1
  127. package/src/instances/index.ts +19 -11
  128. package/src/instances/overrides.ts +49 -0
  129. package/src/instances/swap-overrides.ts +3 -2
  130. package/src/instances/sync.ts +11 -7
  131. package/src/node-defaults.ts +2 -2
  132. package/src/plugin-data/fields.ts +16 -31
  133. package/src/plugin-data/index.ts +1 -0
  134. package/src/plugin-data/schema.ts +30 -0
  135. package/src/shaders/animation.ts +39 -0
  136. package/src/shaders/index.ts +1 -0
  137. package/src/slots/content.ts +8 -4
  138. package/src/statuses/workflow.ts +6 -4
  139. package/src/transfer/variables.ts +2 -1
  140. package/src/types.ts +30 -1
  141. package/src/variables/bindings.ts +35 -18
  142. package/src/variables/formula/index.ts +19 -18
  143. package/src/variables/index.ts +49 -10
  144. package/src/variables/paints.ts +64 -29
  145. package/src/variables/resolver.ts +178 -0
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/* eslint-disable max-lines -- scene node contracts are kept together as the public graph type surface */\n\nimport type { ExportFormatId } from './export-format'\nimport type { CanvasGuide } from './guides'\nimport type { InstanceOverrideState } from './instances/overrides'\nimport type { Color, Matrix, Rect, Vector } from './primitives'\nimport type { ShaderUniformValue } from './shaders/schema'\nimport type { ShapeWithTextType } from './shape-with-text/kinds'\n\nexport interface SceneGraphEvents {\n 'node:created': (node: SceneNode) => void\n 'node:updated': (id: string, changes: Partial<SceneNode>) => void\n 'node:previewUpdated': (id: string, changes: Partial<SceneNode>) => void\n 'node:deleted': (id: string, parentId: string | null) => void\n 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void\n 'node:reordered': (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}\n\nexport type SceneGraphEventHandlers = Partial<{\n created: (node: SceneNode) => void\n updated: (id: string, changes: Partial<SceneNode>) => void\n previewUpdated: (id: string, changes: Partial<SceneNode>) => void\n deleted: (id: string, parentId: string | null) => void\n reparented: (nodeId: string, oldParentId: string | null, newParentId: string) => void\n reordered: (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}>\n\n/** Hears about nodes as an edit adds and changes them, synchronously and before each change. */\nexport interface NodeChangeObserver {\n /** A node is about to change and is still as it was. */\n before: (node: SceneNode) => void\n /** A node was just added. */\n created: (node: SceneNode) => void\n /** What changes from now until `resume` is someone else's; `waitOutsideEdit` calls this. */\n pause?: () => void\n /** The wait ended, and what changed meanwhile belongs outside the edit. */\n resume?: () => void\n}\n\nexport type DocumentColorSpace = 'srgb' | 'display-p3'\n\n/** What a document is for, as Figma keeps design files and FigJam boards apart. */\nexport type DocumentKind = 'design' | 'board'\n\nexport interface FigmaSourcePayload {\n rawSize: Vector | null\n rawTransform: Matrix | null\n rawNodeFields: Record<string, unknown>\n layout: FigmaLayoutMetadata | null\n symbolOverrides: unknown[]\n componentPropAssignments: unknown[]\n derivedSymbolData: unknown[]\n derivedSymbolDataLayoutVersion: number | null\n uniformScaleFactor: number | null\n}\n\n/**\n * An edge as its draw.io file wrote it: the style pairs and geometry the author set. A connector\n * read from a file keeps them so saving an unedited edge writes back what draw.io had, instead of\n * re-routing it.\n */\nexport interface DrawIOEdgeSource {\n /** The style's names and its pairs, in the order the file wrote them. */\n styleNames: string[]\n styleValues: Partial<Record<string, string>>\n /** The label's place along the edge, as the geometry's `x`. */\n labelX: number\n /** Bend points and free ends, in the edge's parent's axes. */\n points: Vector[]\n sourcePoint: Vector | null\n targetPoint: Vector | null\n}\n\nexport interface SourceMetadata {\n format: 'fig' | null\n id: string | null\n orderKey: string | null\n editedFields: string[]\n fig: FigmaSourcePayload\n /** The edge cell a connector was read from, kept until the connector is edited. */\n drawio?: DrawIOEdgeSource | null\n}\n\nexport type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'\nexport type WindingRule = 'NONZERO' | 'EVENODD'\n\nexport interface VectorVertex {\n x: number\n y: number\n strokeCap?: string\n strokeJoin?: string\n cornerRadius?: number\n handleMirroring?: HandleMirroring\n}\n\nexport interface VectorSegment {\n start: number\n end: number\n tangentStart: Vector\n tangentEnd: Vector\n}\n\nexport interface VectorRegion {\n windingRule: WindingRule\n loops: number[][]\n}\n\nexport interface VectorNetwork {\n vertices: VectorVertex[]\n segments: VectorSegment[]\n regions: VectorRegion[]\n}\n\nexport interface GeometryPath {\n windingRule: WindingRule\n commandsBlob: Uint8Array\n /** Resolved paints for geometry using a format-specific style override. */\n fills?: Fill[]\n /** Shared fill style attached to this geometry region, when available. */\n fillStyleId?: string\n}\n\nexport type NodeType =\n | 'CANVAS'\n | 'FRAME'\n | 'RECTANGLE'\n | 'ROUNDED_RECTANGLE'\n | 'ELLIPSE'\n | 'TEXT'\n | 'LINE'\n | 'STAR'\n | 'POLYGON'\n | 'VECTOR'\n | 'BOOLEAN_OPERATION'\n | 'GROUP'\n | 'SECTION'\n | 'COMPONENT'\n | 'COMPONENT_SET'\n | 'INSTANCE'\n | 'CONNECTOR'\n | 'SHAPE_WITH_TEXT'\n | 'STICKY'\n | 'SCRIPT'\n\nexport type FillType =\n | 'SOLID'\n | 'GRADIENT_LINEAR'\n | 'GRADIENT_RADIAL'\n | 'GRADIENT_ANGULAR'\n | 'GRADIENT_DIAMOND'\n | 'MESH'\n | 'IMAGE'\n | 'VIDEO'\n | 'PATTERN'\n | 'NOISE'\n | 'CUSTOM'\nexport type BlendMode =\n | 'NORMAL'\n | 'DARKEN'\n | 'MULTIPLY'\n | 'LINEAR_BURN'\n | 'COLOR_BURN'\n | 'LIGHTEN'\n | 'SCREEN'\n | 'LINEAR_DODGE'\n | 'COLOR_DODGE'\n | 'OVERLAY'\n | 'SOFT_LIGHT'\n | 'HARD_LIGHT'\n | 'DIFFERENCE'\n | 'EXCLUSION'\n | 'HUE'\n | 'SATURATION'\n | 'COLOR'\n | 'LUMINOSITY'\n | 'PASS_THROUGH'\nexport type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'\nexport type NoiseType = 'MULTITONE' | 'MONOTONE' | 'DUOTONE'\nexport type PatternTileType = 'RECTANGULAR' | 'HORIZONTAL_HEXAGONAL' | 'VERTICAL_HEXAGONAL'\nexport type PatternAlignment = 'START' | 'CENTER' | 'END'\n\nexport interface GradientStop {\n color: Color\n position: number\n}\n\n/**\n * One control point of a `MESH` fill: its color, and where it sits in the layer's unit square.\n * A mesh holds `(rows + 1) * (columns + 1)` points in row-major order: corners and edge points\n * first, so a 1x1 mesh is the four corners. Positions outside 0..1 are allowed; the renderer\n * clamps them to the layer.\n */\nexport interface MeshGradientPoint {\n position: Vector\n color: Color\n}\n\nexport type GradientTransform = Matrix\n\n/** Figma's adjustments of an image paint, each from -1 to 1; 0 leaves the image as it is. */\nexport interface ImageFilters {\n exposure?: number\n contrast?: number\n saturation?: number\n temperature?: number\n tint?: number\n highlights?: number\n shadows?: number\n}\n\nexport interface Fill {\n type: FillType\n color: Color\n opacity: number\n visible: boolean\n blendMode?: BlendMode\n gradientStops?: GradientStop[]\n gradientTransform?: GradientTransform\n /** A `MESH` fill's grid: columns and rows of cells, with one more point than cells each way. */\n meshColumns?: number\n meshRows?: number\n meshPoints?: MeshGradientPoint[]\n imageHash?: string\n imageScaleMode?: ImageScaleMode\n /** A crop's image-space window; Fill, Fit and Tile ignore it. */\n imageTransform?: GradientTransform\n /** Clockwise turn of a Fill, Fit or Tile image, in multiples of 90°; a crop holds its own. */\n imageRotation?: number\n /** An image's adjustments, in Figma's plugin API units. */\n filters?: ImageFilters\n sourceNodeId?: string\n scale?: number\n spacing?: number\n patternSpacing?: Vector\n patternTileType?: PatternTileType\n verticalAlignment?: PatternAlignment\n horizontalAlignment?: PatternAlignment\n noiseType?: NoiseType\n density?: number\n noiseSize?: Vector\n customEffectId?: string\n}\n\nexport type StrokeCap =\n | 'NONE'\n | 'ROUND'\n | 'SQUARE'\n | 'ARROW_LINES'\n | 'ARROW_EQUILATERAL'\n | 'TRIANGLE_FILLED'\n | 'DIAMOND_FILLED'\n | 'CIRCLE_FILLED'\nexport type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'\nexport type SharedStyleType = 'FILL' | 'TEXT' | 'EFFECT' | 'GRID'\nexport type SharedStyleKind = 'fill' | 'stroke' | 'text' | 'effect' | 'grid'\nexport type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'\nexport type BooleanOperation = 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'\n\nexport interface LayoutGrid {\n visible?: boolean\n color?: Color\n /** `STRIPES` is the archive's name for columns or rows, along `axis`. */\n pattern?: 'COLUMNS' | 'ROWS' | 'GRID' | 'STRIPES'\n axis?: 'X' | 'Y'\n type?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n alignment?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n numSections?: number\n /** Figma's plugin API reports an Auto count as `null` and accepts `Infinity` for it. */\n count?: number | null\n offset?: number\n sectionSize?: number\n gutterSize?: number\n}\n\nexport interface SharedStyle {\n id: string\n nodeId: string\n name: string\n type: SharedStyleType\n}\n\n/** A stroke is a paint with the geometry that decides where it is drawn. */\nexport interface Stroke extends Fill {\n weight: number\n align: 'INSIDE' | 'CENTER' | 'OUTSIDE'\n cap?: StrokeCap\n join?: StrokeJoin\n dashPattern?: number[]\n}\n\nexport type Effect = ShadowEffect | ShaderEffect | NoiseEffect | TextureEffect\n\nexport interface ShadowEffect {\n type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'\n color: Color\n offset: Vector\n radius: number\n spread: number\n visible: boolean\n blendMode?: BlendMode\n showShadowBehindNode?: boolean\n}\n\n/**\n * A Noise effect's grain, in Figma's plugin terms: `MONOTONE` grains in the effect's colour,\n * `DUOTONE` in it and `secondaryColor`, `MULTITONE` in many colours at `opacity`. `noiseSize` is a\n * grain's size in px, which Figma keeps within 0 to 100, and `density` how much of the layer the\n * grains cover, 0 to 1. `seed` picks the pattern; Figma's plugin API neither shows nor sets it.\n */\nexport interface NoiseEffectParams {\n noiseType: NoiseType\n noiseSize: Vector\n density: number\n secondaryColor?: Color\n opacity?: number\n seed?: number\n}\n\n/**\n * A Texture effect's grain, which roughens the layer's edges: `noiseSize` is the grain's size in\n * px, within 0 to 100 as Figma keeps it, and `clipToShape` keeps the roughened layer inside its\n * own outline. The effect's `radius` is how far the grain moves the edges. `.fig` files name the\n * effect `GRAIN`.\n */\nexport interface TextureEffectParams {\n noiseSize: Vector\n clipToShape: boolean\n seed?: number\n}\n\nexport interface NoiseEffect {\n type: 'NOISE'\n color: Color\n visible: boolean\n blendMode?: BlendMode\n noise: NoiseEffectParams\n}\n\nexport interface TextureEffect {\n type: 'TEXTURE'\n color: Color\n radius: number\n visible: boolean\n blendMode?: BlendMode\n texture: TextureEffectParams\n}\n\n/** A layer post-processed by shader code the user wrote; the layer is the `pencil:object` sample. */\nexport interface ShaderEffect {\n type: 'SHADER'\n source: string\n uniforms?: Record<string, ShaderUniformValue>\n uniformBindings?: Record<string, string>\n visible: boolean\n blendMode?: BlendMode\n}\n\nexport type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'\nexport type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'\n\n/** Where a connector end attaches to a layer: a side, the side Figma picks, or a fixed point. */\nexport type ConnectorMagnet =\n | 'NONE'\n | 'AUTO'\n | 'AUTO_HORIZONTAL'\n | 'TOP'\n | 'RIGHT'\n | 'BOTTOM'\n | 'LEFT'\n | 'CENTER'\n | 'EDGE'\n | 'ABSOLUTE'\n\n/**\n * One end of a connector. Bound to a layer, it follows the layer by `magnet`, or by `position`\n * in the layer's own axes when the magnet is `NONE`. Free, `nodeId` is null and `position` is in\n * the connector's parent's axes.\n */\nexport interface ConnectorEndpoint {\n nodeId: string | null\n magnet: ConnectorMagnet\n position: Vector\n}\n\nexport type ConnectorLineType = 'ELBOWED' | 'STRAIGHT' | 'CURVED'\n\n/**\n * A segment of an elbow connector that was dragged into place: the line it runs along, through\n * `position`, in the connector's own axes. `position` lies midway along the segment as last drawn.\n */\nexport interface ConnectorControlPoint {\n position: Vector\n direction: 'HORIZONTAL' | 'VERTICAL'\n}\n\n/**\n * Where a connector's label was dragged along its line: `offset` of the way from the middle of\n * the line towards one end, by length, on the line or to one side of it. `ABOVE` is the side to\n * the left of the line's direction.\n */\nexport interface ConnectorLabelPosition {\n section: 'MIDDLE_TO_START' | 'MIDDLE_TO_END'\n offset: number\n offAxis: 'NONE' | 'ABOVE' | 'BELOW'\n}\nexport type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'\nexport type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'\nexport type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'\nexport type TextDecorationStyle = 'SOLID' | 'DOTTED' | 'WAVY'\nexport type LeadingTrim = 'NONE' | 'CAP_HEIGHT'\nexport type TextDirection = 'AUTO' | 'LTR' | 'RTL'\nexport type LayoutDirection = 'AUTO' | 'LTR' | 'RTL'\n/** Whether a paragraph is an item of a numbered list, a bulleted list, or no list. */\nexport type TextListType = 'NONE' | 'ORDERED' | 'UNORDERED'\n\n/** How one paragraph of a text node (a line ending at a newline) sits in a list. */\n/** Spacing a text sets for all its paragraphs and a paragraph can set for itself. */\nexport type TextParagraphSpacingField = 'listSpacing' | 'paragraphSpacing' | 'paragraphIndent'\n\nexport interface TextParagraphStyle {\n listType: TextListType\n /** Nesting level: 1–5 for list items; kept but not drawn for plain paragraphs. */\n indentation: number\n /** This paragraph's own spacing, in place of the text's; absent ones follow the text. */\n listSpacing?: number\n paragraphSpacing?: number\n paragraphIndent?: number\n}\n\nexport interface FontVariation {\n axis: string\n value: number\n}\n\nexport interface FontFeature {\n tag: string\n enabled: boolean\n}\n\n/** Where a stretch of text links to, as Figma's `HyperlinkTarget`: a URL, or a node by its ID. */\nexport interface HyperlinkTarget {\n type: 'URL' | 'NODE'\n value: string\n}\n\n/** The text fields a range of characters can bind to a variable, as Figma lists them. */\nexport const TEXT_BINDABLE_FIELDS = [\n 'fontFamily',\n 'fontSize',\n 'fontStyle',\n 'fontWeight',\n 'letterSpacing',\n 'lineHeight',\n 'paragraphSpacing',\n 'paragraphIndent'\n] as const\n\nexport type TextBindableField = (typeof TEXT_BINDABLE_FIELDS)[number]\n\n/** Variable IDs bound to text fields, by field. */\nexport type TextBoundVariables = Partial<Record<TextBindableField, string>>\n\n/**\n * A line height or letter spacing as Figma keeps it: pixels, or a percent of the font size that\n * follows the size when it changes.\n */\nexport interface TextLength {\n value: number\n unit: 'PIXELS' | 'PERCENT'\n}\n\nexport interface CharacterStyleOverride {\n fontWeight?: number\n italic?: boolean\n /** The characters' face by its font's own name for it; `null` is the face their weight picks. */\n fontStyle?: string | null\n textDecoration?: TextDecoration\n textDecorationStyle?: TextDecorationStyle\n textDecorationThickness?: number | null\n textDecorationFills?: Fill[]\n textDecorationSkipInk?: boolean\n textUnderlineOffset?: number | null\n fontSize?: number\n fontFamily?: string\n letterSpacing?: TextLength\n /** `null` is automatic, from the font. */\n lineHeight?: TextLength | null\n fills?: Fill[]\n fontVariations?: FontVariation[]\n /** Whether the characters' optical size follows their font size, in place of the text's own. */\n opticalSizeFromFontSize?: boolean\n fontFeatures?: FontFeature[]\n textLanguage?: string | null\n textCase?: TextCase\n /** A link over the characters; `null`, like leaving it out, links nowhere. */\n hyperlink?: HyperlinkTarget | null\n /** The text style the characters use in place of the text's own; `null` uses none. */\n textStyleId?: string | null\n /** The fill style the characters use in place of the text's own; `null` uses none. */\n fillStyleId?: string | null\n /** The characters' text field bindings, in place of the text's own. */\n boundVariables?: TextBoundVariables\n /**\n * The scale each number the characters bind resolves with, as a rescale left it; a field without\n * one uses the layer's `variableBindingScales`, as runs did before they kept their own.\n */\n variableBindingScales?: Partial<Record<TextBindableField, number>>\n}\n\nexport interface StyleRun {\n start: number\n length: number\n style: CharacterStyleOverride\n}\n\nexport interface ArcData {\n startingAngle: number\n endingAngle: number\n innerRadius: number\n}\n\nexport type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'GRID'\n/** A node's sizing along one axis; fill is stored on the child, see `layoutSizing`. */\nexport type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'\n/** Whether an auto-layout frame keeps its size or hugs its children along one of its axes. */\nexport type AxisSizingMode = 'FIXED' | 'HUG'\n\nexport type GridTrackSizing = 'FIXED' | 'FR' | 'AUTO'\n\nexport interface GridTrack {\n sizing: GridTrackSizing\n value: number\n}\n\nexport interface GridPosition {\n column: number\n row: number\n columnSpan: number\n rowSpan: number\n}\n/**\n * Primary axis alignment of an auto layout's children. `SPACE_AROUND` is Pairdraw's own:\n * Figma has no such mode, so `.fig` files keep it as plugin data over Figma's space between.\n */\nexport type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN' | 'SPACE_AROUND'\nexport type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'\nexport type LayoutAlignSelf = 'AUTO' | 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'\nexport type LayoutWrap = 'NO_WRAP' | 'WRAP'\n\nexport interface PluginDataEntry {\n pluginId: string\n key: string\n value: string\n}\n\nexport interface ExportSetting {\n scale: number\n format: ExportFormatId\n /** JPG and WEBP quality from 1 to 100; absent means the encoder's default. */\n quality?: number\n}\n\nexport interface PluginRelaunchDataEntry {\n pluginId: string\n command: string\n message: string\n isDeleted: boolean\n}\n\n/**\n * One derived glyph outline for display (path text / missing-font fidelity).\n * Figma import is one producer; Pairdraw editing and reflow can regenerate it.\n * commandsBlob is in font units; paint multiplies by fontSize (and scaleX/Y).\n */\nexport interface TextPathData {\n network: VectorNetwork\n normalizedSize: Vector\n /** Where on the start segment the text starts, from 0 at its start to 1 at its end. */\n tValue: number\n forward: boolean\n /** The segment the text starts on, which Figma marks in the network blob; 0 when unmarked. */\n startSegment?: number\n}\n\nexport interface DerivedTextGlyph {\n /** UTF-16 source-text cluster start, when supplied by the shaping source. */\n firstCharacter?: number\n commandsBlob: Uint8Array\n x: number\n y: number\n fontSize: number\n /** Figma Glyph.rotation — radians, not degrees. Zero for axis-aligned text. */\n rotation?: number\n /**\n * Horizontal advance in pixels at `fontSize`, before `scaleX`, when the shaping source gave\n * one; where the glyph ends, so decorations stop at the text rather than the layer's edge.\n */\n advance?: number\n /**\n * Accumulated non-uniform resize scale (default 1). Paint order is\n * translate → scale(scaleX,Y) → rotate → scale(fontSize,-fontSize) so\n * anisotropic stretch matches scaleGeometryPaths(strokeGeometry).\n * Do not fold this into fontSize or rotated letters desync from outlines.\n */\n scaleX?: number\n scaleY?: number\n /**\n * The code points of the emoji this glyph stands for, sequence and all. Its outline is only a\n * placeholder square a 1 em wide; the emoji's image is drawn there instead, as Figma does.\n */\n emojiCodePoints?: number[]\n /** The image set Figma draws the emoji from, when the file names one other than Apple's. */\n emojiImageSet?: 'NOTO'\n}\n\nexport interface SymbolLink {\n uri: string\n displayName?: string\n displayText?: string\n}\n\nexport interface VariantPropSpec {\n propDefId: string\n value: string\n}\n\nexport type FigmaLayoutMetadata = Partial<\n Record<\n | 'stackMode'\n | 'stackCounterAlign'\n | 'stackJustify'\n | 'stackCounterAlignItems'\n | 'stackPrimaryAlignItems'\n | 'stackPrimarySizing'\n | 'stackCounterSizing'\n | 'stackWrap'\n | 'stackPositioning'\n | 'stackChildAlignSelf',\n string\n > &\n Record<\n | 'stackSpacing'\n | 'stackPadding'\n | 'stackPaddingRight'\n | 'stackPaddingBottom'\n | 'stackVerticalPadding'\n | 'stackHorizontalPadding'\n | 'stackChildPrimaryGrow'\n | 'stackCounterSpacing',\n number\n > &\n Record<'bordersTakeSpace' | 'stackReverseZIndex', boolean>\n>\n\nexport interface LibraryAssetIdentity {\n libraryId: string\n assetKey: string\n revisionId: string\n}\n\nexport interface LibraryAssetSource {\n identity: LibraryAssetIdentity\n sourceNodeId: string | null\n readOnly: boolean\n}\n\nexport interface EnabledLibraryBinding {\n libraryId: string\n revisionId: string\n enabled: boolean\n}\n\n/** The library a document publishes as. */\nexport interface SourceLibraryPublication {\n libraryId: string\n revisionId: string\n name: string\n catalogSource?: string\n}\n\n/** A reply in a canvas comment thread. */\nexport interface CommentReply {\n id: string\n author: string\n /** The author's collaboration color when they wrote it, for their avatar. */\n authorColor?: Color\n /** Markdown: bold, italic, strikethrough, links and lists. */\n text: string\n createdAt: string\n deleted?: boolean\n}\n\n/** A canvas comment thread, kept in the document's root plugin data. */\nexport interface CommentThread {\n id: string\n pageId: string\n /** Page name when the pin was placed, for readers of the raw data. */\n pageName?: string\n /** Top-level layer under the pin; the pin follows it when it moves. */\n nodeId?: string | null\n nodeName?: string | null\n /** Offset from the layer's top-left corner, in canvas units. */\n offsetX?: number\n offsetY?: number\n /** Canvas position when the pin was last saved; used when the layer is gone. */\n x: number\n y: number\n author: string\n /** The author's collaboration color when they wrote it, for their avatar. */\n authorColor?: Color\n /** Markdown: bold, italic, strikethrough, links and lists. */\n text: string\n createdAt: string\n /** Bumped on every change. */\n updatedAt: string\n resolved: boolean\n resolvedAt?: string | null\n /** Deleted threads stay as tombstones so a stale copy cannot bring them back. */\n deleted?: boolean\n replies: CommentReply[]\n}\n\n/**\n * How a prototype reaction starts, as `.fig` keeps `PrototypeEvent.interactionType`: a click, the\n * pointer held over the layer (`ON_HOVER`, While hovering) or pressed on it (`ON_PRESS`, While\n * pressing), which undo themselves when it leaves or lifts, the pointer entering or leaving it,\n * or a delay.\n */\nexport type PrototypeTriggerType =\n | 'ON_CLICK'\n | 'ON_HOVER'\n | 'ON_PRESS'\n | 'MOUSE_ENTER'\n | 'MOUSE_LEAVE'\n | 'AFTER_TIMEOUT'\n\n/** What a reaction does, as `.fig` keeps `ConnectionType` on `PrototypeAction`. */\nexport type PrototypeActionType = 'NODE' | 'BACK' | 'CLOSE'\n\n/**\n * What a node action does with its node, as `NavigationType`: move to a frame, open it over the\n * screen, show another variant of the instance's set (Figma's Change to, `SWAP_STATE` in `.fig`),\n * or scroll the layer into view.\n */\nexport type PrototypeNavigationType = 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO'\n\n/** Which way a frame's content scrolls in play, as Figma's `overflowDirection`. */\nexport type OverflowDirection = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'BOTH'\n\n/**\n * How a layer moves when its parent frame scrolls in play: with the content, fixed in the frame,\n * or scrolled until it reaches the frame's top/left edge and then stuck there.\n */\nexport type ScrollBehavior = 'SCROLLS' | 'FIXED' | 'STICKY_SCROLLS'\n\n/**\n * How a reaction animates between frames, as `TransitionType` keeps them: a cut, a crossfade, or\n * Smart animate, which moves the layers two frames share by name and fades the rest.\n */\nexport type PrototypeTransitionType = 'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE'\n\n/** How a transition eases, by the names Figma's plugin API gives its presets. */\nexport type PrototypeEasingType = 'LINEAR' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_AND_OUT'\n\n/** Where an overlay sits over the screen, as `OverlayPositionType`. */\nexport type PrototypeOverlayPositionType =\n | 'CENTER'\n | 'TOP_LEFT'\n | 'TOP_CENTER'\n | 'TOP_RIGHT'\n | 'BOTTOM_LEFT'\n | 'BOTTOM_CENTER'\n | 'BOTTOM_RIGHT'\n\n/** How a reaction animates, how long it takes in seconds, and how it eases. */\nexport interface PrototypeTransition {\n type: PrototypeTransitionType\n duration: number\n /** Absent eases as Figma's default does, `DEFAULT_PROTOTYPE_EASING`. */\n easing?: PrototypeEasingType\n}\n\n/** A reaction's move to another frame, the overlay it opens, the variant or layer it shows. */\nexport interface PrototypeNodeAction {\n type: 'NODE'\n /**\n * The frame the action shows, the variant a Change to shows, or the layer a Scroll to brings\n * into view; `null` keeps the connection when its target is gone.\n */\n nodeId: string | null\n navigation: PrototypeNavigationType\n transition: PrototypeTransition\n /** Where an OVERLAY sits over the screen; NAVIGATE keeps CENTER. */\n overlayPosition: PrototypeOverlayPositionType\n}\n\n/** Goes back to the frame the play came from. */\nexport interface PrototypeBackAction {\n type: 'BACK'\n}\n\n/** Closes the overlay the play is showing. */\nexport interface PrototypeCloseAction {\n type: 'CLOSE'\n}\n\nexport type PrototypeAction = PrototypeNodeAction | PrototypeBackAction | PrototypeCloseAction\n\n/** What starts a reaction, and after how long an AFTER_TIMEOUT or mouse enter or leave does. */\nexport interface PrototypeTrigger {\n type: PrototypeTriggerType\n /** AFTER_TIMEOUT, MOUSE_ENTER and MOUSE_LEAVE: the seconds before the reaction runs. */\n delay: number\n}\n\n/**\n * One prototype connection on a layer: what starts it and what it does, as `.fig` keeps a\n * `PrototypeInteraction` on the layer's `prototypeInteractions`.\n */\nexport interface PrototypeReaction {\n id: string\n trigger: PrototypeTrigger\n actions: PrototypeAction[]\n}\n\nexport interface SceneNode {\n id: string\n type: NodeType\n name: string\n parentId: string | null\n childIds: string[]\n\n x: number\n y: number\n width: number\n height: number\n rotation: number\n source: SourceMetadata\n /** Materialized layout hint imported or generated outside the live Yoga layout pass. */\n derivedLayout: Partial<Rect> | null\n\n fills: Fill[]\n strokes: Stroke[]\n effects: Effect[]\n layoutGrids: LayoutGrid[]\n guides: CanvasGuide[]\n fillStyleId: string | null\n strokeStyleId: string | null\n textStyleId: string | null\n effectStyleId: string | null\n gridStyleId: string | null\n sharedStyleType: SharedStyleType | null\n opacity: number\n\n cornerRadius: number\n topLeftRadius: number\n topRightRadius: number\n bottomRightRadius: number\n bottomLeftRadius: number\n independentCorners: boolean\n cornerSmoothing: number\n\n visible: boolean\n locked: boolean\n clipsContent: boolean\n /** Which way the frame's content scrolls in play; a nested frame scrolls only while it clips. */\n overflowDirection: OverflowDirection\n /** How this layer moves while its parent frame scrolls in play. */\n scrollBehavior: ScrollBehavior\n\n blendMode: BlendMode\n\n text: string\n fontSize: number\n fontFamily: string\n fontWeight: number\n italic: boolean\n /**\n * The face by the name its font gives it (\"Semi Bold\", \"Book\", \"Condensed Bold\"), which Figma\n * finds a font's face by; `null` is the face the weight and slant pick in the family.\n */\n fontStyle: string | null\n textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'\n textDirection: TextDirection\n textLanguage: string | null\n textAlignVertical: TextAlignVertical\n textAutoResize: TextAutoResize\n textCase: TextCase\n textDecoration: TextDecoration\n textDecorationStyle: TextDecorationStyle\n textDecorationThickness: number | null\n textDecorationFills: Fill[]\n textDecorationSkipInk: boolean\n textUnderlineOffset: number | null\n leadingTrim: LeadingTrim\n /** `null` is automatic, from the font. */\n lineHeight: TextLength | null\n letterSpacing: TextLength\n maxLines: number | null\n /**\n * One entry per paragraph of `text`, in order. Missing entries are plain paragraphs, so text\n * without lists keeps this empty.\n */\n textParagraphs: TextParagraphStyle[]\n /** Space after a list item followed by another; a paragraph's own value comes first. */\n listSpacing: number\n /** Space after a paragraph other than between two list items. */\n paragraphSpacing: number\n /** Indent of the first line of each plain paragraph. */\n paragraphIndent: number\n /** Whether list markers hang outside the text box instead of indenting the items. */\n hangingList: boolean\n\n styleRuns: StyleRun[]\n fontVariations: FontVariation[]\n /**\n * Whether a variable font's optical size follows the font size, as Figma's \"Set optical size\n * automatically\" does by default; when it does not, the `opsz` in `fontVariations` applies.\n */\n opticalSizeFromFontSize: boolean\n fontFeatures: FontFeature[]\n\n horizontalConstraint: ConstraintType\n verticalConstraint: ConstraintType\n\n layoutMode: LayoutMode\n layoutDirection: LayoutDirection\n layoutWrap: LayoutWrap\n primaryAxisAlign: LayoutAlign\n counterAxisAlign: LayoutCounterAlign\n primaryAxisSizing: AxisSizingMode\n counterAxisSizing: AxisSizingMode\n itemSpacing: number\n counterAxisSpacing: number\n paddingTop: number\n paddingRight: number\n paddingBottom: number\n paddingLeft: number\n\n layoutPositioning: 'AUTO' | 'ABSOLUTE'\n layoutGrow: number\n layoutAlignSelf: LayoutAlignSelf\n\n vectorNetwork: VectorNetwork | null\n handleMirroring: HandleMirroring\n booleanOperation: BooleanOperation | undefined\n fillGeometry: GeometryPath[]\n strokeGeometry: GeometryPath[]\n\n arcData: ArcData | null\n\n strokeCap: StrokeCap\n strokeJoin: StrokeJoin\n dashPattern: number[]\n\n borderTopWeight: number\n borderRightWeight: number\n borderBottomWeight: number\n borderLeftWeight: number\n independentStrokeWeights: boolean\n\n /**\n * The weight and alignment a node keeps for its strokes, as Figma keeps them on the node: they\n * last while it has no strokes, and a stroke added to it takes them. Each stroke still carries\n * its own `weight` and `align`, which win while the node has strokes.\n */\n strokeWeight: number\n strokeAlign: Stroke['align']\n\n strokeMiterLimit: number\n\n minWidth: number | null\n maxWidth: number | null\n minHeight: number | null\n maxHeight: number | null\n /**\n * The size whose proportions the layer keeps, as Figma stores it: the width and height it had\n * when the ratio was locked, not a reduced ratio. Null leaves the proportions free.\n */\n targetAspectRatio: Vector | null\n\n /** A connector's ends and the line between them; null on other layers. */\n connectorStart: ConnectorEndpoint | null\n connectorEnd: ConnectorEndpoint | null\n connectorLineType: ConnectorLineType\n connectorStartCap: StrokeCap\n connectorEndCap: StrokeCap\n /**\n * An elbow connector's segments between its first and last, in order, once one was dragged;\n * empty while it routes itself. Kept, unused, while the line is straight or curved.\n */\n connectorControlPoints: ConnectorControlPoint[]\n /**\n * A curved connector's two cubic control points, in the connector's own axes, once its curve\n * was dragged; null while it curves by itself. Kept, unused, while the line is not curved.\n */\n connectorCurveHandles: [Vector, Vector] | null\n /** Where a connector's label was dragged to; null while it sits midway along the line. */\n connectorLabelPosition: ConnectorLabelPosition | null\n\n isMask: boolean\n maskType: MaskType\n maskIsOutline: boolean\n\n gridTemplateColumns: GridTrack[]\n gridTemplateRows: GridTrack[]\n gridColumnGap: number\n gridRowGap: number\n gridPosition: GridPosition | null\n\n counterAxisAlignContent: 'AUTO' | 'SPACE_BETWEEN'\n itemReverseZIndex: boolean\n strokesIncludedInLayout: boolean\n\n expanded: boolean\n textTruncation: 'DISABLED' | 'ENDING'\n autoRename: boolean\n\n pointCount: number\n starInnerRadius: number\n /** The FigJam kind a SHAPE_WITH_TEXT draws; its label is the node's own text. */\n shapeWithTextType: ShapeWithTextType\n /** The height a shape with text was given; it grows past it to fit its label. 0 is unset. */\n shapeUserHeight: number\n /**\n * Whether a shape with text keeps its height and cuts its label off with \"…\" instead of growing,\n * as FigJam does once the shape's height was set.\n */\n shapeTruncates: boolean\n\n componentId: string | null\n instanceOverrides: InstanceOverrideState\n componentPropertyDefinitions: ComponentPropertyDefinition[]\n componentPropertyReferences: ComponentPropertyReference[]\n componentPropertyAssignments: Record<string, string>\n componentPropertyValues: Record<string, string>\n componentKey: string | null\n sourceLibraryKey: string | null\n publishId: string | null\n overrideKey: string | null\n sharedSymbolVersion: string | null\n publishedVersion: string | null\n librarySource: LibraryAssetSource | null\n isPublishable: boolean\n isSymbolPublishable: boolean\n /**\n * On an instance inside a component: its properties show on instances of that component,\n * as Figma's `isExposedInstance`.\n */\n isExposedInstance: boolean\n symbolDescription: string\n symbolLinks: SymbolLink[]\n variantPropSpecs: VariantPropSpec[]\n\n boundVariables: Record<string, string>\n /** Multipliers from bound numeric values to this occurrence's scene units. */\n variableBindingScales: Partial<Record<string, number>>\n /** Numeric units for new declarations owned by this node's occurrence scope. */\n variableAssignmentScales: Partial<Record<string, number>>\n /** Explicit coordinate scale relative to the containing component definition. */\n componentScale: number\n variableModes: VariableModeMap\n exportSettings: ExportSetting[]\n /**\n * The id of the status a team gave the layer, a state of the document's workflow such as Ready\n * for dev. It stays while the layer sits where it cannot show one; `effectiveStatus` tells\n * whether it shows.\n */\n status: string | null\n\n pluginData: PluginDataEntry[]\n pluginRelaunchData: PluginRelaunchDataEntry[]\n\n /** The prototype reactions this layer starts, as Figma's prototype keeps them. */\n prototypeReactions: PrototypeReaction[]\n\n internalOnly: boolean\n\n flipX: boolean\n flipY: boolean\n\n textPicture: Uint8Array | null\n derivedTextGlyphs: DerivedTextGlyph[] | null\n /**\n * How far a text's lines reach down from its top: measured at its width when its text or width\n * changes, or read from the lines a file saved, and never saved itself. A fixed-size box does not\n * clip them, as in Figma, so its visual bounds reach this far. Null when not known.\n */\n derivedTextHeight: number | null\n /** Format-neutral layout path for text-on-path nodes. */\n textPathData: TextPathData | null\n /** Node-local box that maps textPathData into the node coordinate space. */\n textPathBox: Rect | null\n}\n\nexport type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP' | 'SLOT'\n\n/** `SLOT_CONTENT` marks a frame whose children are the slot's content. */\nexport type ComponentPropertyReferenceField = 'VISIBLE' | 'TEXT' | 'INSTANCE_SWAP' | 'SLOT_CONTENT'\n\nexport interface ComponentPropertyReference {\n propertyId: string\n field: ComponentPropertyReferenceField\n}\n\n/** Guidance for a slot property; Figma reports a breach but still accepts the content. */\nexport interface SlotSettings {\n minChildren?: number\n maxChildren?: number\n allowPreferredValuesOnly: boolean\n displayEmptyByDefault: boolean\n /** Content added to the slot fills its counter axis. */\n stretchChildOnInsert: boolean\n}\n\n/**\n * For a `SLOT` property, an instance assignment (whatever its value) means the instance owns\n * that slot's content: the slot frame's children in the instance, which component sync keeps.\n */\nexport interface ComponentPropertyDefinition {\n id: string\n name: string\n type: ComponentPropertyType\n defaultValue: string\n variantOptions?: string[]\n preferredValues?: string[]\n description?: string\n slotSettings?: SlotSettings\n}\n\nexport type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'\nexport interface VariableAlias {\n aliasId: string\n}\n\n/** Figma's two-argument color expression; opacity is a percentage, not an alpha multiplier. */\nexport interface VariableColorExpression {\n expression: 'COMPOSE_COLOR'\n color: Color | VariableAlias\n opacity: number | VariableAlias\n}\n\nexport type VariableLiteral = Color | number | string | boolean\n/** The arithmetic, comparison, logic and conversions a formula combines values with. */\nexport const VARIABLE_FORMULA_OPERATORS = [\n 'add',\n 'subtract',\n 'multiply',\n 'divide',\n 'negate',\n 'equal',\n 'notEqual',\n 'less',\n 'lessOrEqual',\n 'greater',\n 'greaterOrEqual',\n 'and',\n 'or',\n 'not',\n 'text',\n 'truthy',\n 'if'\n] as const\nexport type VariableFormulaOperator = (typeof VARIABLE_FORMULA_OPERATORS)[number]\nexport interface VariableFormulaOperation {\n operator: VariableFormulaOperator\n operands: VariableFormulaNode[]\n}\nexport type VariableFormulaNode = VariableLiteral | VariableAlias | VariableFormulaOperation\nexport interface VariableFormula {\n expression: 'FORMULA'\n type: VariableType\n value: VariableFormulaNode\n}\n/**\n * An imported expression Pairdraw cannot evaluate, kept as the file wrote it so saving writes it\n * back. `references` holds one entry per alias in `value`, in the order the format walks them, and\n * `null` where the alias names a variable this document does not have. `modes` holds the mode id of\n * each mode key in `value`, in the same walk order.\n */\nexport interface VariableUnsupportedExpression {\n expression: 'UNSUPPORTED'\n /** The function name the file gives, such as `VAR_MODE_LOOKUP`. */\n function: string\n value: Record<string, unknown>\n references: (string | null)[]\n modes: string[]\n}\nexport type VariableValue =\n | VariableLiteral\n | VariableAlias\n | VariableColorExpression\n | VariableFormula\n | VariableUnsupportedExpression\nexport type VariableModeMap = Record<string, string>\n\n/** Property pickers a variable is offered in, as Figma names them. */\nexport const VARIABLE_SCOPES = [\n 'ALL_SCOPES',\n 'TEXT_CONTENT',\n 'CORNER_RADIUS',\n 'WIDTH_HEIGHT',\n 'GAP',\n 'ALL_FILLS',\n 'FRAME_FILL',\n 'SHAPE_FILL',\n 'TEXT_FILL',\n 'STROKE',\n 'STROKE_FLOAT',\n 'EFFECT_FLOAT',\n 'EFFECT_COLOR',\n 'OPACITY',\n 'FONT_STYLE',\n 'FONT_FAMILY',\n 'FONT_SIZE',\n 'LINE_HEIGHT',\n 'LETTER_SPACING',\n 'PARAGRAPH_SPACING',\n 'PARAGRAPH_INDENT',\n 'FONT_VARIATIONS',\n 'TRANSFORM'\n] as const\nexport type VariableScope = (typeof VARIABLE_SCOPES)[number]\n\nexport const CODE_SYNTAX_PLATFORMS = ['WEB', 'ANDROID', 'iOS'] as const\nexport type CodeSyntaxPlatform = (typeof CODE_SYNTAX_PLATFORMS)[number]\n\n/**\n * The CSS unit a numeric token is written in. Lengths (`px`, `rem`) stay in canvas pixels in\n * the document and convert only when written as CSS; the other units store the number as written.\n */\nexport const TOKEN_UNITS = ['none', 'px', 'rem', '%', 'ms', 's', 'deg'] as const\nexport type TokenUnit = (typeof TOKEN_UNITS)[number]\n\n/**\n * CSS written in place of a number mode's value, such as `clamp(1rem, 4vw, 1.5rem)`. While the\n * mode holds a plain number, `resolved` records it, so a number later edited elsewhere, Figma\n * included, shows the CSS no longer describes it.\n */\nexport interface TokenExpression {\n css: string\n resolved?: number\n}\n\nexport interface Variable {\n id: string\n name: string\n type: VariableType\n collectionId: string\n valuesByMode: Record<string, VariableValue>\n description: string\n hiddenFromPublishing: boolean\n /** Absent means every scope. */\n scopes?: VariableScope[]\n /**\n * Per-platform code snippets, as Figma's Dev Mode shows them. A `WEB` snippet of `--x` or\n * `var(--x)` names the token's CSS custom property; otherwise the name is derived.\n */\n codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>\n /** FLOAT only. Absent means inferred when written as CSS. */\n unit?: TokenUnit\n /** Raw CSS by mode id, for values a number cannot express (`clamp()`, `calc()`). */\n expressions?: Record<string, TokenExpression>\n pluginData?: PluginDataEntry[]\n /** Published library key (from NodeChange.key). Used for assetRef resolution in colorVar. */\n key?: string\n /** Published library version (from NodeChange.version). Used for assetRef resolution in colorVar. */\n version?: string\n}\n\n/** Scalar numeric node fields accepted by numeric property controls. */\nexport type NumericNodeProperty = {\n [K in keyof SceneNode]-?: SceneNode[K] extends number ? K : never\n}[keyof SceneNode]\n\nexport interface VariableCollectionMode {\n modeId: string\n name: string\n /**\n * Where the mode applies in CSS: a selector (`[data-theme=\"dark\"]`, `.compact`) or an\n * at-rule prelude (`@media (max-width: 640px)`). Absent means the default for its axis.\n */\n condition?: string\n /** Where Figma lists the mode, as the file saved it; Figma orders a collection's modes by it. */\n sortPosition?: string\n}\n\nexport interface VariableCollection {\n id: string\n name: string\n /** The default mode comes first, as in Figma. */\n modes: VariableCollectionMode[]\n defaultModeId: string\n variableIds: string[]\n /**\n * The attribute that switches a mode with no condition of its own, `data-theme` for\n * `[data-theme=\"dark\"]`. Absent means one named after the collection.\n */\n modeAttribute?: string\n pluginData?: PluginDataEntry[]\n /**\n * Published library key, for a collection the file copies from a library. Such a collection\n * belongs to the library: Figma lists it with the library's, not the file's own.\n */\n key?: string\n /** Published library version, which references by key carry with it. */\n version?: string\n}\n\n/** Whether a collection is a library's copy, which takes no variables or modes of the file's. */\nexport function isLibraryCollection(collection: Pick<VariableCollection, 'key'>): boolean {\n return !!collection.key\n}\n\n/** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */\nexport const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\\w-]*$/\n\nexport function isModeAttributeName(name: string): boolean {\n return name.length <= 100 && MODE_ATTRIBUTE_PATTERN.test(name)\n}\n"],"mappings":";;AAwcA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAirBA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAmCA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAa,wBAAwB;CAAC;CAAO;CAAW;AAAK;;;;;AAO7D,MAAa,cAAc;CAAC;CAAQ;CAAM;CAAO;CAAK;CAAM;CAAK;AAAK;;AA+EtE,SAAgB,oBAAoB,YAAsD;CACxF,OAAO,CAAC,CAAC,WAAW;AACtB;;AAGA,MAAa,yBAAyB;AAEtC,SAAgB,oBAAoB,MAAuB;CACzD,OAAO,KAAK,UAAU,OAAO,uBAAuB,KAAK,IAAI;AAC/D"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/* eslint-disable max-lines -- scene node contracts are kept together as the public graph type surface */\n\nimport type { ExportFormatId } from './export-format'\nimport type { CanvasGuide } from './guides'\nimport type { InstanceOverrideState } from './instances/overrides'\nimport type { Color, Matrix, Rect, Vector } from './primitives'\nimport type { ShaderUniformValue } from './shaders/schema'\nimport type { ShapeWithTextType } from './shape-with-text/kinds'\n\nexport interface SceneGraphEvents {\n 'node:created': (node: SceneNode) => void\n 'node:updated': (id: string, changes: Partial<SceneNode>) => void\n 'node:previewUpdated': (id: string, changes: Partial<SceneNode>) => void\n 'node:deleted': (id: string, parentId: string | null) => void\n 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void\n 'node:reordered': (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}\n\nexport type SceneGraphEventHandlers = Partial<{\n created: (node: SceneNode) => void\n updated: (id: string, changes: Partial<SceneNode>) => void\n previewUpdated: (id: string, changes: Partial<SceneNode>) => void\n deleted: (id: string, parentId: string | null) => void\n reparented: (nodeId: string, oldParentId: string | null, newParentId: string) => void\n reordered: (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}>\n\n/** Hears about nodes as an edit adds and changes them, synchronously and before each change. */\nexport interface NodeChangeObserver {\n /** A node is about to change and is still as it was. */\n before: (node: SceneNode) => void\n /** A node was just added. */\n created: (node: SceneNode) => void\n /** What changes from now until `resume` is someone else's; `waitOutsideEdit` calls this. */\n pause?: () => void\n /** The wait ended, and what changed meanwhile belongs outside the edit. */\n resume?: () => void\n}\n\n/**\n * A color profile: the one a document's colors are stored in, or the one they are shown or\n * exported in. Figma files are sRGB or Display P3.\n */\nexport type ColorProfile = 'srgb' | 'display-p3'\n\n/** @deprecated use `ColorProfile` */\nexport type DocumentColorSpace = ColorProfile\n\n/** What a document is for, as Figma keeps design files and FigJam boards apart. */\nexport type DocumentKind = 'design' | 'board'\n\nexport interface FigmaSourcePayload {\n rawSize: Vector | null\n rawTransform: Matrix | null\n rawNodeFields: Record<string, unknown>\n layout: FigmaLayoutMetadata | null\n symbolOverrides: unknown[]\n componentPropAssignments: unknown[]\n derivedSymbolData: unknown[]\n derivedSymbolDataLayoutVersion: number | null\n uniformScaleFactor: number | null\n}\n\n/**\n * An edge as its draw.io file wrote it: the style pairs and geometry the author set. A connector\n * read from a file keeps them so saving an unedited edge writes back what draw.io had, instead of\n * re-routing it.\n */\nexport interface DrawIOEdgeSource {\n /** The style's names and its pairs, in the order the file wrote them. */\n styleNames: string[]\n styleValues: Partial<Record<string, string>>\n /** The label's place along the edge, as the geometry's `x`. */\n labelX: number\n /** Bend points and free ends, in the edge's parent's axes. */\n points: Vector[]\n sourcePoint: Vector | null\n targetPoint: Vector | null\n}\n\nexport interface SourceMetadata {\n format: 'fig' | null\n id: string | null\n orderKey: string | null\n editedFields: string[]\n fig: FigmaSourcePayload\n /** The edge cell a connector was read from, kept until the connector is edited. */\n drawio?: DrawIOEdgeSource | null\n}\n\nexport type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'\nexport type WindingRule = 'NONZERO' | 'EVENODD'\n\nexport interface VectorVertex {\n x: number\n y: number\n strokeCap?: string\n strokeJoin?: string\n cornerRadius?: number\n handleMirroring?: HandleMirroring\n}\n\nexport interface VectorSegment {\n start: number\n end: number\n tangentStart: Vector\n tangentEnd: Vector\n}\n\nexport interface VectorRegion {\n windingRule: WindingRule\n loops: number[][]\n}\n\nexport interface VectorNetwork {\n vertices: VectorVertex[]\n segments: VectorSegment[]\n regions: VectorRegion[]\n}\n\nexport interface GeometryPath {\n windingRule: WindingRule\n commandsBlob: Uint8Array\n /** Resolved paints for geometry using a format-specific style override. */\n fills?: Fill[]\n /** Shared fill style attached to this geometry region, when available. */\n fillStyleId?: string\n}\n\nexport type NodeType =\n | 'CANVAS'\n | 'FRAME'\n | 'RECTANGLE'\n | 'ROUNDED_RECTANGLE'\n | 'ELLIPSE'\n | 'TEXT'\n | 'LINE'\n | 'STAR'\n | 'POLYGON'\n | 'VECTOR'\n | 'BOOLEAN_OPERATION'\n | 'GROUP'\n | 'SECTION'\n | 'COMPONENT'\n | 'COMPONENT_SET'\n | 'INSTANCE'\n | 'CONNECTOR'\n | 'SHAPE_WITH_TEXT'\n | 'STICKY'\n | 'SCRIPT'\n\nexport type FillType =\n | 'SOLID'\n | 'GRADIENT_LINEAR'\n | 'GRADIENT_RADIAL'\n | 'GRADIENT_ANGULAR'\n | 'GRADIENT_DIAMOND'\n | 'MESH'\n | 'IMAGE'\n | 'VIDEO'\n | 'PATTERN'\n | 'NOISE'\n | 'CUSTOM'\nexport type BlendMode =\n | 'NORMAL'\n | 'DARKEN'\n | 'MULTIPLY'\n | 'LINEAR_BURN'\n | 'COLOR_BURN'\n | 'LIGHTEN'\n | 'SCREEN'\n | 'LINEAR_DODGE'\n | 'COLOR_DODGE'\n | 'OVERLAY'\n | 'SOFT_LIGHT'\n | 'HARD_LIGHT'\n | 'DIFFERENCE'\n | 'EXCLUSION'\n | 'HUE'\n | 'SATURATION'\n | 'COLOR'\n | 'LUMINOSITY'\n | 'PASS_THROUGH'\nexport type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'\nexport type NoiseType = 'MULTITONE' | 'MONOTONE' | 'DUOTONE'\nexport type PatternTileType = 'RECTANGULAR' | 'HORIZONTAL_HEXAGONAL' | 'VERTICAL_HEXAGONAL'\nexport type PatternAlignment = 'START' | 'CENTER' | 'END'\n\nexport interface GradientStop {\n color: Color\n position: number\n}\n\n/**\n * One control point of a `MESH` fill: its color, and where it sits in the layer's unit square.\n * A mesh holds `(rows + 1) * (columns + 1)` points in row-major order: corners and edge points\n * first, so a 1x1 mesh is the four corners. Positions outside 0..1 are allowed; the renderer\n * clamps them to the layer.\n */\nexport interface MeshGradientPoint {\n position: Vector\n color: Color\n}\n\nexport type GradientTransform = Matrix\n\n/** Figma's adjustments of an image paint, each from -1 to 1; 0 leaves the image as it is. */\nexport interface ImageFilters {\n exposure?: number\n contrast?: number\n saturation?: number\n temperature?: number\n tint?: number\n highlights?: number\n shadows?: number\n}\n\nexport interface Fill {\n type: FillType\n color: Color\n opacity: number\n visible: boolean\n blendMode?: BlendMode\n gradientStops?: GradientStop[]\n gradientTransform?: GradientTransform\n /** A `MESH` fill's grid: columns and rows of cells, with one more point than cells each way. */\n meshColumns?: number\n meshRows?: number\n meshPoints?: MeshGradientPoint[]\n imageHash?: string\n imageScaleMode?: ImageScaleMode\n /** A crop's image-space window; Fill, Fit and Tile ignore it. */\n imageTransform?: GradientTransform\n /** Clockwise turn of a Fill, Fit or Tile image, in multiples of 90°; a crop holds its own. */\n imageRotation?: number\n /** An image's adjustments, in Figma's plugin API units. */\n filters?: ImageFilters\n sourceNodeId?: string\n scale?: number\n spacing?: number\n patternSpacing?: Vector\n patternTileType?: PatternTileType\n verticalAlignment?: PatternAlignment\n horizontalAlignment?: PatternAlignment\n noiseType?: NoiseType\n density?: number\n noiseSize?: Vector\n customEffectId?: string\n}\n\nexport type StrokeCap =\n | 'NONE'\n | 'ROUND'\n | 'SQUARE'\n | 'ARROW_LINES'\n | 'ARROW_EQUILATERAL'\n | 'TRIANGLE_FILLED'\n | 'DIAMOND_FILLED'\n | 'CIRCLE_FILLED'\nexport type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'\nexport type SharedStyleType = 'FILL' | 'TEXT' | 'EFFECT' | 'GRID'\nexport type SharedStyleKind = 'fill' | 'stroke' | 'text' | 'effect' | 'grid'\nexport type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'\nexport type BooleanOperation = 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'\n\nexport interface LayoutGrid {\n visible?: boolean\n color?: Color\n /** `STRIPES` is the archive's name for columns or rows, along `axis`. */\n pattern?: 'COLUMNS' | 'ROWS' | 'GRID' | 'STRIPES'\n axis?: 'X' | 'Y'\n type?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n alignment?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n numSections?: number\n /** Figma's plugin API reports an Auto count as `null` and accepts `Infinity` for it. */\n count?: number | null\n offset?: number\n sectionSize?: number\n gutterSize?: number\n}\n\nexport interface SharedStyle {\n id: string\n nodeId: string\n name: string\n type: SharedStyleType\n}\n\n/** A stroke is a paint with the geometry that decides where it is drawn. */\nexport interface Stroke extends Fill {\n weight: number\n align: 'INSIDE' | 'CENTER' | 'OUTSIDE'\n cap?: StrokeCap\n join?: StrokeJoin\n dashPattern?: number[]\n}\n\nexport type Effect = ShadowEffect | ShaderEffect | NoiseEffect | TextureEffect\n\nexport interface ShadowEffect {\n type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'\n color: Color\n offset: Vector\n radius: number\n spread: number\n visible: boolean\n blendMode?: BlendMode\n showShadowBehindNode?: boolean\n}\n\n/**\n * A Noise effect's grain, in Figma's plugin terms: `MONOTONE` grains in the effect's colour,\n * `DUOTONE` in it and `secondaryColor`, `MULTITONE` in many colours at `opacity`. `noiseSize` is a\n * grain's size in px, which Figma keeps within 0 to 100, and `density` how much of the layer the\n * grains cover, 0 to 1. `seed` picks the pattern; Figma's plugin API neither shows nor sets it.\n */\nexport interface NoiseEffectParams {\n noiseType: NoiseType\n noiseSize: Vector\n density: number\n secondaryColor?: Color\n opacity?: number\n seed?: number\n}\n\n/**\n * A Texture effect's grain, which roughens the layer's edges: `noiseSize` is the grain's size in\n * px, within 0 to 100 as Figma keeps it, and `clipToShape` keeps the roughened layer inside its\n * own outline. The effect's `radius` is how far the grain moves the edges. `.fig` files name the\n * effect `GRAIN`.\n */\nexport interface TextureEffectParams {\n noiseSize: Vector\n clipToShape: boolean\n seed?: number\n}\n\nexport interface NoiseEffect {\n type: 'NOISE'\n color: Color\n visible: boolean\n blendMode?: BlendMode\n noise: NoiseEffectParams\n}\n\nexport interface TextureEffect {\n type: 'TEXTURE'\n color: Color\n radius: number\n visible: boolean\n blendMode?: BlendMode\n texture: TextureEffectParams\n}\n\n/** A layer post-processed by shader code the user wrote; the layer is the `pencil:object` sample. */\nexport interface ShaderEffect {\n type: 'SHADER'\n source: string\n uniforms?: Record<string, ShaderUniformValue>\n uniformBindings?: Record<string, string>\n visible: boolean\n blendMode?: BlendMode\n}\n\nexport type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'\nexport type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'\n\n/** Where a connector end attaches to a layer: a side, the side Figma picks, or a fixed point. */\nexport type ConnectorMagnet =\n | 'NONE'\n | 'AUTO'\n | 'AUTO_HORIZONTAL'\n | 'TOP'\n | 'RIGHT'\n | 'BOTTOM'\n | 'LEFT'\n | 'CENTER'\n | 'EDGE'\n | 'ABSOLUTE'\n\n/**\n * One end of a connector. Bound to a layer, it follows the layer by `magnet`, or by `position`\n * in the layer's own axes when the magnet is `NONE`. Free, `nodeId` is null and `position` is in\n * the connector's parent's axes.\n */\nexport interface ConnectorEndpoint {\n nodeId: string | null\n magnet: ConnectorMagnet\n position: Vector\n}\n\nexport type ConnectorLineType = 'ELBOWED' | 'STRAIGHT' | 'CURVED'\n\n/**\n * A segment of an elbow connector that was dragged into place: the line it runs along, through\n * `position`, in the connector's own axes. `position` lies midway along the segment as last drawn.\n */\nexport interface ConnectorControlPoint {\n position: Vector\n direction: 'HORIZONTAL' | 'VERTICAL'\n}\n\n/**\n * Where a connector's label was dragged along its line: `offset` of the way from the middle of\n * the line towards one end, by length, on the line or to one side of it. `ABOVE` is the side to\n * the left of the line's direction.\n */\nexport interface ConnectorLabelPosition {\n section: 'MIDDLE_TO_START' | 'MIDDLE_TO_END'\n offset: number\n offAxis: 'NONE' | 'ABOVE' | 'BELOW'\n}\nexport type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'\nexport type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'\nexport type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'\nexport type TextDecorationStyle = 'SOLID' | 'DOTTED' | 'WAVY'\nexport type LeadingTrim = 'NONE' | 'CAP_HEIGHT'\nexport type TextDirection = 'AUTO' | 'LTR' | 'RTL'\nexport type LayoutDirection = 'AUTO' | 'LTR' | 'RTL'\n/** Whether a paragraph is an item of a numbered list, a bulleted list, or no list. */\nexport type TextListType = 'NONE' | 'ORDERED' | 'UNORDERED'\n\n/** How one paragraph of a text node (a line ending at a newline) sits in a list. */\n/** Spacing a text sets for all its paragraphs and a paragraph can set for itself. */\nexport type TextParagraphSpacingField = 'listSpacing' | 'paragraphSpacing' | 'paragraphIndent'\n\nexport interface TextParagraphStyle {\n listType: TextListType\n /** Nesting level: 1–5 for list items; kept but not drawn for plain paragraphs. */\n indentation: number\n /** This paragraph's own spacing, in place of the text's; absent ones follow the text. */\n listSpacing?: number\n paragraphSpacing?: number\n paragraphIndent?: number\n}\n\nexport interface FontVariation {\n axis: string\n value: number\n}\n\nexport interface FontFeature {\n tag: string\n enabled: boolean\n}\n\n/** Where a stretch of text links to, as Figma's `HyperlinkTarget`: a URL, or a node by its ID. */\nexport interface HyperlinkTarget {\n type: 'URL' | 'NODE'\n value: string\n}\n\n/** The text fields a range of characters can bind to a variable, as Figma lists them. */\nexport const TEXT_BINDABLE_FIELDS = [\n 'fontFamily',\n 'fontSize',\n 'fontStyle',\n 'fontWeight',\n 'letterSpacing',\n 'lineHeight',\n 'paragraphSpacing',\n 'paragraphIndent'\n] as const\n\nexport type TextBindableField = (typeof TEXT_BINDABLE_FIELDS)[number]\n\n/** Variable IDs bound to text fields, by field. */\nexport type TextBoundVariables = Partial<Record<TextBindableField, string>>\n\n/**\n * A line height or letter spacing as Figma keeps it: pixels, or a percent of the font size that\n * follows the size when it changes.\n */\nexport interface TextLength {\n value: number\n unit: 'PIXELS' | 'PERCENT'\n}\n\nexport interface CharacterStyleOverride {\n fontWeight?: number\n italic?: boolean\n /** The characters' face by its font's own name for it; `null` is the face their weight picks. */\n fontStyle?: string | null\n textDecoration?: TextDecoration\n textDecorationStyle?: TextDecorationStyle\n textDecorationThickness?: number | null\n textDecorationFills?: Fill[]\n textDecorationSkipInk?: boolean\n textUnderlineOffset?: number | null\n fontSize?: number\n fontFamily?: string\n letterSpacing?: TextLength\n /** `null` is automatic, from the font. */\n lineHeight?: TextLength | null\n fills?: Fill[]\n fontVariations?: FontVariation[]\n /** Whether the characters' optical size follows their font size, in place of the text's own. */\n opticalSizeFromFontSize?: boolean\n fontFeatures?: FontFeature[]\n textLanguage?: string | null\n textCase?: TextCase\n /** A link over the characters; `null`, like leaving it out, links nowhere. */\n hyperlink?: HyperlinkTarget | null\n /** The text style the characters use in place of the text's own; `null` uses none. */\n textStyleId?: string | null\n /** The fill style the characters use in place of the text's own; `null` uses none. */\n fillStyleId?: string | null\n /** The characters' text field bindings, in place of the text's own. */\n boundVariables?: TextBoundVariables\n /**\n * The scale each number the characters bind resolves with, as a rescale left it; a field without\n * one uses the layer's `variableBindingScales`, as runs did before they kept their own.\n */\n variableBindingScales?: Partial<Record<TextBindableField, number>>\n}\n\nexport interface StyleRun {\n start: number\n length: number\n style: CharacterStyleOverride\n}\n\nexport interface ArcData {\n startingAngle: number\n endingAngle: number\n innerRadius: number\n}\n\nexport type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'GRID'\n/** A node's sizing along one axis; fill is stored on the child, see `layoutSizing`. */\nexport type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'\n/** Whether an auto-layout frame keeps its size or hugs its children along one of its axes. */\nexport type AxisSizingMode = 'FIXED' | 'HUG'\n\nexport type GridTrackSizing = 'FIXED' | 'FR' | 'AUTO'\n\nexport interface GridTrack {\n sizing: GridTrackSizing\n value: number\n}\n\nexport interface GridPosition {\n column: number\n row: number\n columnSpan: number\n rowSpan: number\n}\n/**\n * Primary axis alignment of an auto layout's children. `SPACE_AROUND` is Pairdraw's own:\n * Figma has no such mode, so `.fig` files keep it as plugin data over Figma's space between.\n */\nexport type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN' | 'SPACE_AROUND'\nexport type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'\nexport type LayoutAlignSelf = 'AUTO' | 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'\nexport type LayoutWrap = 'NO_WRAP' | 'WRAP'\n\nexport interface PluginDataEntry {\n pluginId: string\n key: string\n value: string\n}\n\nexport interface ExportSetting {\n scale: number\n format: ExportFormatId\n /** JPG and WEBP quality from 1 to 100; absent means the encoder's default. */\n quality?: number\n}\n\nexport interface PluginRelaunchDataEntry {\n pluginId: string\n command: string\n message: string\n isDeleted: boolean\n}\n\n/**\n * One derived glyph outline for display (path text / missing-font fidelity).\n * Figma import is one producer; Pairdraw editing and reflow can regenerate it.\n * commandsBlob is in font units; paint multiplies by fontSize (and scaleX/Y).\n */\nexport interface TextPathData {\n network: VectorNetwork\n normalizedSize: Vector\n /** Where on the start segment the text starts, from 0 at its start to 1 at its end. */\n tValue: number\n forward: boolean\n /** The segment the text starts on, which Figma marks in the network blob; 0 when unmarked. */\n startSegment?: number\n}\n\nexport interface DerivedTextGlyph {\n /** UTF-16 source-text cluster start, when supplied by the shaping source. */\n firstCharacter?: number\n commandsBlob: Uint8Array\n x: number\n y: number\n fontSize: number\n /** Figma Glyph.rotation — radians, not degrees. Zero for axis-aligned text. */\n rotation?: number\n /**\n * Horizontal advance in pixels at `fontSize`, before `scaleX`, when the shaping source gave\n * one; where the glyph ends, so decorations stop at the text rather than the layer's edge.\n */\n advance?: number\n /**\n * Accumulated non-uniform resize scale (default 1). Paint order is\n * translate → scale(scaleX,Y) → rotate → scale(fontSize,-fontSize) so\n * anisotropic stretch matches scaleGeometryPaths(strokeGeometry).\n * Do not fold this into fontSize or rotated letters desync from outlines.\n */\n scaleX?: number\n scaleY?: number\n /**\n * The code points of the emoji this glyph stands for, sequence and all. Its outline is only a\n * placeholder square a 1 em wide; the emoji's image is drawn there instead, as Figma does.\n */\n emojiCodePoints?: number[]\n /** The image set Figma draws the emoji from, when the file names one other than Apple's. */\n emojiImageSet?: 'NOTO'\n}\n\nexport interface SymbolLink {\n uri: string\n displayName?: string\n displayText?: string\n}\n\nexport interface VariantPropSpec {\n propDefId: string\n value: string\n}\n\nexport type FigmaLayoutMetadata = Partial<\n Record<\n | 'stackMode'\n | 'stackCounterAlign'\n | 'stackJustify'\n | 'stackCounterAlignItems'\n | 'stackPrimaryAlignItems'\n | 'stackPrimarySizing'\n | 'stackCounterSizing'\n | 'stackWrap'\n | 'stackPositioning'\n | 'stackChildAlignSelf',\n string\n > &\n Record<\n | 'stackSpacing'\n | 'stackPadding'\n | 'stackPaddingRight'\n | 'stackPaddingBottom'\n | 'stackVerticalPadding'\n | 'stackHorizontalPadding'\n | 'stackChildPrimaryGrow'\n | 'stackCounterSpacing',\n number\n > &\n Record<'bordersTakeSpace' | 'stackReverseZIndex', boolean>\n>\n\nexport interface LibraryAssetIdentity {\n libraryId: string\n assetKey: string\n revisionId: string\n}\n\nexport interface LibraryAssetSource {\n identity: LibraryAssetIdentity\n sourceNodeId: string | null\n readOnly: boolean\n}\n\nexport interface EnabledLibraryBinding {\n libraryId: string\n revisionId: string\n enabled: boolean\n}\n\n/** The library a document publishes as. */\nexport interface SourceLibraryPublication {\n libraryId: string\n revisionId: string\n name: string\n catalogSource?: string\n}\n\n/** A reply in a canvas comment thread. */\nexport interface CommentReply {\n id: string\n author: string\n /** The author's collaboration color when they wrote it, for their avatar. */\n authorColor?: Color\n /** Markdown: bold, italic, strikethrough, links and lists. */\n text: string\n createdAt: string\n deleted?: boolean\n}\n\n/** A stroke drawn over the commented area in Comment mode, kept with its thread. */\nexport interface CommentRegion {\n /** Stroke points, in canvas units relative to the thread's pin anchor. */\n points: [number, number][]\n /** Stroke width in canvas units. */\n width: number\n /** Bounds of the stroke including its width, relative to the same anchor. */\n bounds: { minX: number; minY: number; maxX: number; maxY: number }\n}\n\n/** A canvas comment thread, kept in the document's root plugin data. */\nexport interface CommentThread {\n id: string\n pageId: string\n /** Page name when the pin was placed, for readers of the raw data. */\n pageName?: string\n /** Top-level layer under the pin; the pin follows it when it moves. */\n nodeId?: string | null\n nodeName?: string | null\n /** Offset from the layer's top-left corner, in canvas units. */\n offsetX?: number\n offsetY?: number\n /** Canvas position when the pin was last saved; used when the layer is gone. */\n x: number\n y: number\n author: string\n /** The author's collaboration color when they wrote it, for their avatar. */\n authorColor?: Color\n /** Markdown: bold, italic, strikethrough, links and lists. */\n text: string\n createdAt: string\n /** Bumped on every change. */\n updatedAt: string\n resolved: boolean\n resolvedAt?: string | null\n /** Deleted threads stay as tombstones so a stale copy cannot bring them back. */\n deleted?: boolean\n /** The area the person circled, when the thread was drawn rather than pinned. */\n region?: CommentRegion | null\n replies: CommentReply[]\n}\n\n/**\n * How a prototype reaction starts, as `.fig` keeps `PrototypeEvent.interactionType`: a click, the\n * pointer held over the layer (`ON_HOVER`, While hovering) or pressed on it (`ON_PRESS`, While\n * pressing), which undo themselves when it leaves or lifts, the pointer entering or leaving it,\n * or a delay.\n */\nexport type PrototypeTriggerType =\n | 'ON_CLICK'\n | 'ON_HOVER'\n | 'ON_PRESS'\n | 'MOUSE_ENTER'\n | 'MOUSE_LEAVE'\n | 'AFTER_TIMEOUT'\n\n/** What a reaction does, as `.fig` keeps `ConnectionType` on `PrototypeAction`. */\nexport type PrototypeActionType = 'NODE' | 'BACK' | 'CLOSE'\n\n/**\n * What a node action does with its node, as `NavigationType`: move to a frame, open it over the\n * screen, show another variant of the instance's set (Figma's Change to, `SWAP_STATE` in `.fig`),\n * or scroll the layer into view.\n */\nexport type PrototypeNavigationType = 'NAVIGATE' | 'OVERLAY' | 'CHANGE_TO' | 'SCROLL_TO'\n\n/** Which way a frame's content scrolls in play, as Figma's `overflowDirection`. */\nexport type OverflowDirection = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'BOTH'\n\n/**\n * How a layer moves when its parent frame scrolls in play: with the content, fixed in the frame,\n * or scrolled until it reaches the frame's top/left edge and then stuck there.\n */\nexport type ScrollBehavior = 'SCROLLS' | 'FIXED' | 'STICKY_SCROLLS'\n\n/**\n * How a reaction animates between frames, as `TransitionType` keeps them: a cut, a crossfade, or\n * Smart animate, which moves the layers two frames share by name and fades the rest.\n */\nexport type PrototypeTransitionType = 'INSTANT' | 'DISSOLVE' | 'SMART_ANIMATE'\n\n/** How a transition eases, by the names Figma's plugin API gives its presets. */\nexport type PrototypeEasingType = 'LINEAR' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_AND_OUT'\n\n/** Where an overlay sits over the screen, as `OverlayPositionType`. */\nexport type PrototypeOverlayPositionType =\n | 'CENTER'\n | 'TOP_LEFT'\n | 'TOP_CENTER'\n | 'TOP_RIGHT'\n | 'BOTTOM_LEFT'\n | 'BOTTOM_CENTER'\n | 'BOTTOM_RIGHT'\n\n/** How a reaction animates, how long it takes in seconds, and how it eases. */\nexport interface PrototypeTransition {\n type: PrototypeTransitionType\n duration: number\n /** Absent eases as Figma's default does, `DEFAULT_PROTOTYPE_EASING`. */\n easing?: PrototypeEasingType\n}\n\n/** A reaction's move to another frame, the overlay it opens, the variant or layer it shows. */\nexport interface PrototypeNodeAction {\n type: 'NODE'\n /**\n * The frame the action shows, the variant a Change to shows, or the layer a Scroll to brings\n * into view; `null` keeps the connection when its target is gone.\n */\n nodeId: string | null\n navigation: PrototypeNavigationType\n transition: PrototypeTransition\n /** Where an OVERLAY sits over the screen; NAVIGATE keeps CENTER. */\n overlayPosition: PrototypeOverlayPositionType\n}\n\n/** Goes back to the frame the play came from. */\nexport interface PrototypeBackAction {\n type: 'BACK'\n}\n\n/** Closes the overlay the play is showing. */\nexport interface PrototypeCloseAction {\n type: 'CLOSE'\n}\n\nexport type PrototypeAction = PrototypeNodeAction | PrototypeBackAction | PrototypeCloseAction\n\n/** What starts a reaction, and after how long an AFTER_TIMEOUT or mouse enter or leave does. */\nexport interface PrototypeTrigger {\n type: PrototypeTriggerType\n /** AFTER_TIMEOUT, MOUSE_ENTER and MOUSE_LEAVE: the seconds before the reaction runs. */\n delay: number\n}\n\n/**\n * One prototype connection on a layer: what starts it and what it does, as `.fig` keeps a\n * `PrototypeInteraction` on the layer's `prototypeInteractions`.\n */\nexport interface PrototypeReaction {\n id: string\n trigger: PrototypeTrigger\n actions: PrototypeAction[]\n}\n\nexport interface SceneNode {\n id: string\n type: NodeType\n name: string\n parentId: string | null\n childIds: string[]\n\n x: number\n y: number\n width: number\n height: number\n rotation: number\n source: SourceMetadata\n /** Materialized layout hint imported or generated outside the live Yoga layout pass. */\n derivedLayout: Partial<Rect> | null\n\n fills: Fill[]\n strokes: Stroke[]\n effects: Effect[]\n layoutGrids: LayoutGrid[]\n guides: CanvasGuide[]\n fillStyleId: string | null\n strokeStyleId: string | null\n textStyleId: string | null\n effectStyleId: string | null\n gridStyleId: string | null\n sharedStyleType: SharedStyleType | null\n opacity: number\n\n cornerRadius: number\n topLeftRadius: number\n topRightRadius: number\n bottomRightRadius: number\n bottomLeftRadius: number\n independentCorners: boolean\n cornerSmoothing: number\n\n visible: boolean\n locked: boolean\n clipsContent: boolean\n /** Which way the frame's content scrolls in play; a nested frame scrolls only while it clips. */\n overflowDirection: OverflowDirection\n /** How this layer moves while its parent frame scrolls in play. */\n scrollBehavior: ScrollBehavior\n\n blendMode: BlendMode\n\n text: string\n fontSize: number\n fontFamily: string\n fontWeight: number\n italic: boolean\n /**\n * The face by the name its font gives it (\"Semi Bold\", \"Book\", \"Condensed Bold\"), which Figma\n * finds a font's face by; `null` is the face the weight and slant pick in the family.\n */\n fontStyle: string | null\n textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'\n textDirection: TextDirection\n textLanguage: string | null\n textAlignVertical: TextAlignVertical\n textAutoResize: TextAutoResize\n textCase: TextCase\n textDecoration: TextDecoration\n textDecorationStyle: TextDecorationStyle\n textDecorationThickness: number | null\n textDecorationFills: Fill[]\n textDecorationSkipInk: boolean\n textUnderlineOffset: number | null\n leadingTrim: LeadingTrim\n /** `null` is automatic, from the font. */\n lineHeight: TextLength | null\n letterSpacing: TextLength\n maxLines: number | null\n /**\n * One entry per paragraph of `text`, in order. Missing entries are plain paragraphs, so text\n * without lists keeps this empty.\n */\n textParagraphs: TextParagraphStyle[]\n /** Space after a list item followed by another; a paragraph's own value comes first. */\n listSpacing: number\n /** Space after a paragraph other than between two list items. */\n paragraphSpacing: number\n /** Indent of the first line of each plain paragraph. */\n paragraphIndent: number\n /** Whether list markers hang outside the text box instead of indenting the items. */\n hangingList: boolean\n\n styleRuns: StyleRun[]\n fontVariations: FontVariation[]\n /**\n * Whether a variable font's optical size follows the font size, as Figma's \"Set optical size\n * automatically\" does by default; when it does not, the `opsz` in `fontVariations` applies.\n */\n opticalSizeFromFontSize: boolean\n fontFeatures: FontFeature[]\n\n horizontalConstraint: ConstraintType\n verticalConstraint: ConstraintType\n\n layoutMode: LayoutMode\n layoutDirection: LayoutDirection\n layoutWrap: LayoutWrap\n primaryAxisAlign: LayoutAlign\n counterAxisAlign: LayoutCounterAlign\n primaryAxisSizing: AxisSizingMode\n counterAxisSizing: AxisSizingMode\n itemSpacing: number\n counterAxisSpacing: number\n paddingTop: number\n paddingRight: number\n paddingBottom: number\n paddingLeft: number\n\n layoutPositioning: 'AUTO' | 'ABSOLUTE'\n layoutGrow: number\n layoutAlignSelf: LayoutAlignSelf\n\n vectorNetwork: VectorNetwork | null\n handleMirroring: HandleMirroring\n booleanOperation: BooleanOperation | undefined\n fillGeometry: GeometryPath[]\n strokeGeometry: GeometryPath[]\n\n arcData: ArcData | null\n\n strokeCap: StrokeCap\n strokeJoin: StrokeJoin\n dashPattern: number[]\n\n borderTopWeight: number\n borderRightWeight: number\n borderBottomWeight: number\n borderLeftWeight: number\n independentStrokeWeights: boolean\n\n /**\n * The weight and alignment a node keeps for its strokes, as Figma keeps them on the node: they\n * last while it has no strokes, and a stroke added to it takes them. Each stroke still carries\n * its own `weight` and `align`, which win while the node has strokes.\n */\n strokeWeight: number\n strokeAlign: Stroke['align']\n\n strokeMiterLimit: number\n\n minWidth: number | null\n maxWidth: number | null\n minHeight: number | null\n maxHeight: number | null\n /**\n * The size whose proportions the layer keeps, as Figma stores it: the width and height it had\n * when the ratio was locked, not a reduced ratio. Null leaves the proportions free.\n */\n targetAspectRatio: Vector | null\n\n /** A connector's ends and the line between them; null on other layers. */\n connectorStart: ConnectorEndpoint | null\n connectorEnd: ConnectorEndpoint | null\n connectorLineType: ConnectorLineType\n connectorStartCap: StrokeCap\n connectorEndCap: StrokeCap\n /**\n * An elbow connector's segments between its first and last, in order, once one was dragged;\n * empty while it routes itself. Kept, unused, while the line is straight or curved.\n */\n connectorControlPoints: ConnectorControlPoint[]\n /**\n * A curved connector's two cubic control points, in the connector's own axes, once its curve\n * was dragged; null while it curves by itself. Kept, unused, while the line is not curved.\n */\n connectorCurveHandles: [Vector, Vector] | null\n /** Where a connector's label was dragged to; null while it sits midway along the line. */\n connectorLabelPosition: ConnectorLabelPosition | null\n\n isMask: boolean\n maskType: MaskType\n maskIsOutline: boolean\n\n gridTemplateColumns: GridTrack[]\n gridTemplateRows: GridTrack[]\n gridColumnGap: number\n gridRowGap: number\n gridPosition: GridPosition | null\n\n counterAxisAlignContent: 'AUTO' | 'SPACE_BETWEEN'\n itemReverseZIndex: boolean\n strokesIncludedInLayout: boolean\n\n expanded: boolean\n textTruncation: 'DISABLED' | 'ENDING'\n autoRename: boolean\n\n pointCount: number\n starInnerRadius: number\n /** The FigJam kind a SHAPE_WITH_TEXT draws; its label is the node's own text. */\n shapeWithTextType: ShapeWithTextType\n /** The height a shape with text was given; it grows past it to fit its label. 0 is unset. */\n shapeUserHeight: number\n /**\n * Whether a shape with text keeps its height and cuts its label off with \"…\" instead of growing,\n * as FigJam does once the shape's height was set.\n */\n shapeTruncates: boolean\n\n componentId: string | null\n instanceOverrides: InstanceOverrideState\n componentPropertyDefinitions: ComponentPropertyDefinition[]\n componentPropertyReferences: ComponentPropertyReference[]\n componentPropertyAssignments: Record<string, string>\n componentPropertyValues: Record<string, string>\n componentKey: string | null\n sourceLibraryKey: string | null\n publishId: string | null\n overrideKey: string | null\n sharedSymbolVersion: string | null\n publishedVersion: string | null\n librarySource: LibraryAssetSource | null\n isPublishable: boolean\n isSymbolPublishable: boolean\n /**\n * On an instance inside a component: its properties show on instances of that component,\n * as Figma's `isExposedInstance`.\n */\n isExposedInstance: boolean\n symbolDescription: string\n symbolLinks: SymbolLink[]\n variantPropSpecs: VariantPropSpec[]\n\n boundVariables: Record<string, string>\n /** Multipliers from bound numeric values to this occurrence's scene units. */\n variableBindingScales: Partial<Record<string, number>>\n /** Numeric units for new declarations owned by this node's occurrence scope. */\n variableAssignmentScales: Partial<Record<string, number>>\n /** Explicit coordinate scale relative to the containing component definition. */\n componentScale: number\n variableModes: VariableModeMap\n exportSettings: ExportSetting[]\n /**\n * The id of the status a team gave the layer, a state of the document's workflow such as Ready\n * for dev. It stays while the layer sits where it cannot show one; `effectiveStatus` tells\n * whether it shows.\n */\n status: string | null\n\n pluginData: PluginDataEntry[]\n pluginRelaunchData: PluginRelaunchDataEntry[]\n\n /** The prototype reactions this layer starts, as Figma's prototype keeps them. */\n prototypeReactions: PrototypeReaction[]\n\n internalOnly: boolean\n\n flipX: boolean\n flipY: boolean\n\n textPicture: Uint8Array | null\n derivedTextGlyphs: DerivedTextGlyph[] | null\n /**\n * How far a text's lines reach down from its top: measured at its width when its text or width\n * changes, or read from the lines a file saved, and never saved itself. A fixed-size box does not\n * clip them, as in Figma, so its visual bounds reach this far. Null when not known.\n */\n derivedTextHeight: number | null\n /** Format-neutral layout path for text-on-path nodes. */\n textPathData: TextPathData | null\n /** Node-local box that maps textPathData into the node coordinate space. */\n textPathBox: Rect | null\n}\n\nexport type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP' | 'SLOT'\n\n/** `SLOT_CONTENT` marks a frame whose children are the slot's content. */\nexport type ComponentPropertyReferenceField = 'VISIBLE' | 'TEXT' | 'INSTANCE_SWAP' | 'SLOT_CONTENT'\n\nexport interface ComponentPropertyReference {\n propertyId: string\n field: ComponentPropertyReferenceField\n}\n\n/** Guidance for a slot property; Figma reports a breach but still accepts the content. */\nexport interface SlotSettings {\n minChildren?: number\n maxChildren?: number\n allowPreferredValuesOnly: boolean\n displayEmptyByDefault: boolean\n /** Content added to the slot fills its counter axis. */\n stretchChildOnInsert: boolean\n}\n\n/**\n * For a `SLOT` property, an instance assignment (whatever its value) means the instance owns\n * that slot's content: the slot frame's children in the instance, which component sync keeps.\n */\nexport interface ComponentPropertyDefinition {\n id: string\n name: string\n type: ComponentPropertyType\n defaultValue: string\n variantOptions?: string[]\n preferredValues?: string[]\n description?: string\n slotSettings?: SlotSettings\n}\n\nexport type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'\nexport interface VariableAlias {\n aliasId: string\n}\n\n/** Figma's two-argument color expression; opacity is a percentage, not an alpha multiplier. */\nexport interface VariableColorExpression {\n expression: 'COMPOSE_COLOR'\n color: Color | VariableAlias\n opacity: number | VariableAlias\n}\n\nexport type VariableLiteral = Color | number | string | boolean\n/** The arithmetic, comparison, logic and conversions a formula combines values with. */\nexport const VARIABLE_FORMULA_OPERATORS = [\n 'add',\n 'subtract',\n 'multiply',\n 'divide',\n 'negate',\n 'equal',\n 'notEqual',\n 'less',\n 'lessOrEqual',\n 'greater',\n 'greaterOrEqual',\n 'and',\n 'or',\n 'not',\n 'text',\n 'truthy',\n 'if'\n] as const\nexport type VariableFormulaOperator = (typeof VARIABLE_FORMULA_OPERATORS)[number]\nexport interface VariableFormulaOperation {\n operator: VariableFormulaOperator\n operands: VariableFormulaNode[]\n}\nexport type VariableFormulaNode = VariableLiteral | VariableAlias | VariableFormulaOperation\nexport interface VariableFormula {\n expression: 'FORMULA'\n type: VariableType\n value: VariableFormulaNode\n}\n/**\n * An imported expression Pairdraw cannot evaluate, kept as the file wrote it so saving writes it\n * back. `references` holds one entry per alias in `value`, in the order the format walks them, and\n * `null` where the alias names a variable this document does not have. `modes` holds the mode id of\n * each mode key in `value`, in the same walk order.\n */\nexport interface VariableUnsupportedExpression {\n expression: 'UNSUPPORTED'\n /** The function name the file gives, such as `VAR_MODE_LOOKUP`. */\n function: string\n value: Record<string, unknown>\n references: (string | null)[]\n modes: string[]\n}\nexport type VariableValue =\n | VariableLiteral\n | VariableAlias\n | VariableColorExpression\n | VariableFormula\n | VariableUnsupportedExpression\nexport type VariableModeMap = Record<string, string>\n\n/** Property pickers a variable is offered in, as Figma names them. */\nexport const VARIABLE_SCOPES = [\n 'ALL_SCOPES',\n 'TEXT_CONTENT',\n 'CORNER_RADIUS',\n 'WIDTH_HEIGHT',\n 'GAP',\n 'ALL_FILLS',\n 'FRAME_FILL',\n 'SHAPE_FILL',\n 'TEXT_FILL',\n 'STROKE',\n 'STROKE_FLOAT',\n 'EFFECT_FLOAT',\n 'EFFECT_COLOR',\n 'OPACITY',\n 'FONT_STYLE',\n 'FONT_FAMILY',\n 'FONT_SIZE',\n 'LINE_HEIGHT',\n 'LETTER_SPACING',\n 'PARAGRAPH_SPACING',\n 'PARAGRAPH_INDENT',\n 'FONT_VARIATIONS',\n 'TRANSFORM'\n] as const\nexport type VariableScope = (typeof VARIABLE_SCOPES)[number]\n\nexport const CODE_SYNTAX_PLATFORMS = ['WEB', 'ANDROID', 'iOS'] as const\nexport type CodeSyntaxPlatform = (typeof CODE_SYNTAX_PLATFORMS)[number]\n\n/**\n * The CSS unit a numeric token is written in. Lengths (`px`, `rem`) stay in canvas pixels in\n * the document and convert only when written as CSS; the other units store the number as written.\n */\nexport const TOKEN_UNITS = ['none', 'px', 'rem', '%', 'ms', 's', 'deg'] as const\nexport type TokenUnit = (typeof TOKEN_UNITS)[number]\n\n/**\n * CSS written in place of a number mode's value, such as `clamp(1rem, 4vw, 1.5rem)`. While the\n * mode holds a plain number, `resolved` records it, so a number later edited elsewhere, Figma\n * included, shows the CSS no longer describes it.\n */\nexport interface TokenExpression {\n css: string\n resolved?: number\n}\n\nexport interface Variable {\n id: string\n name: string\n type: VariableType\n collectionId: string\n valuesByMode: Record<string, VariableValue>\n description: string\n hiddenFromPublishing: boolean\n /** Absent means every scope. */\n scopes?: VariableScope[]\n /**\n * Per-platform code snippets, as Figma's Dev Mode shows them. A `WEB` snippet of `--x` or\n * `var(--x)` names the token's CSS custom property; otherwise the name is derived.\n */\n codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>\n /** FLOAT only. Absent means inferred when written as CSS. */\n unit?: TokenUnit\n /** Raw CSS by mode id, for values a number cannot express (`clamp()`, `calc()`). */\n expressions?: Record<string, TokenExpression>\n pluginData?: PluginDataEntry[]\n /** Published library key (from NodeChange.key). Used for assetRef resolution in colorVar. */\n key?: string\n /** Published library version (from NodeChange.version). Used for assetRef resolution in colorVar. */\n version?: string\n /**\n * Deleted as Figma deletes a variable: gone from its collection's `variableIds` and from every\n * list of variables, while layers bound to it still resolve it and the file keeps it.\n */\n deleted?: true\n}\n\n/** Scalar numeric node fields accepted by numeric property controls. */\nexport type NumericNodeProperty = {\n [K in keyof SceneNode]-?: SceneNode[K] extends number ? K : never\n}[keyof SceneNode]\n\nexport interface VariableCollectionMode {\n modeId: string\n name: string\n /**\n * Where the mode applies in CSS: a selector (`[data-theme=\"dark\"]`, `.compact`) or an\n * at-rule prelude (`@media (max-width: 640px)`). Absent means the default for its axis.\n */\n condition?: string\n /** Where Figma lists the mode, as the file saved it; Figma orders a collection's modes by it. */\n sortPosition?: string\n}\n\nexport interface VariableCollection {\n id: string\n name: string\n /** The default mode comes first, as in Figma. */\n modes: VariableCollectionMode[]\n defaultModeId: string\n variableIds: string[]\n /**\n * The attribute that switches a mode with no condition of its own, `data-theme` for\n * `[data-theme=\"dark\"]`. Absent means one named after the collection.\n */\n modeAttribute?: string\n pluginData?: PluginDataEntry[]\n /**\n * Published library key, for a collection the file copies from a library. Such a collection\n * belongs to the library: Figma lists it with the library's, not the file's own.\n */\n key?: string\n /** Published library version, which references by key carry with it. */\n version?: string\n /**\n * Deleted as Figma deletes a collection: gone from every list of collections, with its variables\n * deleted too, while layers bound to them still resolve them and the file keeps them.\n */\n deleted?: true\n}\n\n/** Whether a collection is a library's copy, which takes no variables or modes of the file's. */\nexport function isLibraryCollection(collection: Pick<VariableCollection, 'key'>): boolean {\n return !!collection.key\n}\n\n/** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */\nexport const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\\w-]*$/\n\nexport function isModeAttributeName(name: string): boolean {\n return name.length <= 100 && MODE_ATTRIBUTE_PATTERN.test(name)\n}\n"],"mappings":";;AA+cA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA6rBA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAmCA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAa,wBAAwB;CAAC;CAAO;CAAW;AAAK;;;;;AAO7D,MAAa,cAAc;CAAC;CAAQ;CAAM;CAAO;CAAK;CAAM;CAAK;AAAK;;AAyFtE,SAAgB,oBAAoB,YAAsD;CACxF,OAAO,CAAC,CAAC,WAAW;AACtB;;AAGA,MAAa,yBAAyB;AAEtC,SAAgB,oBAAoB,MAAuB;CACzD,OAAO,KAAK,UAAU,OAAO,uBAAuB,KAAK,IAAI;AAC/D"}
@@ -1,4 +1,5 @@
1
1
  import { VariableModeFallback } from "./resolution.js";
2
+ import { VariableResolver } from "./resolver.js";
2
3
  import { ICON_BINDING_FIELDS, PaintBindingList, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget } from "./fields.js";
3
4
  import { SceneGraph } from "../graph.js";
4
5
  import { SceneNode, TextLength } from "../types.js";
@@ -12,7 +13,7 @@ declare function boundNumberValue(field: string, value: number): number | TextLe
12
13
  * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
13
14
  * whose stored value differs. A width or height an instance overrides keeps its own value.
14
15
  */
15
- declare function resolvedNumericBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback): Partial<SceneNode>;
16
+ declare function resolvedNumericBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback, resolver?: VariableResolver): Partial<SceneNode>;
16
17
  /**
17
18
  * The text, font family, and visibility a node's string and boolean bindings resolve to in its
18
19
  * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance
@@ -20,19 +21,19 @@ declare function resolvedNumericBindings(graph: SceneGraph, node: SceneNode, fal
20
21
  * overridden width or height does. A font family is only named here; the editor loads its faces
21
22
  * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.
22
23
  */
23
- declare function resolvedValueBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback): Partial<SceneNode>;
24
+ declare function resolvedValueBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback, resolver?: VariableResolver): Partial<SceneNode>;
24
25
  /**
25
26
  * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon
26
27
  * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The
27
28
  * caller redraws the frame, as resolving only names the icon.
28
29
  */
29
- declare function resolvedIconBinding(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback): string | undefined;
30
+ declare function resolvedIconBinding(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback, resolver?: VariableResolver): string | undefined;
30
31
  /**
31
32
  * The runs a text's character bindings resolve to in its mode, when a bound number or font family
32
33
  * differs from what its characters hold, a size or spacing in the run's binding scale for the
33
34
  * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.
34
35
  */
35
- declare function resolvedRunBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback): Pick<Partial<SceneNode>, 'styleRuns'>;
36
+ declare function resolvedRunBindings(graph: SceneGraph, node: SceneNode, fallback?: VariableModeFallback, resolver?: VariableResolver): Pick<Partial<SceneNode>, 'styleRuns'>;
36
37
  /**
37
38
  * The layers a reconcile looks at: those bound to these variables, directly or through a variable
38
39
  * aliasing them, or the layers in these subtrees. Without a scope, every layer.
@@ -48,7 +49,7 @@ declare function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<stri
48
49
  * The collections whose variables the layers in these subtrees resolve: those they bind, and
49
50
  * those the bound variables alias, so a mode set on the subtrees can change what they show.
50
51
  */
51
- declare function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string>;
52
+ declare function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>, resolver?: VariableResolver): Set<string>;
52
53
  /**
53
54
  * The layers a change to these variables reaches: those binding one of them, or a variable that
54
55
  * aliases one, on the layer itself or on its characters.
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.d.ts","names":[],"sources":["../../src/variables/bindings.ts"],"mappings":";;;;;;iBA0BgB,qBAAqB,OAAO,YAAY,MAAM,YAAY;iBAW1D,2BACd,OAAO,YACP,MAAM,WACN;;iBAoBc,iBAAiB,eAAe,yBAAyB;;;;;iBAQzD,wBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;;;iBA2BK,sBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;iBAsBK,oBACd,OAAO,YACP,MAAM,WACN,WAAU;;;;;;iBAsBI,oBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,KAAK,QAAQ;;;;;KAwCJ;EAAiB,WAAW;;EAAuB,UAAU;;;iBAGzD,0BAA0B,OAAO,YAAY,KAAK,mBAAmB;;;;;iBAuBrE,mBAAmB,OAAO,YAAY,OAAO,mBAAmB;;;;;iBAQhE,qBAAqB,OAAO,YAAY,KAAK,mBAAmB;;;;;;;;iBAoBhE,0BAA0B,OAAO,YAAY,QAAQ;;KAkBzD;;;;;;iBAOI,sBACd,gBAAgB,SAAS,yBACzB,MAAM,gBACN,sCACC"}
1
+ {"version":3,"file":"bindings.d.ts","names":[],"sources":["../../src/variables/bindings.ts"],"mappings":";;;;;;;iBA0BgB,qBAAqB,OAAO,YAAY,MAAM,YAAY;iBAW1D,2BACd,OAAO,YACP,MAAM,WACN;;iBAoBc,iBAAiB,eAAe,yBAAyB;;;;;iBAazD,wBACd,OAAO,YACP,MAAM,WACN,WAAU,sBACV,WAAW,mBACV,QAAQ;;;;;;;;iBA4BK,sBACd,OAAO,YACP,MAAM,WACN,WAAU,sBACV,WAAW,mBACV,QAAQ;;;;;;iBAuBK,oBACd,OAAO,YACP,MAAM,WACN,WAAU,sBACV,WAAW;;;;;;iBAsBG,oBACd,OAAO,YACP,MAAM,WACN,WAAU,sBACV,WAAW,mBACV,KAAK,QAAQ;;;;;KAuCJ;EAAiB,WAAW;;EAAuB,UAAU;;;iBAGzD,0BAA0B,OAAO,YAAY,KAAK,mBAAmB;;;;;iBAuBrE,mBACd,OAAO,YACP,OAAO,kBACP,WAAW,mBACV;;;;;iBAUa,qBAAqB,OAAO,YAAY,KAAK,mBAAmB;;;;;;;;iBAoBhE,0BAA0B,OAAO,YAAY,QAAQ;;KAmBzD;;;;;;iBAOI,sBACd,gBAAgB,SAAS,yBACzB,MAAM,gBACN,sCACC"}
@@ -5,7 +5,7 @@ import { ICON_NAME } from "../icons/schema.js";
5
5
  import { readIcon } from "../icons/model.js";
6
6
  import { variableFontFamily, variableText, variableTruthy } from "./text.js";
7
7
  import { variableValueReferences } from "./value.js";
8
- import { collectionsResolving } from "./resolution.js";
8
+ import { createVariableResolver } from "./resolver.js";
9
9
  import { subtreeNodes } from "./subtree.js";
10
10
  import { refreshBoundPaints } from "./paints.js";
11
11
  import { runBindingScale } from "./units.js";
@@ -41,16 +41,21 @@ function overriddenInInstance(graph, nodeId, field) {
41
41
  function boundNumberValue(field, value) {
42
42
  return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value;
43
43
  }
44
+ /** One resolver per field lookup, unless a caller reconciling many nodes shares its own. */
45
+ function resolverFor(graph, resolver) {
46
+ return resolver ?? createVariableResolver(graph);
47
+ }
44
48
  /**
45
49
  * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields
46
50
  * whose stored value differs. A width or height an instance overrides keeps its own value.
47
51
  */
48
- function resolvedNumericBindings(graph, node, fallback = "active") {
52
+ function resolvedNumericBindings(graph, node, fallback = "active", resolver) {
49
53
  const updates = {};
54
+ const reader = resolverFor(graph, resolver).forNode(node.id, fallback);
50
55
  for (const [field, variableId] of Object.entries(node.boundVariables)) {
51
56
  if (!NUMERIC_FIELDS.has(field)) continue;
52
57
  if ((field === "width" || field === "height") && overriddenInInstance(graph, node.id, field)) continue;
53
- const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
58
+ const value = reader.number(variableId);
54
59
  if (value === void 0 || !Number.isFinite(value)) continue;
55
60
  const effective = value * (node.variableBindingScales[field] ?? 1);
56
61
  if (!Number.isFinite(effective)) continue;
@@ -66,12 +71,13 @@ function resolvedNumericBindings(graph, node, fallback = "active") {
66
71
  * overridden width or height does. A font family is only named here; the editor loads its faces
67
72
  * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.
68
73
  */
69
- function resolvedValueBindings(graph, node, fallback = "active") {
74
+ function resolvedValueBindings(graph, node, fallback = "active", resolver) {
70
75
  const updates = {};
76
+ const reader = resolverFor(graph, resolver).forNode(node.id, fallback);
71
77
  const resolve = (field) => {
72
78
  const variableId = node.boundVariables[field];
73
79
  if (!variableId || overriddenInInstance(graph, node.id, field)) return void 0;
74
- return graph.resolveVariableForNode(node.id, variableId, fallback);
80
+ return reader.value(variableId);
75
81
  };
76
82
  const text = node.type === "TEXT" ? variableText(resolve("text")) : void 0;
77
83
  if (text !== void 0 && text !== node.text) updates.text = text;
@@ -86,13 +92,13 @@ function resolvedValueBindings(graph, node, fallback = "active") {
86
92
  * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The
87
93
  * caller redraws the frame, as resolving only names the icon.
88
94
  */
89
- function resolvedIconBinding(graph, node, fallback = "active") {
95
+ function resolvedIconBinding(graph, node, fallback = "active", resolver) {
90
96
  if (node.type !== "FRAME") return void 0;
91
97
  const icon = readIcon(node);
92
98
  if (!icon) return void 0;
93
99
  const variableId = node.boundVariables["iconName"];
94
100
  if (!variableId || overriddenInInstance(graph, node.id, "iconName")) return void 0;
95
- const resolved = graph.resolveVariableForNode(node.id, variableId, fallback);
101
+ const resolved = resolverFor(graph, resolver).forNode(node.id, fallback).value(variableId);
96
102
  if (typeof resolved !== "string") return void 0;
97
103
  const name = resolved.trim();
98
104
  if (name === "" || name === icon.name || !ICON_NAME.test(name)) return void 0;
@@ -110,7 +116,8 @@ const NUMERIC_RUN_FIELDS = [
110
116
  * differs from what its characters hold, a size or spacing in the run's binding scale for the
111
117
  * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.
112
118
  */
113
- function resolvedRunBindings(graph, node, fallback = "active") {
119
+ function resolvedRunBindings(graph, node, fallback = "active", resolver) {
120
+ const reader = resolverFor(graph, resolver).forNode(node.id, fallback);
114
121
  const styleRuns = node.styleRuns.map((run) => {
115
122
  const bound = run.style.boundVariables;
116
123
  if (!bound) return run;
@@ -118,7 +125,7 @@ function resolvedRunBindings(graph, node, fallback = "active") {
118
125
  for (const field of NUMERIC_RUN_FIELDS) {
119
126
  const variableId = bound[field];
120
127
  if (!variableId) continue;
121
- const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
128
+ const value = reader.number(variableId);
122
129
  if (value === void 0 || !Number.isFinite(value)) continue;
123
130
  const effective = value * runBindingScale(node, style, field);
124
131
  if (!Number.isFinite(effective)) continue;
@@ -130,7 +137,7 @@ function resolvedRunBindings(graph, node, fallback = "active") {
130
137
  };
131
138
  }
132
139
  const familyId = bound.fontFamily;
133
- const family = familyId ? variableFontFamily(graph.resolveVariableForNode(node.id, familyId, fallback)) : void 0;
140
+ const family = familyId ? variableFontFamily(reader.value(familyId)) : void 0;
134
141
  if (family !== void 0 && family !== style.fontFamily) style = {
135
142
  ...style,
136
143
  fontFamily: family
@@ -166,8 +173,8 @@ function variablesResolvingThrough(graph, ids) {
166
173
  * The collections whose variables the layers in these subtrees resolve: those they bind, and
167
174
  * those the bound variables alias, so a mode set on the subtrees can change what they show.
168
175
  */
169
- function collectionsBoundIn(graph, roots) {
170
- return collectionsResolving(graph, subtreeNodes(graph, roots).flatMap(boundVariableIds));
176
+ function collectionsBoundIn(graph, roots, resolver) {
177
+ return resolverFor(graph, resolver).dependencies(subtreeNodes(graph, roots).flatMap(boundVariableIds));
171
178
  }
172
179
  /**
173
180
  * The layers a change to these variables reaches: those binding one of them, or a variable that
@@ -192,12 +199,13 @@ function scopedNodes(graph, scope) {
192
199
  function reconcileVariableBindings(graph, scope) {
193
200
  const changed = [];
194
201
  const nodes = [...scopedNodes(graph, scope)];
195
- for (const node of nodes) refreshBoundPaints(graph, node);
202
+ const resolver = createVariableResolver(graph);
203
+ for (const node of nodes) refreshBoundPaints(graph, node, resolver);
196
204
  for (const node of nodes) {
197
205
  const updates = {
198
- ...resolvedNumericBindings(graph, node),
199
- ...resolvedValueBindings(graph, node),
200
- ...resolvedRunBindings(graph, node)
206
+ ...resolvedNumericBindings(graph, node, "active", resolver),
207
+ ...resolvedValueBindings(graph, node, "active", resolver),
208
+ ...resolvedRunBindings(graph, node, "active", resolver)
201
209
  };
202
210
  if (Object.keys(updates).length === 0) continue;
203
211
  graph.updateNode(node.id, updates);
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.js","names":[],"sources":["../../src/variables/bindings.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { VariableModeFallback } from '.'\nimport type { SceneGraph } from '../graph'\nimport { readIcon } from '../icons/model'\nimport { ICON_NAME } from '../icons/schema'\nimport { hasInstanceOverride } from '../instances/overrides'\nimport { pixelLength } from '../text/lengths'\nimport type { SceneNode, StyleRun, TextLength } from '../types'\nimport { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'\nimport { refreshBoundPaints } from './paints'\nimport { collectionsResolving } from './resolution'\nimport { subtreeNodes } from './subtree'\nimport { variableFontFamily, variableText, variableTruthy } from './text'\nimport { runBindingScale } from './units'\nimport { variableValueReferences } from './value'\nexport {\n ICON_BINDING_FIELDS,\n isNumericVariableBindingField,\n paintBindingTarget,\n TEXT_CONTENT_VARIABLE_TYPES,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\n\n/** New declarations belong to the outermost occurrence, bounded by a component definition. */\nexport function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {\n let owner = node\n let current: SceneNode | undefined = node\n while (current) {\n if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break\n if (current.type === 'INSTANCE') owner = current\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return owner\n}\n\nexport function assignVariableBindingUnits(\n graph: SceneGraph,\n node: SceneNode,\n field: string\n): void {\n if (!isNumericVariableBindingField(field)) return\n const owner = variableBindingOwner(graph, node)\n node.variableBindingScales = {\n ...node.variableBindingScales,\n [field]: owner.variableAssignmentScales[field] ?? 1\n }\n}\n\n/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */\nconst TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])\n\n/** Whether the instance a layer sits in, or the instance itself, overrides one of its fields. */\nfunction overriddenInInstance(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = graph.closest(nodeId, (node) => node.type === 'INSTANCE')\n return !!instance && hasInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/** A bound number as the field stores it. */\nexport function boundNumberValue(field: string, value: number): number | TextLength {\n return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value\n}\n\n/**\n * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields\n * whose stored value differs. A width or height an instance overrides keeps its own value.\n */\nexport function resolvedNumericBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n if (!NUMERIC_FIELDS.has(field)) continue\n if ((field === 'width' || field === 'height') && overriddenInInstance(graph, node.id, field))\n continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const scale = node.variableBindingScales[field] ?? 1\n const effective = value * scale\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(\n field,\n field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective\n )\n if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })\n }\n return updates\n}\n\n/**\n * The text, font family, and visibility a node's string and boolean bindings resolve to in its\n * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance\n * overrides, which typing in a layer or toggling its eye records, keeps its own value, as an\n * overridden width or height does. A font family is only named here; the editor loads its faces\n * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.\n */\nexport function resolvedValueBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const resolve = (field: 'text' | 'fontFamily' | 'visible') => {\n const variableId = node.boundVariables[field]\n if (!variableId || overriddenInInstance(graph, node.id, field)) return undefined\n return graph.resolveVariableForNode(node.id, variableId, fallback)\n }\n const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined\n if (text !== undefined && text !== node.text) updates.text = text\n const fontFamily = node.type === 'TEXT' ? variableFontFamily(resolve('fontFamily')) : undefined\n if (fontFamily !== undefined && fontFamily !== node.fontFamily) updates.fontFamily = fontFamily\n // Figma binds visibility to text too, and shows the layer when the text reads as true.\n const visible = variableTruthy(resolve('visible'))\n if (visible !== undefined && visible !== node.visible) updates.visible = visible\n return updates\n}\n\n/**\n * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon\n * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The\n * caller redraws the frame, as resolving only names the icon.\n */\nexport function resolvedIconBinding(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n if (node.type !== 'FRAME') return undefined\n const icon = readIcon(node)\n if (!icon) return undefined\n const variableId = node.boundVariables['iconName']\n if (!variableId || overriddenInInstance(graph, node.id, 'iconName')) return undefined\n const resolved = graph.resolveVariableForNode(node.id, variableId, fallback)\n if (typeof resolved !== 'string') return undefined\n const name = resolved.trim()\n if (name === '' || name === icon.name || !ICON_NAME.test(name)) return undefined\n return name\n}\n\n/** Fields of a range of characters a bound number gives its value. */\nconst NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const\n\n/**\n * The runs a text's character bindings resolve to in its mode, when a bound number or font family\n * differs from what its characters hold, a size or spacing in the run's binding scale for the\n * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.\n */\nexport function resolvedRunBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = node.styleRuns.map((run): StyleRun => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let style = run.style\n for (const field of NUMERIC_RUN_FIELDS) {\n const variableId = bound[field]\n if (!variableId) continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const effective = value * runBindingScale(node, style, field)\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(field, effective)\n if (isEqual(style[field], next)) continue\n style = { ...style, [field]: next }\n }\n const familyId = bound.fontFamily\n const family = familyId\n ? variableFontFamily(graph.resolveVariableForNode(node.id, familyId, fallback))\n : undefined\n if (family !== undefined && family !== style.fontFamily)\n style = { ...style, fontFamily: family }\n return style === run.style ? run : { ...run, style }\n })\n const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])\n return changed ? { styleRuns } : {}\n}\n\n/** The variables a node binds, its own and its characters'. */\nfunction boundVariableIds(node: SceneNode): string[] {\n return [\n ...Object.values(node.boundVariables),\n ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))\n ].filter((id): id is string => typeof id === 'string')\n}\n\n/**\n * The layers a reconcile looks at: those bound to these variables, directly or through a variable\n * aliasing them, or the layers in these subtrees. Without a scope, every layer.\n */\nexport type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }\n\n/** These variables and every variable that aliases one of them, at any depth and in any mode. */\nexport function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {\n const found = new Set(ids)\n let grew = true\n while (grew) {\n grew = false\n for (const variable of graph.variables.values()) {\n if (found.has(variable.id)) continue\n const aliases = Object.values(variable.valuesByMode).some((value) =>\n variableValueReferences(value).some((id) => found.has(id))\n )\n if (aliases) {\n found.add(variable.id)\n grew = true\n }\n }\n }\n return found\n}\n\n/**\n * The collections whose variables the layers in these subtrees resolve: those they bind, and\n * those the bound variables alias, so a mode set on the subtrees can change what they show.\n */\nexport function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {\n return collectionsResolving(graph, subtreeNodes(graph, roots).flatMap(boundVariableIds))\n}\n\n/**\n * The layers a change to these variables reaches: those binding one of them, or a variable that\n * aliases one, on the layer itself or on its characters.\n */\nexport function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {\n const variables = variablesResolvingThrough(graph, ids)\n return [...graph.getAllNodes()].filter((node) =>\n boundVariableIds(node).some((id) => variables.has(id))\n )\n}\n\nfunction scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {\n if (!scope) return graph.getAllNodes()\n if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)\n return layersUsingVariables(graph, scope.variables)\n}\n\n/**\n * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, and\n * refresh bound paints whose variable's color for the layer changed (`refreshBoundPaints`),\n * without authoring instance overrides. A scope limits it to the layers a change can reach, so\n * layers whose saved values differ from their bindings elsewhere in the document are left as\n * saved.\n */\nexport function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {\n const changed: string[] = []\n const nodes = [...scopedNodes(graph, scope)]\n for (const node of nodes) refreshBoundPaints(graph, node)\n for (const node of nodes) {\n const updates = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node)\n }\n if (Object.keys(updates).length === 0) continue\n graph.updateNode(node.id, updates)\n changed.push(node.id)\n }\n return changed\n}\n\n/** A layer list whose items carry their own bindings, keyed by position such as `fills/1/color`. */\nexport type BoundLayerList = 'fills' | 'strokes' | 'effects'\n\n/**\n * `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the\n * position the new item `i` had before, or null for an added item. A binding moves with its item\n * and goes with a removed one, as Figma keeps a binding on its paint or effect.\n */\nexport function listBindingsAfterEdit(\n boundVariables: Readonly<Record<string, string>>,\n list: BoundLayerList,\n sources: readonly (number | null)[]\n): Record<string, string> {\n const prefix = `${list}/`\n const moved: Record<string, string> = {}\n for (const [field, variableId] of Object.entries(boundVariables)) {\n if (!field.startsWith(prefix)) {\n moved[field] = variableId\n continue\n }\n const [index, ...property] = field.slice(prefix.length).split('/')\n const next = sources.indexOf(Number(index))\n if (next !== -1 && property.length > 0)\n moved[`${prefix}${next}/${property.join('/')}`] = variableId\n }\n return moved\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAgB,qBAAqB,OAAmB,MAA4B;CAClF,IAAI,QAAQ;CACZ,IAAI,UAAiC;CACrC,OAAO,SAAS;EACd,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,iBAAiB;EACtE,IAAI,QAAQ,SAAS,YAAY,QAAQ;EACzC,UAAU,QAAQ,WAAW,MAAM,QAAQ,QAAQ,QAAQ,IAAI,KAAA;CACjE;CACA,OAAO;AACT;AAEA,SAAgB,2BACd,OACA,MACA,OACM;CACN,IAAI,CAAC,8BAA8B,KAAK,GAAG;CAC3C,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,KAAK,wBAAwB;EAC3B,GAAG,KAAK;GACP,QAAQ,MAA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AAM,SAAS,GAAG,KAAK;CACvB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,cAAc,GAAG;EAChE,IAAI,CAAC,MAAM,WAAW,MAAM,GAAG;GAC7B,MAAM,SAAS;GACf;EACF;EACA,MAAM,CAAC,OAAO,GAAG,YAAY,MAAM,MAAM,OAAO,MAAM,CAAC,CAAC,MAAM,GAAG;EACjE,MAAM,OAAO,QAAQ,QAAQ,OAAO,KAAK,CAAC;EAC1C,IAAI,SAAS,MAAM,SAAS,SAAS,GACnC,MAAM,GAAG,SAAS,KAAK,GAAG,SAAS,KAAK,GAAG,OAAO;CACtD;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"bindings.js","names":[],"sources":["../../src/variables/bindings.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { VariableModeFallback } from '.'\nimport type { SceneGraph } from '../graph'\nimport { readIcon } from '../icons/model'\nimport { ICON_NAME } from '../icons/schema'\nimport { hasInstanceOverride } from '../instances/overrides'\nimport { pixelLength } from '../text/lengths'\nimport type { SceneNode, StyleRun, TextLength } from '../types'\nimport { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'\nimport { refreshBoundPaints } from './paints'\nimport { createVariableResolver, type VariableResolver } from './resolver'\nimport { subtreeNodes } from './subtree'\nimport { variableFontFamily, variableText, variableTruthy } from './text'\nimport { runBindingScale } from './units'\nimport { variableValueReferences } from './value'\nexport {\n ICON_BINDING_FIELDS,\n isNumericVariableBindingField,\n paintBindingTarget,\n TEXT_CONTENT_VARIABLE_TYPES,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\n\n/** New declarations belong to the outermost occurrence, bounded by a component definition. */\nexport function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {\n let owner = node\n let current: SceneNode | undefined = node\n while (current) {\n if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break\n if (current.type === 'INSTANCE') owner = current\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return owner\n}\n\nexport function assignVariableBindingUnits(\n graph: SceneGraph,\n node: SceneNode,\n field: string\n): void {\n if (!isNumericVariableBindingField(field)) return\n const owner = variableBindingOwner(graph, node)\n node.variableBindingScales = {\n ...node.variableBindingScales,\n [field]: owner.variableAssignmentScales[field] ?? 1\n }\n}\n\n/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */\nconst TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])\n\n/** Whether the instance a layer sits in, or the instance itself, overrides one of its fields. */\nfunction overriddenInInstance(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = graph.closest(nodeId, (node) => node.type === 'INSTANCE')\n return !!instance && hasInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/** A bound number as the field stores it. */\nexport function boundNumberValue(field: string, value: number): number | TextLength {\n return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value\n}\n\n/** One resolver per field lookup, unless a caller reconciling many nodes shares its own. */\nfunction resolverFor(graph: SceneGraph, resolver?: VariableResolver): VariableResolver {\n return resolver ?? createVariableResolver(graph)\n}\n\n/**\n * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields\n * whose stored value differs. A width or height an instance overrides keeps its own value.\n */\nexport function resolvedNumericBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active',\n resolver?: VariableResolver\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const reader = resolverFor(graph, resolver).forNode(node.id, fallback)\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n if (!NUMERIC_FIELDS.has(field)) continue\n if ((field === 'width' || field === 'height') && overriddenInInstance(graph, node.id, field))\n continue\n const value = reader.number(variableId)\n if (value === undefined || !Number.isFinite(value)) continue\n const scale = node.variableBindingScales[field] ?? 1\n const effective = value * scale\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(\n field,\n field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective\n )\n if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })\n }\n return updates\n}\n\n/**\n * The text, font family, and visibility a node's string and boolean bindings resolve to in its\n * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance\n * overrides, which typing in a layer or toggling its eye records, keeps its own value, as an\n * overridden width or height does. A font family is only named here; the editor loads its faces\n * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.\n */\nexport function resolvedValueBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active',\n resolver?: VariableResolver\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const reader = resolverFor(graph, resolver).forNode(node.id, fallback)\n const resolve = (field: 'text' | 'fontFamily' | 'visible') => {\n const variableId = node.boundVariables[field]\n if (!variableId || overriddenInInstance(graph, node.id, field)) return undefined\n return reader.value(variableId)\n }\n const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined\n if (text !== undefined && text !== node.text) updates.text = text\n const fontFamily = node.type === 'TEXT' ? variableFontFamily(resolve('fontFamily')) : undefined\n if (fontFamily !== undefined && fontFamily !== node.fontFamily) updates.fontFamily = fontFamily\n // Figma binds visibility to text too, and shows the layer when the text reads as true.\n const visible = variableTruthy(resolve('visible'))\n if (visible !== undefined && visible !== node.visible) updates.visible = visible\n return updates\n}\n\n/**\n * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon\n * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The\n * caller redraws the frame, as resolving only names the icon.\n */\nexport function resolvedIconBinding(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active',\n resolver?: VariableResolver\n): string | undefined {\n if (node.type !== 'FRAME') return undefined\n const icon = readIcon(node)\n if (!icon) return undefined\n const variableId = node.boundVariables['iconName']\n if (!variableId || overriddenInInstance(graph, node.id, 'iconName')) return undefined\n const resolved = resolverFor(graph, resolver).forNode(node.id, fallback).value(variableId)\n if (typeof resolved !== 'string') return undefined\n const name = resolved.trim()\n if (name === '' || name === icon.name || !ICON_NAME.test(name)) return undefined\n return name\n}\n\n/** Fields of a range of characters a bound number gives its value. */\nconst NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const\n\n/**\n * The runs a text's character bindings resolve to in its mode, when a bound number or font family\n * differs from what its characters hold, a size or spacing in the run's binding scale for the\n * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.\n */\nexport function resolvedRunBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active',\n resolver?: VariableResolver\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const reader = resolverFor(graph, resolver).forNode(node.id, fallback)\n const styleRuns = node.styleRuns.map((run): StyleRun => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let style = run.style\n for (const field of NUMERIC_RUN_FIELDS) {\n const variableId = bound[field]\n if (!variableId) continue\n const value = reader.number(variableId)\n if (value === undefined || !Number.isFinite(value)) continue\n const effective = value * runBindingScale(node, style, field)\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(field, effective)\n if (isEqual(style[field], next)) continue\n style = { ...style, [field]: next }\n }\n const familyId = bound.fontFamily\n const family = familyId ? variableFontFamily(reader.value(familyId)) : undefined\n if (family !== undefined && family !== style.fontFamily)\n style = { ...style, fontFamily: family }\n return style === run.style ? run : { ...run, style }\n })\n const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])\n return changed ? { styleRuns } : {}\n}\n\n/** The variables a node binds, its own and its characters'. */\nfunction boundVariableIds(node: SceneNode): string[] {\n return [\n ...Object.values(node.boundVariables),\n ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))\n ].filter((id): id is string => typeof id === 'string')\n}\n\n/**\n * The layers a reconcile looks at: those bound to these variables, directly or through a variable\n * aliasing them, or the layers in these subtrees. Without a scope, every layer.\n */\nexport type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }\n\n/** These variables and every variable that aliases one of them, at any depth and in any mode. */\nexport function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {\n const found = new Set(ids)\n let grew = true\n while (grew) {\n grew = false\n for (const variable of graph.variables.values()) {\n if (found.has(variable.id)) continue\n const aliases = Object.values(variable.valuesByMode).some((value) =>\n variableValueReferences(value).some((id) => found.has(id))\n )\n if (aliases) {\n found.add(variable.id)\n grew = true\n }\n }\n }\n return found\n}\n\n/**\n * The collections whose variables the layers in these subtrees resolve: those they bind, and\n * those the bound variables alias, so a mode set on the subtrees can change what they show.\n */\nexport function collectionsBoundIn(\n graph: SceneGraph,\n roots: Iterable<string>,\n resolver?: VariableResolver\n): Set<string> {\n return resolverFor(graph, resolver).dependencies(\n subtreeNodes(graph, roots).flatMap(boundVariableIds)\n )\n}\n\n/**\n * The layers a change to these variables reaches: those binding one of them, or a variable that\n * aliases one, on the layer itself or on its characters.\n */\nexport function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {\n const variables = variablesResolvingThrough(graph, ids)\n return [...graph.getAllNodes()].filter((node) =>\n boundVariableIds(node).some((id) => variables.has(id))\n )\n}\n\nfunction scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {\n if (!scope) return graph.getAllNodes()\n if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)\n return layersUsingVariables(graph, scope.variables)\n}\n\n/**\n * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, and\n * refresh bound paints whose variable's color for the layer changed (`refreshBoundPaints`),\n * without authoring instance overrides. A scope limits it to the layers a change can reach, so\n * layers whose saved values differ from their bindings elsewhere in the document are left as\n * saved.\n */\nexport function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {\n const changed: string[] = []\n const nodes = [...scopedNodes(graph, scope)]\n const resolver = createVariableResolver(graph)\n for (const node of nodes) refreshBoundPaints(graph, node, resolver)\n for (const node of nodes) {\n const updates = {\n ...resolvedNumericBindings(graph, node, 'active', resolver),\n ...resolvedValueBindings(graph, node, 'active', resolver),\n ...resolvedRunBindings(graph, node, 'active', resolver)\n }\n if (Object.keys(updates).length === 0) continue\n graph.updateNode(node.id, updates)\n changed.push(node.id)\n }\n return changed\n}\n\n/** A layer list whose items carry their own bindings, keyed by position such as `fills/1/color`. */\nexport type BoundLayerList = 'fills' | 'strokes' | 'effects'\n\n/**\n * `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the\n * position the new item `i` had before, or null for an added item. A binding moves with its item\n * and goes with a removed one, as Figma keeps a binding on its paint or effect.\n */\nexport function listBindingsAfterEdit(\n boundVariables: Readonly<Record<string, string>>,\n list: BoundLayerList,\n sources: readonly (number | null)[]\n): Record<string, string> {\n const prefix = `${list}/`\n const moved: Record<string, string> = {}\n for (const [field, variableId] of Object.entries(boundVariables)) {\n if (!field.startsWith(prefix)) {\n moved[field] = variableId\n continue\n }\n const [index, ...property] = field.slice(prefix.length).split('/')\n const next = sources.indexOf(Number(index))\n if (next !== -1 && property.length > 0)\n moved[`${prefix}${next}/${property.join('/')}`] = variableId\n }\n return moved\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAgB,qBAAqB,OAAmB,MAA4B;CAClF,IAAI,QAAQ;CACZ,IAAI,UAAiC;CACrC,OAAO,SAAS;EACd,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,iBAAiB;EACtE,IAAI,QAAQ,SAAS,YAAY,QAAQ;EACzC,UAAU,QAAQ,WAAW,MAAM,QAAQ,QAAQ,QAAQ,IAAI,KAAA;CACjE;CACA,OAAO;AACT;AAEA,SAAgB,2BACd,OACA,MACA,OACM;CACN,IAAI,CAAC,8BAA8B,KAAK,GAAG;CAC3C,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,KAAK,wBAAwB;EAC3B,GAAG,KAAK;GACP,QAAQ,MAAM,yBAAyB,UAAU;CACpD;AACF;;AAGA,MAAM,qCAA0C,IAAI,IAAI,CAAC,cAAc,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AM,UAAU,QAAQ;GAC1D,GAAG,sBAAsB,OAAO,MAAM,UAAU,QAAQ;GACxD,GAAG,oBAAoB,OAAO,MAAM,UAAU,QAAQ;EACxD;EACA,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI,OAAO;EACjC,QAAQ,KAAK,KAAK,EAAE;CACtB;CACA,OAAO;AACT;;;;;;AAUA,SAAgB,sBACd,gBACA,MACA,SACwB;CACxB,MAAM,SAAS,GAAG,KAAK;CACvB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,cAAc,GAAG;EAChE,IAAI,CAAC,MAAM,WAAW,MAAM,GAAG;GAC7B,MAAM,SAAS;GACf;EACF;EACA,MAAM,CAAC,OAAO,GAAG,YAAY,MAAM,MAAM,OAAO,MAAM,CAAC,CAAC,MAAM,GAAG;EACjE,MAAM,OAAO,QAAQ,QAAQ,OAAO,KAAK,CAAC;EAC1C,IAAI,SAAS,MAAM,SAAS,SAAS,GACnC,MAAM,GAAG,SAAS,KAAK,GAAG,SAAS,KAAK,GAAG,OAAO;CACtD;CACA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/variables/formula/index.ts"],"mappings":";;;;;;;;;;iBAsCgB,yBAAyB,OAAO,YAAY;;iBAmB5C,sBACd,OAAO,YACP,OAAO,eACP,UAAU;;iBAqCI,qBACd,OAAO,YACP,oBACA,gBACA;EACG,OAAO;EAAe,UAAU"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/variables/formula/index.ts"],"mappings":";;;;;;;;;;iBAsCgB,yBAAyB,OAAO,YAAY;;iBAsB5C,sBACd,OAAO,YACP,OAAO,eACP,UAAU;;iBAsCI,qBACd,OAAO,YACP,oBACA,gBACA;EACG,OAAO;EAAe,UAAU"}
@@ -2,7 +2,7 @@ import { MAX_FORMULA_DEPTH, VariableFormulaError, foldFormula, isFormulaOperatio
2
2
  import { formulaArity, formulaSymbol } from "./signatures.js";
3
3
  import { formulaValueType, inferFormulaType } from "./check.js";
4
4
  import { evaluateVariableFormula } from "./evaluate.js";
5
- import { resolveVariableInModes } from "../resolution.js";
5
+ import { createVariableResolver } from "../resolver.js";
6
6
  import { formulaTokenName, formulaTokens, readFormulaToken } from "./tokens.js";
7
7
  import { parseFormulaSyntax } from "./parse.js";
8
8
  import { printFormula } from "./print.js";
@@ -15,10 +15,10 @@ function qualifiedName(graph, id) {
15
15
  /** Qualified names disambiguate references; the stored formula uses stable IDs. */
16
16
  function variableFormulaReference(graph, id) {
17
17
  const variable = graph.variables.get(id);
18
- if (!variable) return `{#${id}}`;
19
- const unique = (name, of) => [...graph.variables.keys()].filter((other) => of(other) === name).length === 1;
18
+ if (!variable || variable.deleted) return `{#${id}}`;
19
+ const unique = (name, of) => graph.getLiveVariables().filter((other) => of(other.id) === name).length === 1;
20
20
  const plain = variable.name;
21
- if (!/[{}]/.test(plain) && plain.trim() === plain && unique(plain, (other) => graph.variables.get(other)?.name)) return `{${plain}}`;
21
+ if (!/[{}]/.test(plain) && !plain.startsWith("#") && plain.trim() === plain && unique(plain, (other) => graph.variables.get(other)?.name)) return `{${plain}}`;
22
22
  const qualified = qualifiedName(graph, id) ?? "";
23
23
  return /[{}]/.test(qualified) || !unique(qualified, (other) => qualifiedName(graph, other)) ? `{#${id}}` : `{${qualified}}`;
24
24
  }
@@ -37,7 +37,12 @@ function formatVariableFormula(graph, value, options) {
37
37
  * edited variable's own collection when a name appears in several.
38
38
  */
39
39
  function resolveReference(graph, collectionId, name) {
40
- const candidates = [...graph.variables.values()].filter((candidate) => name === `#${candidate.id}` || name === qualifiedName(graph, candidate.id) || name === candidate.name);
40
+ const byId = name.startsWith("#") ? graph.variables.get(name.slice(1)) : void 0;
41
+ if (byId) return {
42
+ id: byId.id,
43
+ type: byId.type
44
+ };
45
+ const candidates = graph.getLiveVariables().filter((candidate) => name === qualifiedName(graph, candidate.id) || name === candidate.name);
41
46
  const local = candidates.filter((candidate) => candidate.collectionId === collectionId);
42
47
  const matches = local.length === 1 ? local : candidates;
43
48
  const match = matches.at(0);
@@ -66,9 +71,10 @@ function parseVariableFormula(graph, variableId, modeId, source) {
66
71
  type: variable.type,
67
72
  value: node
68
73
  } : node;
74
+ const resolver = createVariableResolver(graph, { overrides: /* @__PURE__ */ new Map([[variableId, value]]) });
69
75
  return {
70
76
  value,
71
- resolved: resolveVariableInModes(graph, variableId, (collectionId) => collectionId === variable.collectionId ? modeId : graph.getActiveModeId(collectionId), /* @__PURE__ */ new Set(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map([[variableId, value]]))
77
+ resolved: resolver.forModes((collectionId) => collectionId === variable.collectionId ? modeId : resolver.activeMode(collectionId)).resolve(variableId)
72
78
  };
73
79
  }
74
80
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/variables/formula/index.ts"],"sourcesContent":["import type { SceneGraph } from '#scene-graph/graph'\nimport type { VariableLiteral, VariableValue } from '#scene-graph/types'\n\nimport { resolveVariableInModes } from '../resolution'\nimport { parseFormulaSyntax, type FormulaReference } from './parse'\nimport { printFormula, type PrintFormulaOptions } from './print'\nimport type { FormulaValueType } from './signatures'\nimport { isFormulaOperation, VariableFormulaError } from './tree'\n\nexport { printFormula, type PrintFormulaOptions } from './print'\nexport {\n formulaTokenName,\n formulaTokens,\n readFormulaToken,\n type FormulaToken,\n type FormulaTokenKind\n} from './tokens'\n\nexport { evaluateVariableFormula } from './evaluate'\nexport { formulaValueType, inferFormulaType } from './check'\nexport { formulaArity, formulaSymbol, type FormulaValueType } from './signatures'\nexport {\n foldFormula,\n isFormulaOperation,\n isFormulaReference,\n MAX_FORMULA_DEPTH,\n VariableFormulaError,\n type FormulaFold\n} from './tree'\n\nfunction qualifiedName(graph: SceneGraph, id: string) {\n const variable = graph.variables.get(id)\n if (!variable) return undefined\n const collection = graph.variableCollections.get(variable.collectionId)\n return `${collection?.name ?? variable.collectionId}::${variable.name}`\n}\n\n/** Qualified names disambiguate references; the stored formula uses stable IDs. */\nexport function variableFormulaReference(graph: SceneGraph, id: string): string {\n const variable = graph.variables.get(id)\n if (!variable) return `{#${id}}`\n const unique = (name: string, of: (id: string) => string | undefined) =>\n [...graph.variables.keys()].filter((other) => of(other) === name).length === 1\n const plain = variable.name\n if (\n !/[{}]/.test(plain) &&\n plain.trim() === plain &&\n unique(plain, (other) => graph.variables.get(other)?.name)\n )\n return `{${plain}}`\n const qualified = qualifiedName(graph, id) ?? ''\n return /[{}]/.test(qualified) || !unique(qualified, (other) => qualifiedName(graph, other))\n ? `{#${id}}`\n : `{${qualified}}`\n}\n\n/** The formula's source text, with `{name}` for each reference, as the clipboard and scripts write it; text is quoted. */\nexport function formatVariableFormula(\n graph: SceneGraph,\n value: VariableValue,\n options?: PrintFormulaOptions\n): string {\n const reference = (id: string) => variableFormulaReference(graph, id)\n const typed = { type: (id: string) => graph.variables.get(id)?.type, ...options }\n if (typeof value !== 'object' || !('expression' in value))\n return printFormula(value, reference, typed)\n return value.expression === 'FORMULA' ? printFormula(value.value, reference, typed) : ''\n}\n\n/**\n * Find the variable a reference names: `#id`, `Collection::name`, or a name, preferring the\n * edited variable's own collection when a name appears in several.\n */\nfunction resolveReference(graph: SceneGraph, collectionId: string, name: string): FormulaReference {\n const candidates = [...graph.variables.values()].filter(\n (candidate) =>\n name === `#${candidate.id}` ||\n name === qualifiedName(graph, candidate.id) ||\n name === candidate.name\n )\n const local = candidates.filter((candidate) => candidate.collectionId === collectionId)\n const matches = local.length === 1 ? local : candidates\n const match = matches.at(0)\n if (!match) throw new VariableFormulaError(`No variable named ${name}`)\n if (matches.length !== 1)\n throw new VariableFormulaError(`More than one variable is named ${name}`)\n return { id: match.id, type: match.type }\n}\n\nconst TYPE_NAMES: Record<FormulaValueType, string> = {\n FLOAT: 'a number',\n BOOLEAN: 'true or false',\n STRING: 'text',\n COLOR: 'a color'\n}\n\n/** Validate a draft without changing the document. Formulas operate on stored units. */\nexport function parseVariableFormula(\n graph: SceneGraph,\n variableId: string,\n modeId: string,\n source: string\n): { value: VariableValue; resolved: VariableLiteral } {\n const variable = graph.variables.get(variableId)\n if (!variable) throw new VariableFormulaError('Select a variable')\n const collection = graph.variableCollections.get(variable.collectionId)\n if (!collection?.modes.some((mode) => mode.modeId === modeId))\n throw new VariableFormulaError('Unknown variable mode')\n const { node, type } = parseFormulaSyntax(source, (name) =>\n resolveReference(graph, variable.collectionId, name)\n )\n if (type !== variable.type)\n throw new VariableFormulaError(\n `This gives ${TYPE_NAMES[type]}, but ${variable.name} holds ${TYPE_NAMES[variable.type]}`\n )\n const value: VariableValue = isFormulaOperation(node)\n ? { expression: 'FORMULA', type: variable.type, value: node }\n : node\n const resolved = resolveVariableInModes(\n graph,\n variableId,\n (collectionId) =>\n collectionId === variable.collectionId ? modeId : graph.getActiveModeId(collectionId),\n new Set(),\n new Map(),\n new Map([[variableId, value]])\n )\n return { value, resolved }\n}\n"],"mappings":";;;;;;;;;AA8BA,SAAS,cAAc,OAAmB,IAAY;CACpD,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;CACvC,IAAI,CAAC,UAAU,OAAO,KAAA;CAEtB,OAAO,GADY,MAAM,oBAAoB,IAAI,SAAS,YACvC,CAAC,EAAE,QAAQ,SAAS,aAAa,IAAI,SAAS;AACnE;;AAGA,SAAgB,yBAAyB,OAAmB,IAAoB;CAC9E,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;CACvC,IAAI,CAAC,UAAU,OAAO,KAAK,GAAG;CAC9B,MAAM,UAAU,MAAc,OAC5B,CAAC,GAAG,MAAM,UAAU,KAAK,CAAC,CAAC,CAAC,QAAQ,UAAU,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC,WAAW;CAC/E,MAAM,QAAQ,SAAS;CACvB,IACE,CAAC,OAAO,KAAK,KAAK,KAClB,MAAM,KAAK,MAAM,SACjB,OAAO,QAAQ,UAAU,MA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U,IAAI,UAAU;CAC/C,IAAI,CAAC,UAAU,MAAM,IAAI,qBAAqB,mBAAmB;CAEjE,IAAI,CADe,MAAM,oBAAoB,IAAI,SAAS,YAC5C,CAAC,EAAE,MAAM,MAAM,SAAS,KAAK,WAAW,MAAM,GAC1D,MAAM,IAAI,qBAAqB,uBAAuB;CACxD,MAAM,EAAE,MAAM,SAAS,mBAAmB,SAAS,SACjD,iBAAiB,OAAO,SAAS,cAAc,IAAI,CACrD;CACA,IAAI,SAAS,SAAS,MACpB,MAAM,IAAI,qBACR,cAAc,WAAW,MAAM,QAAQ,SAAS,KAAK,SAAS,WAAW,SAAS,OACpF;CACF,MAAM,QAAuB,mBAAmB,IAAI,IAChD;EAAE,YAAY;EAAW,MAAM,SAAS;EAAM,OAAO;CAAK,IAC1D;CAUJ,OAAO;EAAE;EAAO,UATC,uBACf,OACA,aACC,iBACC,iBAAiB,SAAS,eAAe,SAAS,MAAM,gBAAgB,YAAY,mBACtF,IAAI,IAAI,mBACR,IAAI,IAAI,mBACR,IAAI,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAER;CAAE;AAC3B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/variables/formula/index.ts"],"sourcesContent":["import type { SceneGraph } from '#scene-graph/graph'\nimport type { VariableLiteral, VariableValue } from '#scene-graph/types'\n\nimport { createVariableResolver } from '../resolver'\nimport { parseFormulaSyntax, type FormulaReference } from './parse'\nimport { printFormula, type PrintFormulaOptions } from './print'\nimport type { FormulaValueType } from './signatures'\nimport { isFormulaOperation, VariableFormulaError } from './tree'\n\nexport { printFormula, type PrintFormulaOptions } from './print'\nexport {\n formulaTokenName,\n formulaTokens,\n readFormulaToken,\n type FormulaToken,\n type FormulaTokenKind\n} from './tokens'\n\nexport { evaluateVariableFormula } from './evaluate'\nexport { formulaValueType, inferFormulaType } from './check'\nexport { formulaArity, formulaSymbol, type FormulaValueType } from './signatures'\nexport {\n foldFormula,\n isFormulaOperation,\n isFormulaReference,\n MAX_FORMULA_DEPTH,\n VariableFormulaError,\n type FormulaFold\n} from './tree'\n\nfunction qualifiedName(graph: SceneGraph, id: string) {\n const variable = graph.variables.get(id)\n if (!variable) return undefined\n const collection = graph.variableCollections.get(variable.collectionId)\n return `${collection?.name ?? variable.collectionId}::${variable.name}`\n}\n\n/** Qualified names disambiguate references; the stored formula uses stable IDs. */\nexport function variableFormulaReference(graph: SceneGraph, id: string): string {\n const variable = graph.variables.get(id)\n // A deleted variable's name no longer names it, so only its ID does.\n if (!variable || variable.deleted) return `{#${id}}`\n const unique = (name: string, of: (id: string) => string | undefined) =>\n graph.getLiveVariables().filter((other) => of(other.id) === name).length === 1\n const plain = variable.name\n if (\n !/[{}]/.test(plain) &&\n // A name that starts like an ID would be read as one.\n !plain.startsWith('#') &&\n plain.trim() === plain &&\n unique(plain, (other) => graph.variables.get(other)?.name)\n )\n return `{${plain}}`\n const qualified = qualifiedName(graph, id) ?? ''\n return /[{}]/.test(qualified) || !unique(qualified, (other) => qualifiedName(graph, other))\n ? `{#${id}}`\n : `{${qualified}}`\n}\n\n/** The formula's source text, with `{name}` for each reference, as the clipboard and scripts write it; text is quoted. */\nexport function formatVariableFormula(\n graph: SceneGraph,\n value: VariableValue,\n options?: PrintFormulaOptions\n): string {\n const reference = (id: string) => variableFormulaReference(graph, id)\n const typed = { type: (id: string) => graph.variables.get(id)?.type, ...options }\n if (typeof value !== 'object' || !('expression' in value))\n return printFormula(value, reference, typed)\n return value.expression === 'FORMULA' ? printFormula(value.value, reference, typed) : ''\n}\n\n/**\n * Find the variable a reference names: `#id`, `Collection::name`, or a name, preferring the\n * edited variable's own collection when a name appears in several.\n */\nfunction resolveReference(graph: SceneGraph, collectionId: string, name: string): FormulaReference {\n // An ID names its variable before any name does; a deleted variable is reached only by it, as\n // a formula saved before the deletion names it.\n const byId = name.startsWith('#') ? graph.variables.get(name.slice(1)) : undefined\n if (byId) return { id: byId.id, type: byId.type }\n const candidates = graph\n .getLiveVariables()\n .filter((candidate) => name === qualifiedName(graph, candidate.id) || name === candidate.name)\n const local = candidates.filter((candidate) => candidate.collectionId === collectionId)\n const matches = local.length === 1 ? local : candidates\n const match = matches.at(0)\n if (!match) throw new VariableFormulaError(`No variable named ${name}`)\n if (matches.length !== 1)\n throw new VariableFormulaError(`More than one variable is named ${name}`)\n return { id: match.id, type: match.type }\n}\n\nconst TYPE_NAMES: Record<FormulaValueType, string> = {\n FLOAT: 'a number',\n BOOLEAN: 'true or false',\n STRING: 'text',\n COLOR: 'a color'\n}\n\n/** Validate a draft without changing the document. Formulas operate on stored units. */\nexport function parseVariableFormula(\n graph: SceneGraph,\n variableId: string,\n modeId: string,\n source: string\n): { value: VariableValue; resolved: VariableLiteral } {\n const variable = graph.variables.get(variableId)\n if (!variable) throw new VariableFormulaError('Select a variable')\n const collection = graph.variableCollections.get(variable.collectionId)\n if (!collection?.modes.some((mode) => mode.modeId === modeId))\n throw new VariableFormulaError('Unknown variable mode')\n const { node, type } = parseFormulaSyntax(source, (name) =>\n resolveReference(graph, variable.collectionId, name)\n )\n if (type !== variable.type)\n throw new VariableFormulaError(\n `This gives ${TYPE_NAMES[type]}, but ${variable.name} holds ${TYPE_NAMES[variable.type]}`\n )\n const value: VariableValue = isFormulaOperation(node)\n ? { expression: 'FORMULA', type: variable.type, value: node }\n : node\n const resolver = createVariableResolver(graph, { overrides: new Map([[variableId, value]]) })\n const resolved = resolver\n .forModes((collectionId) =>\n collectionId === variable.collectionId ? modeId : resolver.activeMode(collectionId)\n )\n .resolve(variableId)\n return { value, resolved }\n}\n"],"mappings":";;;;;;;;;AA8BA,SAAS,cAAc,OAAmB,IAAY;CACpD,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;CACvC,IAAI,CAAC,UAAU,OAAO,KAAA;CAEtB,OAAO,GADY,MAAM,oBAAoB,IAAI,SAAS,YACvC,CAAC,EAAE,QAAQ,SAAS,aAAa,IAAI,SAAS;AACnE;;AAGA,SAAgB,yBAAyB,OAAmB,IAAo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