@pairdraw/scene-graph 0.19.0 → 0.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/behaviours/index.d.ts +2 -2
- package/dist/behaviours/index.js +2 -2
- package/dist/behaviours/spec.d.ts +6 -1
- package/dist/behaviours/spec.d.ts.map +1 -1
- package/dist/behaviours/spec.js +62 -5
- package/dist/behaviours/spec.js.map +1 -1
- package/dist/canvas-layout.js +66 -0
- package/dist/canvas-layout.js.map +1 -0
- package/dist/coordinate.js +1 -1
- package/dist/css/index.d.ts +2 -2
- package/dist/css/index.js +2 -2
- package/dist/css/text.d.ts +6 -1
- package/dist/css/text.d.ts.map +1 -1
- package/dist/css/text.js +20 -1
- package/dist/css/text.js.map +1 -1
- package/dist/generated/index.d.ts +2 -2
- package/dist/generated/index.js +2 -2
- package/dist/generated/shape-with-text.d.ts +7 -2
- package/dist/generated/shape-with-text.d.ts.map +1 -1
- package/dist/generated/shape-with-text.js +20 -3
- package/dist/generated/shape-with-text.js.map +1 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +11 -5
- package/dist/graph.js.map +1 -1
- package/dist/group-bounds.d.ts +4 -1
- package/dist/group-bounds.d.ts.map +1 -1
- package/dist/group-bounds.js +11 -1
- package/dist/group-bounds.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +47 -24
- package/dist/hit-test.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/node-defaults.d.ts +21 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +22 -14
- package/dist/node-defaults.js.map +1 -1
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +3 -6
- package/dist/resize.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +23 -3
- package/dist/scaling/node.js.map +1 -1
- package/dist/shared-styles.d.ts +3 -1
- package/dist/shared-styles.d.ts.map +1 -1
- package/dist/shared-styles.js +7 -1
- package/dist/shared-styles.js.map +1 -1
- package/dist/text/path.js +11 -0
- package/dist/text/path.js.map +1 -0
- package/dist/text/picture.d.ts.map +1 -1
- package/dist/text/picture.js +5 -5
- package/dist/text/picture.js.map +1 -1
- package/dist/transfer/copied.d.ts +14 -0
- package/dist/transfer/copied.d.ts.map +1 -0
- package/dist/transfer/copied.js +52 -0
- package/dist/transfer/copied.js.map +1 -0
- package/dist/transfer/index.d.ts +2 -1
- package/dist/transfer/index.js +2 -1
- package/dist/transfer/nodes.js +7 -0
- package/dist/transfer/nodes.js.map +1 -1
- package/dist/types.d.ts +3 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/undo.d.ts +6 -0
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +13 -0
- package/dist/undo.js.map +1 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js.map +1 -1
- package/package.json +1 -1
- package/src/behaviours/spec.ts +94 -4
- package/src/canvas-layout.ts +76 -0
- package/src/css/index.ts +6 -1
- package/src/css/text.ts +24 -0
- package/src/generated/shape-with-text.ts +28 -2
- package/src/graph.ts +14 -4
- package/src/group-bounds.ts +13 -0
- package/src/hit-test.ts +95 -39
- package/src/node-defaults.ts +22 -13
- package/src/resize.ts +3 -14
- package/src/scaling/node.ts +27 -3
- package/src/shared-styles.ts +8 -0
- package/src/text/path.ts +14 -0
- package/src/text/picture.ts +5 -2
- package/src/transfer/copied.ts +72 -0
- package/src/transfer/index.ts +1 -0
- package/src/transfer/nodes.ts +10 -0
- package/src/types.ts +2 -1
- package/src/undo.ts +11 -0
- package/src/variables/index.ts +1 -4
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\nexport interface SourceMetadata {\n format: 'fig' | null\n id: string | null\n orderKey: string | null\n editedFields: string[]\n fig: FigmaSourcePayload\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, kept and saved; the canvas does not draw them. */\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'\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\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/** 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/** How a prototype reaction starts, as `.fig` keeps `PrototypeEvent.interactionType`. */\nexport type PrototypeTriggerType = 'ON_CLICK' | 'AFTER_TIMEOUT'\n\n/** What a reaction does, as `.fig` keeps `ConnectionType` on `PrototypeAction`. */\nexport type PrototypeActionType = 'NODE' | 'BACK' | 'CLOSE'\n\n/** Whether an action moves to a frame or opens it over the screen, as `NavigationType`. */\nexport type PrototypeNavigationType = 'NAVIGATE' | 'OVERLAY'\n\n/** How a reaction animates between frames, as `TransitionType` keeps them. */\nexport type PrototypeTransitionType = 'INSTANT' | 'DISSOLVE'\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, and how long it takes in seconds. */\nexport interface PrototypeTransition {\n type: PrototypeTransitionType\n duration: number\n}\n\n/** A reaction's move to another frame, or the overlay it opens. */\nexport interface PrototypeNodeAction {\n type: 'NODE'\n /** The frame the action shows; `null` keeps the connection when its target is gone. */\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 does. */\nexport interface PrototypeTrigger {\n type: PrototypeTriggerType\n /** AFTER_TIMEOUT only: 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\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: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE' | 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":";;AAwYA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA0oBA,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\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\nexport interface SourceMetadata {\n format: 'fig' | null\n id: string | null\n orderKey: string | null\n editedFields: string[]\n fig: FigmaSourcePayload\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, kept and saved; the canvas does not draw them. */\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\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/** 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/** How a prototype reaction starts, as `.fig` keeps `PrototypeEvent.interactionType`. */\nexport type PrototypeTriggerType = 'ON_CLICK' | 'AFTER_TIMEOUT'\n\n/** What a reaction does, as `.fig` keeps `ConnectionType` on `PrototypeAction`. */\nexport type PrototypeActionType = 'NODE' | 'BACK' | 'CLOSE'\n\n/** Whether an action moves to a frame or opens it over the screen, as `NavigationType`. */\nexport type PrototypeNavigationType = 'NAVIGATE' | 'OVERLAY'\n\n/** How a reaction animates between frames, as `TransitionType` keeps them. */\nexport type PrototypeTransitionType = 'INSTANT' | 'DISSOLVE'\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, and how long it takes in seconds. */\nexport interface PrototypeTransition {\n type: PrototypeTransitionType\n duration: number\n}\n\n/** A reaction's move to another frame, or the overlay it opens. */\nexport interface PrototypeNodeAction {\n type: 'NODE'\n /** The frame the action shows; `null` keeps the connection when its target is gone. */\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 does. */\nexport interface PrototypeTrigger {\n type: PrototypeTriggerType\n /** AFTER_TIMEOUT only: 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\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":";;AAyYA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA0oBA,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"}
|
package/dist/undo.d.ts
CHANGED
|
@@ -80,6 +80,12 @@ declare class UndoManager {
|
|
|
80
80
|
* `adoptHistory` puts it back when that graph opens again.
|
|
81
81
|
*/
|
|
82
82
|
takeHistory(): UndoHistory;
|
|
83
|
+
/**
|
|
84
|
+
* Adds a step to a history kept aside while another graph is open, and returns it. The step's
|
|
85
|
+
* marks stay in its own graph, which is not the open one, and nothing is announced: the open
|
|
86
|
+
* document's history does not change.
|
|
87
|
+
*/
|
|
88
|
+
pushIntoParked(history: UndoHistory, entry: UndoEntry): UndoHistory;
|
|
83
89
|
/** Makes `history`, recorded on the graph now open, the committed one. */
|
|
84
90
|
adoptHistory(history: UndoHistory | undefined): void;
|
|
85
91
|
/** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */
|
package/dist/undo.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"undo.d.ts","names":[],"sources":["../src/undo.ts"],"mappings":";UAAiB;EACf;EACA;EACA;EACA;;;;;;UAOe;WACN,eAAe;WACf,eAAe;;UAGT;EACf;;EAEA;;;;;EAKA,QAAQ;;;UAIO;;EA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AIA;cAIQ;UAIJ;UASA;UAeA"}
|
package/dist/undo.js
CHANGED
|
@@ -155,6 +155,19 @@ var UndoManager = class {
|
|
|
155
155
|
this.discardBatches();
|
|
156
156
|
return history;
|
|
157
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Adds a step to a history kept aside while another graph is open, and returns it. The step's
|
|
160
|
+
* marks stay in its own graph, which is not the open one, and nothing is announced: the open
|
|
161
|
+
* document's history does not change.
|
|
162
|
+
*/
|
|
163
|
+
pushIntoParked(history, entry) {
|
|
164
|
+
const undo = [...history.undo, entry];
|
|
165
|
+
const overflow = Number.isFinite(this.limit) && this.limit > 0 ? undo.length - this.limit : 0;
|
|
166
|
+
return {
|
|
167
|
+
undo: overflow > 0 ? undo.slice(overflow) : undo,
|
|
168
|
+
redo: []
|
|
169
|
+
};
|
|
170
|
+
}
|
|
158
171
|
/** Makes `history`, recorded on the graph now open, the committed one. */
|
|
159
172
|
adoptHistory(history) {
|
|
160
173
|
this.undoStack = history ? [...history.undo] : [];
|
package/dist/undo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"undo.js","names":[],"sources":["../src/undo.ts"],"sourcesContent":["export interface UndoEntry {\n label: string\n forward: () => void\n inverse: () => void\n coalesceKey?: string\n}\n\n/**\n * Committed history, kept aside while another graph is open so a document opened in the same\n * editor never inherits the last one's steps.\n */\nexport interface UndoHistory {\n readonly undo: readonly UndoEntry[]\n readonly redo: readonly UndoEntry[]\n}\n\nexport interface UndoManagerOptions {\n limit?: number\n /** Called after recording, undoing, redoing, or clearing committed history. */\n onChange?: () => void\n /**\n * The edited-field marks an edit adds. A step takes its marks back when undone and puts them\n * back when redone, so a layer ends a step exactly as it began one, marks included.\n */\n marks?: UndoSourceMarks\n}\n\n/** Marks an edit left on layers, kept by the graph for one undo step. */\nexport interface UndoSourceMarks {\n /** The marks added since the last step, which that step owns. */\n take: () => Array<[nodeId: string, field: string]>\n add: (nodeId: string, fields: readonly string[]) => void\n remove: (nodeId: string, fields: readonly string[]) => void\n /** Runs a replay that writes values only, so it marks no field of its own. */\n preserve: (run: () => void) => void\n}\n\ninterface UndoBatch {\n label: string\n entries: UndoEntry[]\n coalesceKey?: string\n}\n\n/** How many edits undo keeps by default. */\nexport const DEFAULT_HISTORY_LIMIT = 200\n\nexport class UndoManager {\n private undoStack: UndoEntry[] = []\n private redoStack: UndoEntry[] = []\n private batches: UndoBatch[] = []\n private replaying = 0\n private openEdits = 0\n private readonly settlers = new Set<() => void>()\n private readonly limit: number\n private readonly onChange: (() => void) | undefined\n private readonly marks: UndoSourceMarks | undefined\n\n constructor(options: UndoManagerOptions = {}) {\n this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT\n this.onChange = options.onChange\n this.marks = options.marks\n }\n\n apply(entry: UndoEntry): void {\n this.execute(entry)\n }\n\n execute(entry: UndoEntry): void {\n entry.forward()\n this.record(entry)\n }\n\n push(entry: UndoEntry): void {\n this.record(entry)\n }\n\n record(entry: UndoEntry): void {\n const marked = this.withSourceMarks(entry)\n const batch = this.currentBatch\n if (batch) {\n batch.entries.push(marked)\n return\n }\n this.pushUndoEntry(marked)\n }\n\n /**\n * The step's replay writes values without marking them, then the marks the edit added come\n * back on redo and go with it on undo.\n */\n private withSourceMarks(entry: UndoEntry): UndoEntry {\n const marks = this.marks\n if (!marks) return entry\n const taken = marks.take()\n const byNode = new Map<string, string[]>()\n for (const [id, field] of taken) {\n const fields = byNode.get(id)\n if (fields) fields.push(field)\n else byNode.set(id, [field])\n }\n return {\n ...entry,\n forward: () => {\n // Redo repeats the edit, marks its layout adds included, then keeps the marks the step\n // owned even if the replay wrote fewer fields than the edit did.\n entry.forward()\n for (const [id, fields] of byNode) marks.add(id, fields)\n },\n inverse: () => {\n // Undo puts a state back rather than editing, so it marks nothing of its own.\n marks.preserve(() => entry.inverse())\n for (const [id, fields] of byNode) marks.remove(id, fields)\n }\n }\n }\n\n /**\n * Records an entry as a step of its own, outside the batches being built, such as an agent's\n * edit made while a colour picker is open. Batches settle first, so the step follows the\n * changes they hold so far.\n */\n pushStep(entry: UndoEntry): void {\n this.settle()\n this.pushUndoEntry(entry)\n }\n\n /**\n * Registers a hook that commits an edit still being coalesced, such as a run of picker changes.\n * Undo and redo run every hook first, so they act on the newest change.\n */\n onBeforeHistory(settle: () => void): () => void {\n this.settlers.add(settle)\n return () => this.settlers.delete(settle)\n }\n\n private settle() {\n for (const settle of this.settlers) settle()\n }\n\n undo(): string | null {\n this.settle()\n const entry = this.undoStack.pop()\n if (!entry) return null\n this.replay(() => entry.inverse())\n this.redoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n redo(): string | null {\n this.settle()\n const entry = this.redoStack.pop()\n if (!entry) return null\n this.replay(() => entry.forward())\n this.undoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n beginBatch(label: string, coalesceKey?: string): void {\n this.batches.push({ label, entries: [], coalesceKey })\n }\n\n commitBatch(): void {\n const batch = this.batches.pop()\n if (!batch || batch.entries.length === 0) return\n\n const entry = this.createBatchEntry(batch)\n const parentBatch = this.currentBatch\n if (parentBatch) parentBatch.entries.push(entry)\n else this.pushUndoEntry(entry)\n }\n\n runBatch<T>(label: string, fn: () => T, coalesceKey?: string): T {\n this.beginBatch(label, coalesceKey)\n try {\n const result = fn()\n this.commitBatch()\n return result\n } catch (error) {\n this.rollbackBatch()\n throw error\n }\n }\n\n rollbackBatch(): void {\n const batch = this.batches.pop()\n if (!batch) return\n for (const entry of batch.entries.toReversed()) entry.inverse()\n }\n\n /** Abandon provisional history without replaying it or changing committed undo/redo entries. */\n discardBatches(): void {\n this.batches = []\n }\n\n clear(): void {\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n this.marks?.take()\n this.onChange?.()\n }\n\n /**\n * Takes the committed history out, for the graph it was recorded on, and leaves this one empty;\n * `adoptHistory` puts it back when that graph opens again.\n */\n takeHistory(): UndoHistory {\n const history = { undo: this.undoStack, redo: this.redoStack }\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n return history\n }\n\n /** Makes `history`, recorded on the graph now open, the committed one. */\n adoptHistory(history: UndoHistory | undefined): void {\n this.undoStack = history ? [...history.undo] : []\n this.redoStack = history ? [...history.redo] : []\n this.discardBatches()\n }\n\n /** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */\n get isReplaying(): boolean {\n return this.replaying > 0\n }\n\n /**\n * Adds a change that the newest step caused, as one an editor makes in response to it, so undo\n * and redo apply them together. Inside a batch it joins the batch. False with no step to join,\n * including after an undo, when the newest step is on the redo stack and not applied.\n */\n extendLastStep(entry: UndoEntry): boolean {\n if (this.currentBatch) {\n this.currentBatch.entries.push(entry)\n return true\n }\n const last = this.undoStack.at(-1)\n if (!last || this.redoStack.length > 0) return false\n // The step keeps its identity, so callers that hold it still find it in the history.\n const { forward, inverse } = last\n last.forward = () => {\n forward()\n entry.forward()\n }\n last.inverse = () => {\n entry.inverse()\n inverse()\n }\n return true\n }\n\n private replay(step: () => void) {\n this.replaying++\n try {\n step()\n } finally {\n this.replaying--\n }\n }\n\n get isBatching(): boolean {\n return this.batches.length > 0\n }\n\n /**\n * Marks an edit whose step is recorded when it ends, such as an agent's call that awaits fonts\n * or a layout before it finishes. Returns the function that ends it; ending it twice is a no-op.\n */\n openEdit(): () => void {\n this.openEdits++\n let open = true\n return () => {\n if (!open) return\n open = false\n this.openEdits--\n }\n }\n\n /**\n * Whether a batch or an edit opened with `openEdit` will record a step for the changes made now,\n * so they are not edits outside the history.\n */\n get isRecording(): boolean {\n return this.isBatching || this.openEdits > 0\n }\n\n /** Committed history, or changes in an open batch that a settling hook commits first. */\n get canUndo(): boolean {\n if (this.undoStack.length > 0) return true\n return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0)\n }\n\n get canRedo(): boolean {\n return this.redoStack.length > 0\n }\n\n /**\n * The entry `depth` steps below the top of the undo stack, so a caller that pushed entries\n * can tell whether they are still the most recent ones.\n */\n peekUndo(depth = 0): UndoEntry | undefined {\n return this.undoStack.at(-1 - depth)\n }\n\n /** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */\n peekRedo(depth = 0): UndoEntry | undefined {\n return this.redoStack.at(-1 - depth)\n }\n\n /**\n * Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it\n * left the history, trimmed or dropped when an edit cleared Redo.\n */\n stateOf(entry: UndoEntry): 'applied' | 'undone' | null {\n if (this.undoStack.includes(entry)) return 'applied'\n if (this.redoStack.includes(entry)) return 'undone'\n return null\n }\n\n get undoLabel(): string | null {\n return this.undoStack.at(-1)?.label ?? null\n }\n\n get redoLabel(): string | null {\n return this.redoStack.at(-1)?.label ?? null\n }\n\n private get currentBatch(): UndoBatch | null {\n return this.batches.at(-1) ?? null\n }\n\n private createBatchEntry(batch: UndoBatch): UndoEntry {\n return {\n label: batch.label,\n forward: () => batch.entries.forEach((entry) => entry.forward()),\n inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),\n coalesceKey: batch.coalesceKey\n }\n }\n\n private pushUndoEntry(entry: UndoEntry): void {\n const previous = this.undoStack.at(-1)\n if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) {\n this.undoStack[this.undoStack.length - 1] = {\n ...entry,\n inverse: previous.inverse\n }\n } else {\n this.undoStack.push(entry)\n }\n this.redoStack = []\n this.trimUndoStack()\n this.onChange?.()\n }\n\n private trimUndoStack(): void {\n if (!Number.isFinite(this.limit) || this.limit <= 0) return\n const overflow = this.undoStack.length - this.limit\n if (overflow > 0) this.undoStack.splice(0, overflow)\n }\n}\n"],"mappings":";;AA4CA,MAAa,wBAAwB;AAErC,IAAa,cAAb,MAAyB;CACvB,YAAiC,CAAC;CAClC,YAAiC,CAAC;CAClC,UAA+B,CAAC;CAChC,YAAoB;CACpB,YAAoB;CACpB,2BAA4B,IAAI,IAAgB;CAChD;CACA;CACA;CAEA,YAAY,UAA8B,CAAC,GAAG;EAC5C,KAAK,QAAQ,QAAQ,SAAA;EACrB,KAAK,WAAW,QAAQ;EACxB,KAAK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1
|
+
{"version":3,"file":"undo.js","names":[],"sources":["../src/undo.ts"],"sourcesContent":["export interface UndoEntry {\n label: string\n forward: () => void\n inverse: () => void\n coalesceKey?: string\n}\n\n/**\n * Committed history, kept aside while another graph is open so a document opened in the same\n * editor never inherits the last one's steps.\n */\nexport interface UndoHistory {\n readonly undo: readonly UndoEntry[]\n readonly redo: readonly UndoEntry[]\n}\n\nexport interface UndoManagerOptions {\n limit?: number\n /** Called after recording, undoing, redoing, or clearing committed history. */\n onChange?: () => void\n /**\n * The edited-field marks an edit adds. A step takes its marks back when undone and puts them\n * back when redone, so a layer ends a step exactly as it began one, marks included.\n */\n marks?: UndoSourceMarks\n}\n\n/** Marks an edit left on layers, kept by the graph for one undo step. */\nexport interface UndoSourceMarks {\n /** The marks added since the last step, which that step owns. */\n take: () => Array<[nodeId: string, field: string]>\n add: (nodeId: string, fields: readonly string[]) => void\n remove: (nodeId: string, fields: readonly string[]) => void\n /** Runs a replay that writes values only, so it marks no field of its own. */\n preserve: (run: () => void) => void\n}\n\ninterface UndoBatch {\n label: string\n entries: UndoEntry[]\n coalesceKey?: string\n}\n\n/** How many edits undo keeps by default. */\nexport const DEFAULT_HISTORY_LIMIT = 200\n\nexport class UndoManager {\n private undoStack: UndoEntry[] = []\n private redoStack: UndoEntry[] = []\n private batches: UndoBatch[] = []\n private replaying = 0\n private openEdits = 0\n private readonly settlers = new Set<() => void>()\n private readonly limit: number\n private readonly onChange: (() => void) | undefined\n private readonly marks: UndoSourceMarks | undefined\n\n constructor(options: UndoManagerOptions = {}) {\n this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT\n this.onChange = options.onChange\n this.marks = options.marks\n }\n\n apply(entry: UndoEntry): void {\n this.execute(entry)\n }\n\n execute(entry: UndoEntry): void {\n entry.forward()\n this.record(entry)\n }\n\n push(entry: UndoEntry): void {\n this.record(entry)\n }\n\n record(entry: UndoEntry): void {\n const marked = this.withSourceMarks(entry)\n const batch = this.currentBatch\n if (batch) {\n batch.entries.push(marked)\n return\n }\n this.pushUndoEntry(marked)\n }\n\n /**\n * The step's replay writes values without marking them, then the marks the edit added come\n * back on redo and go with it on undo.\n */\n private withSourceMarks(entry: UndoEntry): UndoEntry {\n const marks = this.marks\n if (!marks) return entry\n const taken = marks.take()\n const byNode = new Map<string, string[]>()\n for (const [id, field] of taken) {\n const fields = byNode.get(id)\n if (fields) fields.push(field)\n else byNode.set(id, [field])\n }\n return {\n ...entry,\n forward: () => {\n // Redo repeats the edit, marks its layout adds included, then keeps the marks the step\n // owned even if the replay wrote fewer fields than the edit did.\n entry.forward()\n for (const [id, fields] of byNode) marks.add(id, fields)\n },\n inverse: () => {\n // Undo puts a state back rather than editing, so it marks nothing of its own.\n marks.preserve(() => entry.inverse())\n for (const [id, fields] of byNode) marks.remove(id, fields)\n }\n }\n }\n\n /**\n * Records an entry as a step of its own, outside the batches being built, such as an agent's\n * edit made while a colour picker is open. Batches settle first, so the step follows the\n * changes they hold so far.\n */\n pushStep(entry: UndoEntry): void {\n this.settle()\n this.pushUndoEntry(entry)\n }\n\n /**\n * Registers a hook that commits an edit still being coalesced, such as a run of picker changes.\n * Undo and redo run every hook first, so they act on the newest change.\n */\n onBeforeHistory(settle: () => void): () => void {\n this.settlers.add(settle)\n return () => this.settlers.delete(settle)\n }\n\n private settle() {\n for (const settle of this.settlers) settle()\n }\n\n undo(): string | null {\n this.settle()\n const entry = this.undoStack.pop()\n if (!entry) return null\n this.replay(() => entry.inverse())\n this.redoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n redo(): string | null {\n this.settle()\n const entry = this.redoStack.pop()\n if (!entry) return null\n this.replay(() => entry.forward())\n this.undoStack.push(entry)\n this.onChange?.()\n return entry.label\n }\n\n beginBatch(label: string, coalesceKey?: string): void {\n this.batches.push({ label, entries: [], coalesceKey })\n }\n\n commitBatch(): void {\n const batch = this.batches.pop()\n if (!batch || batch.entries.length === 0) return\n\n const entry = this.createBatchEntry(batch)\n const parentBatch = this.currentBatch\n if (parentBatch) parentBatch.entries.push(entry)\n else this.pushUndoEntry(entry)\n }\n\n runBatch<T>(label: string, fn: () => T, coalesceKey?: string): T {\n this.beginBatch(label, coalesceKey)\n try {\n const result = fn()\n this.commitBatch()\n return result\n } catch (error) {\n this.rollbackBatch()\n throw error\n }\n }\n\n rollbackBatch(): void {\n const batch = this.batches.pop()\n if (!batch) return\n for (const entry of batch.entries.toReversed()) entry.inverse()\n }\n\n /** Abandon provisional history without replaying it or changing committed undo/redo entries. */\n discardBatches(): void {\n this.batches = []\n }\n\n clear(): void {\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n this.marks?.take()\n this.onChange?.()\n }\n\n /**\n * Takes the committed history out, for the graph it was recorded on, and leaves this one empty;\n * `adoptHistory` puts it back when that graph opens again.\n */\n takeHistory(): UndoHistory {\n const history = { undo: this.undoStack, redo: this.redoStack }\n this.undoStack = []\n this.redoStack = []\n this.discardBatches()\n return history\n }\n\n /**\n * Adds a step to a history kept aside while another graph is open, and returns it. The step's\n * marks stay in its own graph, which is not the open one, and nothing is announced: the open\n * document's history does not change.\n */\n pushIntoParked(history: UndoHistory, entry: UndoEntry): UndoHistory {\n const undo = [...history.undo, entry]\n const overflow = Number.isFinite(this.limit) && this.limit > 0 ? undo.length - this.limit : 0\n return { undo: overflow > 0 ? undo.slice(overflow) : undo, redo: [] }\n }\n\n /** Makes `history`, recorded on the graph now open, the committed one. */\n adoptHistory(history: UndoHistory | undefined): void {\n this.undoStack = history ? [...history.undo] : []\n this.redoStack = history ? [...history.redo] : []\n this.discardBatches()\n }\n\n /** Whether undo or redo is replaying a step, whose changes are history rather than new edits. */\n get isReplaying(): boolean {\n return this.replaying > 0\n }\n\n /**\n * Adds a change that the newest step caused, as one an editor makes in response to it, so undo\n * and redo apply them together. Inside a batch it joins the batch. False with no step to join,\n * including after an undo, when the newest step is on the redo stack and not applied.\n */\n extendLastStep(entry: UndoEntry): boolean {\n if (this.currentBatch) {\n this.currentBatch.entries.push(entry)\n return true\n }\n const last = this.undoStack.at(-1)\n if (!last || this.redoStack.length > 0) return false\n // The step keeps its identity, so callers that hold it still find it in the history.\n const { forward, inverse } = last\n last.forward = () => {\n forward()\n entry.forward()\n }\n last.inverse = () => {\n entry.inverse()\n inverse()\n }\n return true\n }\n\n private replay(step: () => void) {\n this.replaying++\n try {\n step()\n } finally {\n this.replaying--\n }\n }\n\n get isBatching(): boolean {\n return this.batches.length > 0\n }\n\n /**\n * Marks an edit whose step is recorded when it ends, such as an agent's call that awaits fonts\n * or a layout before it finishes. Returns the function that ends it; ending it twice is a no-op.\n */\n openEdit(): () => void {\n this.openEdits++\n let open = true\n return () => {\n if (!open) return\n open = false\n this.openEdits--\n }\n }\n\n /**\n * Whether a batch or an edit opened with `openEdit` will record a step for the changes made now,\n * so they are not edits outside the history.\n */\n get isRecording(): boolean {\n return this.isBatching || this.openEdits > 0\n }\n\n /** Committed history, or changes in an open batch that a settling hook commits first. */\n get canUndo(): boolean {\n if (this.undoStack.length > 0) return true\n return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0)\n }\n\n get canRedo(): boolean {\n return this.redoStack.length > 0\n }\n\n /**\n * The entry `depth` steps below the top of the undo stack, so a caller that pushed entries\n * can tell whether they are still the most recent ones.\n */\n peekUndo(depth = 0): UndoEntry | undefined {\n return this.undoStack.at(-1 - depth)\n }\n\n /** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */\n peekRedo(depth = 0): UndoEntry | undefined {\n return this.redoStack.at(-1 - depth)\n }\n\n /**\n * Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it\n * left the history, trimmed or dropped when an edit cleared Redo.\n */\n stateOf(entry: UndoEntry): 'applied' | 'undone' | null {\n if (this.undoStack.includes(entry)) return 'applied'\n if (this.redoStack.includes(entry)) return 'undone'\n return null\n }\n\n get undoLabel(): string | null {\n return this.undoStack.at(-1)?.label ?? null\n }\n\n get redoLabel(): string | null {\n return this.redoStack.at(-1)?.label ?? null\n }\n\n private get currentBatch(): UndoBatch | null {\n return this.batches.at(-1) ?? null\n }\n\n private createBatchEntry(batch: UndoBatch): UndoEntry {\n return {\n label: batch.label,\n forward: () => batch.entries.forEach((entry) => entry.forward()),\n inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),\n coalesceKey: batch.coalesceKey\n }\n }\n\n private pushUndoEntry(entry: UndoEntry): void {\n const previous = this.undoStack.at(-1)\n if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) {\n this.undoStack[this.undoStack.length - 1] = {\n ...entry,\n inverse: previous.inverse\n }\n } else {\n this.undoStack.push(entry)\n }\n this.redoStack = []\n this.trimUndoStack()\n this.onChange?.()\n }\n\n private trimUndoStack(): void {\n if (!Number.isFinite(this.limit) || this.limit <= 0) return\n const overflow = this.undoStack.length - this.limit\n if (overflow > 0) this.undoStack.splice(0, overflow)\n }\n}\n"],"mappings":";;AA4CA,MAAa,wBAAwB;AAErC,IAAa,cAAb,MAAyB;CACvB,YAAiC,CAAC;CAClC,YAAiC,CAAC;CAClC,UAA+B,CAAC;CAChC,YAAoB;CACpB,YAAoB;CACpB,2BAA4B,IAAI,IAAgB;CAChD;CACA;CACA;CAEA,YAAY,UAA8B,CAAC,GAAG;EAC5C,KAAK,QAAQ,QAAQ,SAAA;EACrB,KAAK,WAAW,QAAQ;EACxB,KAAK,QAAQ,QAAQ;CACvB;CAEA,MAAM,OAAwB;EAC5B,KAAK,QAAQ,KAAK;CACpB;CAEA,QAAQ,OAAwB;EAC9B,MAAM,QAAQ;EACd,KAAK,OAAO,KAAK;CACnB;CAEA,KAAK,OAAwB;EAC3B,KAAK,OAAO,KAAK;CACnB;CAEA,OAAO,OAAwB;EAC7B,MAAM,SAAS,KAAK,gBAAgB,KAAK;EACzC,MAAM,QAAQ,KAAK;EACnB,IAAI,OAAO;GACT,MAAM,QAAQ,KAAK,MAAM;GACzB;EACF;EACA,KAAK,cAAc,MAAM;CAC3B;;;;;CAMA,gBAAwB,OAA6B;EACnD,MAAM,QAAQ,KAAK;EAC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,OAAO,YAAY;iBA8BlC,cAAc,OAAO,YAAY,YAAY;iBAe7C,eACd,OAAO,YACP,0BACA,cACA,MAAM,cACN,sBACA,QAAQ,gBACP;iBAsBa,iBACd,OAAO,YACP,0BACA,eACC;iBAca,iBAAiB,OAAO,YAAY;iBAmBpC,cAAc,OAAO,YAAY,sBAAsB;iBAIvD,QACd,OAAO,YACP,sBACA,gBACA,cACA;;iBAgBc,WACd,OAAO,YACP,0BACA,sBACA,cACA;iBAQc,WAAW,OAAO,YAAY,sBAAsB;iBA8BpD,WACd,OAAO,YACP,sBACA,gBACA;iBAQc,eAAe,OAAO,YAAY,sBAAsB;;iBAuBxD,kBAAkB,YAAY,qBAAqB;;;;;iBAYnD,mBAAmB,YAAY,qBAAqB;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;iBAwDgB,YAAY,OAAO,YAAY,UAAU;iBAQzC,eAAe,OAAO,YAAY;iBA8BlC,cAAc,OAAO,YAAY,YAAY;iBAe7C,eACd,OAAO,YACP,0BACA,cACA,MAAM,cACN,sBACA,QAAQ,gBACP;iBAsBa,iBACd,OAAO,YACP,0BACA,eACC;iBAca,iBAAiB,OAAO,YAAY;iBAmBpC,cAAc,OAAO,YAAY,sBAAsB;iBAIvD,QACd,OAAO,YACP,sBACA,gBACA,cACA;;iBAgBc,WACd,OAAO,YACP,0BACA,sBACA,cACA;iBAQc,WAAW,OAAO,YAAY,sBAAsB;iBA8BpD,WACd,OAAO,YACP,sBACA,gBACA;iBAQc,eAAe,OAAO,YAAY,sBAAsB;;iBAuBxD,kBAAkB,YAAY,qBAAqB;;;;;iBAYnD,mBAAmB,YAAY,qBAAqB;iBAIpD,0BAA0B,OAAO,YAAY,uBAAuB;iBAQpE,mBAAmB,OAAO,YAAY,MAAM,eAAe;iBAgE3D,aACd,OAAO,YACP,gBACA,eACA;iBA8Ec,eAAe,OAAO,YAAY,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { compact, partition, sortBy, uniq } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport {\n bindingOverrideField,\n setInstanceOverride,\n variableModeOverrideField\n} from '../instances/overrides'\nimport { siblingOrderKeys } from '../order-keys'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n SceneNode,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n NUMERIC_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\nimport { applyBoundPaintColor } from './paints'\nimport { pinnedRunBindingScales } from './units'\n\nexport * from './resolution'\n\n/**\n * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's\n * scale for those fields changes or goes, and the change to announce.\n */\nfunction pinRunBindingScales(\n node: SceneNode,\n fields: readonly string[]\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = pinnedRunBindingScales(node, fields)\n if (!styleRuns) return {}\n node.styleRuns = styleRuns\n return { styleRuns }\n}\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n const pruned = Object.keys(node.variableBindingScales).filter(\n (field) => !(field in node.boundVariables)\n )\n const runs = pinRunBindingScales(node, pruned)\n node.variableBindingScales = omit(node.variableBindingScales, pruned)\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n // A layer that chose one of its modes has nothing left to choose from.\n for (const node of graph.nodes.values()) {\n if (!(id in node.variableModes)) continue\n const variableModes = omit(node.variableModes, [id])\n graph.willChangeNode(node)\n node.variableModes = variableModes\n graph.emitter.emit('node:updated', node.id, { variableModes })\n }\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n // The next default is the next listed mode, as Figma picks it, not the next saved entry.\n collection.defaultModeId = modesInListedOrder(collection)[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n // A layer that chose the mode goes back to the collection's default, and an instance keeps no\n // override naming a mode that is gone, which would otherwise come back on a later sync.\n const overrideField = variableModeOverrideField(collectionId)\n for (const node of graph.nodes.values()) {\n if (node.variableModes[collectionId] !== modeId) continue\n const variableModes = omit(node.variableModes, [collectionId])\n graph.willChangeNode(node)\n node.variableModes = variableModes\n node.instanceOverrides.self.delete(overrideField)\n for (const overrides of node.instanceOverrides.descendants.values())\n overrides.delete(overrideField)\n graph.emitter.emit('node:updated', node.id, { variableModes })\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n if (collection.modes.every((mode) => !mode.sortPosition)) {\n // No sort positions carry an order of their own: the array is the order, so the new\n // default moves first in it, as a collection created here has always done.\n collection.modes = modesDefaultFirst(collection)\n return\n }\n // The saved array order stays the file's own; the new default sorts first by its sort\n // position, so the listed order shows it first and a re-import reads it as the default.\n const listed = modesDefaultFirst(collection)\n const positions = siblingOrderKeys(listed.map((mode) => mode.sortPosition))\n const byId = new Map(listed.map((mode, index) => [mode.modeId, positions[index]]))\n collection.modes = collection.modes.map((mode) => ({\n ...mode,\n sortPosition: byId.get(mode.modeId) ?? mode.sortPosition\n }))\n}\n\n/** Figma has no default-mode field: the first listed mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(\n modesInListedOrder(collection),\n (m) => m.modeId === collection.defaultModeId\n )\n return [...defaults, ...rest]\n}\n\n/**\n * The modes as Figma lists them: by `sortPosition`, modes without one following in saved order.\n * The collection's own array keeps the file's saved order, which an export writes back as it was.\n */\nexport function modesInListedOrder(collection: VariableCollection): VariableCollectionMode[] {\n return sortBy(collection.modes, [\n (mode) => !mode.sortPosition,\n (mode) => mode.sortPosition ?? ''\n ])\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\nconst PAINT_BINDING_LISTS = ['fills', 'strokes'] as const satisfies readonly PaintBindingList[]\n\n/**\n * Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for\n * an unknown one names what the caller can send instead of leaving them to guess.\n */\nconst ACCEPTED_BINDING_FIELDS: readonly string[] = [\n ...NUMERIC_FIELDS,\n ...STRING_BINDING_FIELDS,\n ...BOOLEAN_BINDING_FIELDS,\n ...ICON_BINDING_FIELDS,\n ...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])\n]\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(\n `Unknown binding field \"${field}\". Accepted: ${ACCEPTED_BINDING_FIELDS.join(', ')}`\n )\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n const runs = pinRunBindingScales(node, [field])\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n // A paint takes its variable's color, alpha as opacity, when it binds, as Figma's does.\n if (paint) applyBoundPaintColor(graph, node, field)\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n const runs = pinRunBindingScales(node, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n const instances = uniq(compact([nearest, owner])).filter((x) => x.id !== nodeId)\n for (const instance of instances) graph.willChangeNode(instance)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n // Each instance claims the binding it changed alone, so the layer's other bindings keep\n // following their components, as Figma claims only the paint or effect a script edits.\n if (field)\n for (const instance of instances)\n setInstanceOverride(\n instance.instanceOverrides,\n instance.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n for (const instance of instances)\n graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './paints'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './units'\nexport * from './value'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAS,oBACP,MACA,QACuC;CACvC,MAAM,YAAY,uBAAuB,MAAM,MAAM;CACrD,IAAI,CAAC,WAAW,OAAO,CAAC;CACxB,KAAK,YAAY;CACjB,OAAO,EAAE,UAAU;AACrB;AAEA,SAAgB,YAAY,OAAmB,UAA0B;CACvE,MAAM,UAAU,IAAI,SAAS,IAAI,QAAQ;CACzC,MAAM,aAAa,MAAM,oBAAoB,IAAI,SAAS,YAAY;CACtE,IAAI,cAAc,CAAC,WAAW,YAAY,SAAS,SAAS,EAAE,GAC5D,WAAW,YAAY,KAAK,SAAS,EAAE;AAE3C;AAEA,SAAgB,eAAe,OAAmB,IAAkB;CAClE,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;CACvC,IAAI,CAAC,UAAU;CACf,MAAM,UAAU,OAAO,EAAE;CACzB,MAAM,aAAa,MAAM,oBAAoB,IAAI,SAAS,YAAY;CACtE,IAAI,YACF,WAAW,cAAc,WAAW,YAAY,QAAQ,QAAQ,QAAQ,EAAE;CAE5E,KAAK,MA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CACP,OACA,QACA,OACM;CACN,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,MAAM,YAAY,KAAK,QAAQ,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,MAAM,EAAE,OAAO,MAAM;CAC/E,KAAK,MAAM,YAAY,WAAW,MAAM,eAAe,QAAQ;CAC/D,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAG/E,IAAI,OACF,KAAK,MAAM,YAAY,WACrB,oBACE,SAAS,mBACT,SAAS,IACT,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;CACJ,KAAK,MAAM,YAAY,WACrB,MAAM,WAAW,SAAS,IAAI,EAAE,mBAAmB,SAAS,kBAAkB,CAAC;AACnF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { compact, partition, sortBy, uniq } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport {\n bindingOverrideField,\n setInstanceOverride,\n variableModeOverrideField\n} from '../instances/overrides'\nimport { siblingOrderKeys } from '../order-keys'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n SceneNode,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n NUMERIC_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\nimport { applyBoundPaintColor } from './paints'\nimport { pinnedRunBindingScales } from './units'\n\nexport * from './resolution'\n\n/**\n * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's\n * scale for those fields changes or goes, and the change to announce.\n */\nfunction pinRunBindingScales(\n node: SceneNode,\n fields: readonly string[]\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = pinnedRunBindingScales(node, fields)\n if (!styleRuns) return {}\n node.styleRuns = styleRuns\n return { styleRuns }\n}\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n const pruned = Object.keys(node.variableBindingScales).filter(\n (field) => !(field in node.boundVariables)\n )\n const runs = pinRunBindingScales(node, pruned)\n node.variableBindingScales = omit(node.variableBindingScales, pruned)\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n // A layer that chose one of its modes has nothing left to choose from.\n for (const node of graph.nodes.values()) {\n if (!(id in node.variableModes)) continue\n const variableModes = omit(node.variableModes, [id])\n graph.willChangeNode(node)\n node.variableModes = variableModes\n graph.emitter.emit('node:updated', node.id, { variableModes })\n }\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n // The next default is the next listed mode, as Figma picks it, not the next saved entry.\n collection.defaultModeId = modesInListedOrder(collection)[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n // A layer that chose the mode goes back to the collection's default, and an instance keeps no\n // override naming a mode that is gone, which would otherwise come back on a later sync.\n const overrideField = variableModeOverrideField(collectionId)\n for (const node of graph.nodes.values()) {\n if (node.variableModes[collectionId] !== modeId) continue\n const variableModes = omit(node.variableModes, [collectionId])\n graph.willChangeNode(node)\n node.variableModes = variableModes\n node.instanceOverrides.self.delete(overrideField)\n for (const overrides of node.instanceOverrides.descendants.values())\n overrides.delete(overrideField)\n graph.emitter.emit('node:updated', node.id, { variableModes })\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n if (collection.modes.every((mode) => !mode.sortPosition)) {\n // No sort positions carry an order of their own: the array is the order, so the new\n // default moves first in it, as a collection created here has always done.\n collection.modes = modesDefaultFirst(collection)\n return\n }\n // The saved array order stays the file's own; the new default sorts first by its sort\n // position, so the listed order shows it first and a re-import reads it as the default.\n const listed = modesDefaultFirst(collection)\n const positions = siblingOrderKeys(listed.map((mode) => mode.sortPosition))\n const byId = new Map(listed.map((mode, index) => [mode.modeId, positions[index]]))\n collection.modes = collection.modes.map((mode) => ({\n ...mode,\n sortPosition: byId.get(mode.modeId) ?? mode.sortPosition\n }))\n}\n\n/** Figma has no default-mode field: the first listed mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(\n modesInListedOrder(collection),\n (m) => m.modeId === collection.defaultModeId\n )\n return [...defaults, ...rest]\n}\n\n/**\n * The modes as Figma lists them: by `sortPosition`, modes without one following in saved order.\n * The collection's own array keeps the file's saved order, which an export writes back as it was.\n */\nexport function modesInListedOrder(collection: VariableCollection): VariableCollectionMode[] {\n return sortBy(collection.modes, [(mode) => !mode.sortPosition, (mode) => mode.sortPosition ?? ''])\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\nconst PAINT_BINDING_LISTS = ['fills', 'strokes'] as const satisfies readonly PaintBindingList[]\n\n/**\n * Every field a binding takes, from the same sets `checkBindingFieldType` reads, so a refusal for\n * an unknown one names what the caller can send instead of leaving them to guess.\n */\nconst ACCEPTED_BINDING_FIELDS: readonly string[] = [\n ...NUMERIC_FIELDS,\n ...STRING_BINDING_FIELDS,\n ...BOOLEAN_BINDING_FIELDS,\n ...ICON_BINDING_FIELDS,\n ...PAINT_BINDING_LISTS.flatMap((list) => [`${list}/<n>/color`, `${list}/<n>/uniforms/<name>`])\n]\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(\n `Unknown binding field \"${field}\". Accepted: ${ACCEPTED_BINDING_FIELDS.join(', ')}`\n )\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n const runs = pinRunBindingScales(node, [field])\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n // A paint takes its variable's color, alpha as opacity, when it binds, as Figma's does.\n if (paint) applyBoundPaintColor(graph, node, field)\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n const runs = pinRunBindingScales(node, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n const instances = uniq(compact([nearest, owner])).filter((x) => x.id !== nodeId)\n for (const instance of instances) graph.willChangeNode(instance)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n // Each instance claims the binding it changed alone, so the layer's other bindings keep\n // following their components, as Figma claims only the paint or effect a script edits.\n if (field)\n for (const instance of instances)\n setInstanceOverride(\n instance.instanceOverrides,\n instance.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n for (const instance of instances)\n graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './paints'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './units'\nexport * from './value'\n"],"mappings":";;;;;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AqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;CACJ,KAAK,MAAM,YAAY,WACrB,MAAM,WAAW,SAAS,IAAI,EAAE,mBAAmB,SAAS,kBAAkB,CAAC;AACnF"}
|
package/package.json
CHANGED
package/src/behaviours/spec.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import { omitBy } from 'es-toolkit/object'
|
|
2
2
|
|
|
3
3
|
import type { SceneGraph } from '../graph'
|
|
4
|
+
import { slotPropertyId } from '../slots/frames'
|
|
4
5
|
import type { ComponentPropertyDefinition, SceneNode } from '../types'
|
|
5
6
|
import { behaviourContract } from './kinds'
|
|
6
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
behaviourProperties,
|
|
9
|
+
booleanBinding,
|
|
10
|
+
emptyBehaviour,
|
|
11
|
+
guessInteractionStates,
|
|
12
|
+
textBinding
|
|
13
|
+
} from './model'
|
|
7
14
|
import { isNumberRange, type Behaviour, type BehaviourSpec } from './schema'
|
|
8
15
|
|
|
9
16
|
/** Variant values that usually mean on, compared case-insensitively. */
|
|
@@ -58,13 +65,18 @@ function resolveValue(
|
|
|
58
65
|
binding: ValueBinding
|
|
59
66
|
): void {
|
|
60
67
|
const contract = behaviourContract(behaviour.kind)
|
|
61
|
-
const
|
|
62
|
-
const value = bindable.find((item) => item.id === valueId)
|
|
68
|
+
const value = contract.values.find((item) => item.id === valueId)
|
|
63
69
|
if (!value)
|
|
64
70
|
throw new Error(
|
|
65
|
-
`A ${behaviour.kind} has no
|
|
71
|
+
`A ${behaviour.kind} has no value "${valueId}"; it has ${listed(contract.values)}`
|
|
66
72
|
)
|
|
67
73
|
const name = typeof binding === 'string' ? binding : binding.property
|
|
74
|
+
if (value.type === 'choice') {
|
|
75
|
+
// A choice is which child of its slot is active, held by the variant property that draws it.
|
|
76
|
+
const definition = findProperty(properties, name, ['VARIANT'], valueId)
|
|
77
|
+
behaviour.booleans[valueId] = { propertyId: definition.id }
|
|
78
|
+
return
|
|
79
|
+
}
|
|
68
80
|
if (value.type === 'text') {
|
|
69
81
|
behaviour.texts[valueId] = { propertyId: findProperty(properties, name, ['TEXT'], valueId).id }
|
|
70
82
|
return
|
|
@@ -132,9 +144,87 @@ export function behaviourFromSpec(
|
|
|
132
144
|
behaviour.parts[partId] = id
|
|
133
145
|
}
|
|
134
146
|
if (spec.states !== undefined) resolveStates(behaviour, properties, spec.states)
|
|
147
|
+
validateChoiceValues(graph, owner, behaviour)
|
|
135
148
|
return behaviour
|
|
136
149
|
}
|
|
137
150
|
|
|
151
|
+
/** The words a layer reads, joined across its text. */
|
|
152
|
+
function textOf(graph: SceneGraph, node: SceneNode): string {
|
|
153
|
+
if (node.type === 'TEXT') return node.text
|
|
154
|
+
return graph
|
|
155
|
+
.getChildren(node.id)
|
|
156
|
+
.map((child) => textOf(graph, child))
|
|
157
|
+
.join(' ')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The frames in one variant bound to the tabs' list slot, without entering nested instances. */
|
|
161
|
+
function listFrames(graph: SceneGraph, variant: SceneNode, listPropertyId: string): SceneNode[] {
|
|
162
|
+
const frames: SceneNode[] = []
|
|
163
|
+
const visit = (node: SceneNode): void => {
|
|
164
|
+
for (const child of graph.getChildren(node.id)) {
|
|
165
|
+
if (slotPropertyId(child) === listPropertyId) frames.push(child)
|
|
166
|
+
else if (child.type !== 'INSTANCE') visit(child)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
visit(variant)
|
|
170
|
+
return frames
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The trigger labels under the tabs' list slot, in layer order. Each variant must draw one,
|
|
175
|
+
* with the same triggers, so choosing a variant changes no more than the tab drawn.
|
|
176
|
+
*/
|
|
177
|
+
function triggerLabels(graph: SceneGraph, owner: SceneNode, listPropertyId: string): string[] {
|
|
178
|
+
const variants =
|
|
179
|
+
owner.type === 'COMPONENT_SET'
|
|
180
|
+
? graph.getChildren(owner.id).filter((child) => child.type === 'COMPONENT')
|
|
181
|
+
: [owner]
|
|
182
|
+
const frames: SceneNode[] = []
|
|
183
|
+
for (const variant of variants) {
|
|
184
|
+
const found = listFrames(graph, variant, listPropertyId)
|
|
185
|
+
if (!found.length)
|
|
186
|
+
throw new Error(`The variant "${variant.name}" has no frame bound to the tabs' list slot`)
|
|
187
|
+
frames.push(...found)
|
|
188
|
+
}
|
|
189
|
+
const labels = frames[0]
|
|
190
|
+
? graph.getChildren(frames[0].id).map((child) => textOf(graph, child))
|
|
191
|
+
: []
|
|
192
|
+
for (const frame of frames.slice(1)) {
|
|
193
|
+
const others = graph.getChildren(frame.id).map((child) => textOf(graph, child))
|
|
194
|
+
if (others.length !== labels.length || others.some((label, index) => label !== labels[index]))
|
|
195
|
+
throw new Error(
|
|
196
|
+
`The tabs' triggers differ between variants; ${frames[0] ? `the first has ${labels.join(', ')}` : 'they have none'}`
|
|
197
|
+
)
|
|
198
|
+
}
|
|
199
|
+
return labels
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Check the variant options a tabs' choice binds against the words its list draws. A choice
|
|
204
|
+
* picks the trigger of the same value, so the property must offer exactly those values.
|
|
205
|
+
*/
|
|
206
|
+
export function validateChoiceValues(
|
|
207
|
+
graph: SceneGraph,
|
|
208
|
+
owner: SceneNode,
|
|
209
|
+
behaviour: Behaviour
|
|
210
|
+
): void {
|
|
211
|
+
if (behaviour.kind !== 'tabs') return
|
|
212
|
+
const binding = booleanBinding(behaviour, 'value')
|
|
213
|
+
const listPropertyId = behaviour.parts.list
|
|
214
|
+
if (!binding || !listPropertyId) return
|
|
215
|
+
const definition = behaviourProperties(graph, owner).find(
|
|
216
|
+
(item) => item.id === binding.propertyId && item.type === 'VARIANT'
|
|
217
|
+
)
|
|
218
|
+
if (!definition) return
|
|
219
|
+
const labels = triggerLabels(graph, owner, listPropertyId)
|
|
220
|
+
const options = definition.variantOptions ?? []
|
|
221
|
+
if (labels.length === 0) return
|
|
222
|
+
if (labels.length !== options.length || labels.some((label, index) => label !== options[index]))
|
|
223
|
+
throw new Error(
|
|
224
|
+
`"${definition.name}" offers ${options.join(', ')}; the tabs' triggers are ${labels.join(', ')}`
|
|
225
|
+
)
|
|
226
|
+
}
|
|
227
|
+
|
|
138
228
|
function stripUndefined<T extends Record<string, unknown>>(record: T): Partial<T> {
|
|
139
229
|
return omitBy(record, (value) => value === undefined)
|
|
140
230
|
}
|