@open-pencil/scene-graph 0.17.0-beta.5 → 0.17.0-beta.6
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/comments/schema.d.ts.map +1 -1
- package/dist/comments/schema.js +1 -0
- package/dist/comments/schema.js.map +1 -1
- package/dist/comments/threads.d.ts +2 -0
- package/dist/comments/threads.d.ts.map +1 -1
- package/dist/comments/threads.js +11 -5
- package/dist/comments/threads.js.map +1 -1
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +1 -1
- package/dist/components/properties.js.map +1 -1
- package/dist/constants.d.ts +12 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +42 -1
- package/dist/constants.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +2 -0
- package/dist/copy.js.map +1 -1
- package/dist/css/grid.d.ts.map +1 -1
- package/dist/css/grid.js +27 -3
- package/dist/css/grid.js.map +1 -1
- package/dist/css/index.d.ts +3 -3
- package/dist/css/index.js +3 -3
- package/dist/css/layout.d.ts +13 -1
- package/dist/css/layout.d.ts.map +1 -1
- package/dist/css/layout.js +26 -1
- package/dist/css/layout.js.map +1 -1
- package/dist/css/values.d.ts +18 -1
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +39 -1
- package/dist/css/values.js.map +1 -1
- package/dist/geometry.d.ts +6 -6
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +4 -20
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts +5 -2
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +16 -6
- package/dist/graph.js.map +1 -1
- package/dist/icons/glyph.d.ts.map +1 -1
- package/dist/icons/glyph.js +1 -1
- package/dist/icons/glyph.js.map +1 -1
- package/dist/ids.js +1 -1
- package/dist/ids.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/index.d.ts +6 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +20 -8
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/swap.js +1 -1
- package/dist/instances/swap.js.map +1 -1
- package/dist/instances/sync.js +25 -1
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/index.d.ts +2 -1
- package/dist/layout/index.js +2 -1
- package/dist/layout/strokes.d.ts +10 -0
- package/dist/layout/strokes.d.ts.map +1 -0
- package/dist/layout/strokes.js +30 -0
- package/dist/layout/strokes.js.map +1 -0
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +49 -37
- package/dist/node-defaults.js.map +1 -1
- package/dist/outline/flatten.d.ts.map +1 -1
- package/dist/outline/flatten.js +2 -2
- package/dist/outline/flatten.js.map +1 -1
- package/dist/parse-path.d.ts +4 -1
- package/dist/parse-path.d.ts.map +1 -1
- package/dist/parse-path.js +15 -1
- package/dist/parse-path.js.map +1 -1
- package/dist/paths/index.d.ts +2 -2
- package/dist/paths/index.js +2 -2
- package/dist/paths/network.d.ts +26 -6
- package/dist/paths/network.d.ts.map +1 -1
- package/dist/paths/network.js +79 -13
- package/dist/paths/network.js.map +1 -1
- package/dist/paths/smooth-corners.d.ts.map +1 -1
- package/dist/paths/smooth-corners.js +1 -1
- package/dist/paths/smooth-corners.js.map +1 -1
- package/dist/primitives/index.d.ts +1 -7
- package/dist/primitives/index.d.ts.map +1 -1
- package/dist/shaders/model.d.ts.map +1 -1
- package/dist/shaders/model.js +1 -1
- package/dist/shaders/model.js.map +1 -1
- package/dist/shared-styles.d.ts.map +1 -1
- package/dist/shared-styles.js +2 -9
- package/dist/shared-styles.js.map +1 -1
- package/dist/strokes.d.ts +39 -0
- package/dist/strokes.d.ts.map +1 -0
- package/dist/strokes.js +104 -0
- package/dist/strokes.js.map +1 -0
- package/dist/text/index.d.ts +2 -1
- package/dist/text/index.js +2 -1
- package/dist/text/runs.d.ts +29 -0
- package/dist/text/runs.d.ts.map +1 -0
- package/dist/text/runs.js +72 -0
- package/dist/text/runs.js.map +1 -0
- package/dist/transfer/dependencies.d.ts.map +1 -1
- package/dist/transfer/dependencies.js +1 -1
- package/dist/transfer/dependencies.js.map +1 -1
- package/dist/types.d.ts +35 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/resolution.d.ts.map +1 -1
- package/dist/variables/resolution.js +1 -1
- package/dist/variables/resolution.js.map +1 -1
- package/dist/vector-network.d.ts.map +1 -1
- package/dist/vector-network.js +2 -4
- package/dist/vector-network.js.map +1 -1
- package/package.json +10 -13
- package/src/comments/schema.ts +1 -0
- package/src/comments/threads.ts +13 -5
- package/src/components/properties.ts +2 -1
- package/src/constants.ts +25 -1
- package/src/copy.ts +2 -0
- package/src/css/grid.ts +31 -3
- package/src/css/index.ts +13 -2
- package/src/css/layout.ts +36 -0
- package/src/css/values.ts +49 -0
- package/src/geometry.ts +9 -27
- package/src/graph.ts +13 -6
- package/src/icons/glyph.ts +2 -1
- package/src/ids.ts +1 -1
- package/src/instances/index.ts +24 -9
- package/src/instances/swap.ts +2 -1
- package/src/instances/sync.ts +41 -0
- package/src/layout/index.ts +1 -0
- package/src/layout/strokes.ts +23 -0
- package/src/node-defaults.ts +48 -33
- package/src/outline/flatten.ts +2 -1
- package/src/parse-path.ts +14 -0
- package/src/paths/network.ts +90 -13
- package/src/paths/smooth-corners.ts +2 -1
- package/src/primitives/index.ts +0 -5
- package/src/shaders/model.ts +2 -1
- package/src/shared-styles.ts +3 -4
- package/src/strokes.ts +121 -0
- package/src/text/index.ts +1 -0
- package/src/text/runs.ts +80 -0
- package/src/transfer/dependencies.ts +2 -1
- package/src/types.ts +37 -0
- package/src/variables/resolution.ts +2 -1
- package/src/vector-network.ts +2 -4
- package/dist/arrays.d.ts +0 -17
- package/dist/arrays.d.ts.map +0 -1
- package/dist/arrays.js +0 -38
- package/dist/arrays.js.map +0 -1
- package/dist/random.d.ts +0 -7
- package/dist/random.d.ts.map +0 -1
- package/dist/random.js +0 -25
- package/dist/random.js.map +0 -1
- package/src/arrays.ts +0 -37
- package/src/random.ts +0 -28
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 { 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/** The document's records besides its nodes, which edits report changing as they do nodes. */\nexport type DocumentRecordKind = 'variable' | 'collection'\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 /** A node is about to take a preview's changes, which no history keeps. */\n previewed?: (node: SceneNode) => void\n /**\n * A variable or collection is about to change, be added, or be removed, and is still as it\n * was: absent, for one about to be added.\n */\n beforeRecord?: (kind: DocumentRecordKind, id: string) => void\n /**\n * The edit being observed waits on something outside it (`SceneGraph.waitOutsideEdit`): until\n * `resume`, nodes change for someone else's edit, not this one.\n */\n pause?: () => void\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 /** The region's own paints. Without them it draws the layer's fills, as in Figma. */\n fills?: Fill[]\n /** The shared fill style the region's paints come from. */\n fillStyleId?: string\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}\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\nexport type FillType =\n | 'SOLID'\n | 'GRADIENT_LINEAR'\n | 'GRADIENT_RADIAL'\n | 'GRADIENT_ANGULAR'\n | 'GRADIENT_DIAMOND'\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\nexport type GradientTransform = Matrix\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 /** The image an IMAGE paint draws, or the poster frame a VIDEO paint draws in its clip's place. */\n imageHash?: string\n /** A VIDEO paint's clip, which `imageHash`'s poster frame stands in for when drawn. */\n videoHash?: 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 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\n/**\n * A Glass effect's lens, in Figma's plugin terms: how far in from the edge it bends what is\n * behind the layer (`depth`, 1 to 100 px) and how strongly (`refraction`, 0 to 1), the light it\n * catches (`lightAngle` in degrees, 0 lighting the top edge, and `lightIntensity`, 0 to 1), and how\n * far the colours split (`dispersion`, 0 to 1). The effect's `radius` frosts the glass.\n */\nexport interface GlassEffectParams {\n refraction: number\n depth: number\n lightAngle: number\n lightIntensity: number\n dispersion: number\n}\n\n/**\n * A progressive blur's ramp, in Figma's plugin terms: the blur grows from `startRadius` at\n * `startOffset` to the effect's `radius` at `endOffset`, both points fractions of the layer's\n * size, and holds each end's radius beyond it.\n */\nexport interface ProgressiveBlur {\n startRadius: number\n startOffset: Vector\n endOffset: Vector\n}\n\nexport interface Effect {\n type:\n | 'DROP_SHADOW'\n | 'INNER_SHADOW'\n | 'LAYER_BLUR'\n | 'BACKGROUND_BLUR'\n | 'FOREGROUND_BLUR'\n | 'GLASS'\n color: Color\n offset: Vector\n radius: number\n spread: number\n visible: boolean\n blendMode?: BlendMode\n showShadowBehindNode?: boolean\n /** Set on a `GLASS` effect, and only there. */\n glass?: GlassEffectParams\n /** Set on a layer or background blur that is progressive, and only there. */\n progressive?: ProgressiveBlur\n}\n\nexport type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'\nexport type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT'\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\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}\nexport type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'\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\n/** A fixed width or height in pixels an export is scaled to, instead of a multiplier. */\nexport interface ExportSize {\n type: 'WIDTH' | 'HEIGHT'\n value: number\n}\n\n/** The colour profile an export is written in; the document's own unless set. */\nexport type ExportColorProfile = 'DOCUMENT' | 'SRGB' | 'DISPLAY_P3_V4'\n\n/**\n * One export a layer keeps. The options past `scale` and `format` are Figma's and read as Figma's\n * defaults when left out.\n */\nexport interface ExportSetting {\n scale: number\n format: ExportFormatId\n /** Appended to the file name. */\n suffix?: string\n /** A size that replaces `scale`. */\n size?: ExportSize\n /** Only the layer, without what overlaps it (default true). */\n contentsOnly?: boolean\n /** The layer's box rather than everything it draws, for text (default false). */\n useAbsoluteBounds?: boolean\n colorProfile?: ExportColorProfile\n /** SVG: text as outlines rather than `<text>` (default true). */\n svgOutlineText?: boolean\n /** SVG: every layer's name as its element's `id` (default false). */\n svgIdAttribute?: boolean\n /** SVG: strokes as strokes where possible rather than masked outlines (default true). */\n svgSimplifyStroke?: boolean\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; OpenPencil 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\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 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 /** Space between wrapped lines; null follows `itemSpacing`. Read it with `counterAxisSpacingOf`. */\n counterAxisSpacing: number | null\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 /**\n * The layer of a library's source document that a library definition's layer copies, which pairs\n * it with the same layer in the library's next revision whatever that layer is called by then.\n */\n libraryLayerId: string | 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 internalOnly: boolean\n\n flipX: boolean\n flipY: boolean\n\n textPicture: Uint8Array | null\n derivedTextGlyphs: DerivedTextGlyph[] | null\n /**\n * How tall a text's lines are, from the top of the first to the bottom of the last: measured at\n * its width when its text or width changes, or read from the lines a file saved, and never saved\n * itself. A fixed-size box does not clip them, as in Figma, so its visual bounds reach past the\n * box on the side away from its vertical alignment (`textLinesReach`). 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 OpenPencil 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; some may also be null. */\nexport type NumericNodeProperty = {\n [K in keyof SceneNode]-?: SceneNode[K] extends number | null\n ? number extends SceneNode[K]\n ? K\n : never\n : never\n}[keyof SceneNode]\n\nexport interface VariableCollectionMode {\n modeId: string\n name: string\n /**\n * The library mode this one came from, for a mode of a collection copied from a library. A\n * library that renames its mode renames this one with it, so the layers and the document set\n * to it keep following the library.\n */\n libraryModeId?: 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":";;AA+YA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA2lBA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAmCA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAa,wBAAwB;CAAC;CAAO;CAAW;AAAK;;;;;AAO7D,MAAa,cAAc;CAAC;CAAQ;CAAM;CAAO;CAAK;CAAM;CAAK;AAAK;;AAyFtE,SAAgB,oBAAoB,YAAsD;CACxF,OAAO,CAAC,CAAC,WAAW;AACtB;;AAGA,MAAa,yBAAyB;AAEtC,SAAgB,oBAAoB,MAAuB;CACzD,OAAO,KAAK,UAAU,OAAO,uBAAuB,KAAK,IAAI;AAC/D"}
|
|
1
|
+
{"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 { 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/** The document's records besides its nodes, which edits report changing as they do nodes. */\nexport type DocumentRecordKind = 'variable' | 'collection'\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 /** A node is about to take a preview's changes, which no history keeps. */\n previewed?: (node: SceneNode) => void\n /**\n * A variable or collection is about to change, be added, or be removed, and is still as it\n * was: absent, for one about to be added.\n */\n beforeRecord?: (kind: DocumentRecordKind, id: string) => void\n /**\n * The edit being observed waits on something outside it (`SceneGraph.waitOutsideEdit`): until\n * `resume`, nodes change for someone else's edit, not this one.\n */\n pause?: () => void\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 /** The region's own paints. Without them it draws the layer's fills, as in Figma. */\n fills?: Fill[]\n /** The shared fill style the region's paints come from. */\n fillStyleId?: string\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}\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\nexport type FillType =\n | 'SOLID'\n | 'GRADIENT_LINEAR'\n | 'GRADIENT_RADIAL'\n | 'GRADIENT_ANGULAR'\n | 'GRADIENT_DIAMOND'\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\nexport type GradientTransform = Matrix\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 /** The image an IMAGE paint draws, or the poster frame a VIDEO paint draws in its clip's place. */\n imageHash?: string\n /** A VIDEO paint's clip, which `imageHash`'s poster frame stands in for when drawn. */\n videoHash?: 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 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\n/**\n * A Glass effect's lens, in Figma's plugin terms: how far in from the edge it bends what is\n * behind the layer (`depth`, 1 to 100 px) and how strongly (`refraction`, 0 to 1), the light it\n * catches (`lightAngle` in degrees, 0 lighting the top edge, and `lightIntensity`, 0 to 1), and how\n * far the colours split (`dispersion`, 0 to 1). The effect's `radius` frosts the glass.\n */\nexport interface GlassEffectParams {\n refraction: number\n depth: number\n lightAngle: number\n lightIntensity: number\n dispersion: number\n}\n\n/**\n * A progressive blur's ramp, in Figma's plugin terms: the blur grows from `startRadius` at\n * `startOffset` to the effect's `radius` at `endOffset`, both points fractions of the layer's\n * size, and holds each end's radius beyond it.\n */\nexport interface ProgressiveBlur {\n startRadius: number\n startOffset: Vector\n endOffset: Vector\n}\n\n/**\n * A Noise effect's grain, in Figma's plugin terms: `MONOTONE` grains in the effect's colour,\n * `DUOTONE` in it and `secondaryColor`, `MULTITONE` in many colours at `opacity`. `noiseSize` is a\n * grain's size in px, which Figma keeps within 0 to 100, and `density` how much of the layer the\n * grains cover, 0 to 1. `seed` picks the pattern; Figma's plugin API neither shows nor sets it.\n */\nexport interface NoiseEffectParams {\n noiseType: NoiseType\n noiseSize: Vector\n density: number\n secondaryColor?: Color\n opacity?: number\n seed?: number\n}\n\n/**\n * A Texture effect's grain, which roughens the layer's edges: `noiseSize` is the grain's size in\n * px, within 0 to 100 as Figma keeps it, and `clipToShape` keeps the roughened layer inside its\n * own outline. The effect's `radius` is how far the grain moves the edges. `.fig` files name the\n * effect `GRAIN`.\n */\nexport interface TextureEffectParams {\n noiseSize: Vector\n clipToShape: boolean\n seed?: number\n}\n\nexport interface Effect {\n type:\n | 'DROP_SHADOW'\n | 'INNER_SHADOW'\n | 'LAYER_BLUR'\n | 'BACKGROUND_BLUR'\n | 'FOREGROUND_BLUR'\n | 'GLASS'\n | 'NOISE'\n | 'TEXTURE'\n color: Color\n offset: Vector\n radius: number\n spread: number\n visible: boolean\n blendMode?: BlendMode\n showShadowBehindNode?: boolean\n /** Set on a `GLASS` effect, and only there. */\n glass?: GlassEffectParams\n /** Set on a layer or background blur that is progressive, and only there. */\n progressive?: ProgressiveBlur\n /** Set on a `NOISE` effect, and only there. */\n noise?: NoiseEffectParams\n /** Set on a `TEXTURE` effect, and only there. */\n texture?: TextureEffectParams\n}\n\nexport type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'\nexport type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT'\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\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}\nexport type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'\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\n/** A fixed width or height in pixels an export is scaled to, instead of a multiplier. */\nexport interface ExportSize {\n type: 'WIDTH' | 'HEIGHT'\n value: number\n}\n\n/** The colour profile an export is written in; the document's own unless set. */\nexport type ExportColorProfile = 'DOCUMENT' | 'SRGB' | 'DISPLAY_P3_V4'\n\n/**\n * One export a layer keeps. The options past `scale` and `format` are Figma's and read as Figma's\n * defaults when left out.\n */\nexport interface ExportSetting {\n scale: number\n format: ExportFormatId\n /** Appended to the file name. */\n suffix?: string\n /** A size that replaces `scale`. */\n size?: ExportSize\n /** Only the layer, without what overlaps it (default true). */\n contentsOnly?: boolean\n /** The layer's box rather than everything it draws, for text (default false). */\n useAbsoluteBounds?: boolean\n colorProfile?: ExportColorProfile\n /** SVG: text as outlines rather than `<text>` (default true). */\n svgOutlineText?: boolean\n /** SVG: every layer's name as its element's `id` (default false). */\n svgIdAttribute?: boolean\n /** SVG: strokes as strokes where possible rather than masked outlines (default true). */\n svgSimplifyStroke?: boolean\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; OpenPencil 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 /** The agent that wrote it, for `author` or as itself. */\n agent?: string\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 /** The agent that wrote it, for `author` or as itself. */\n agent?: string\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\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 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 /** Space between wrapped lines; null follows `itemSpacing`. Read it with `counterAxisSpacingOf`. */\n counterAxisSpacing: number | null\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 /**\n * The layer of a library's source document that a library definition's layer copies, which pairs\n * it with the same layer in the library's next revision whatever that layer is called by then.\n */\n libraryLayerId: string | 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 internalOnly: boolean\n\n flipX: boolean\n flipY: boolean\n\n textPicture: Uint8Array | null\n derivedTextGlyphs: DerivedTextGlyph[] | null\n /**\n * How tall a text's lines are, from the top of the first to the bottom of the last: measured at\n * its width when its text or width changes, or read from the lines a file saved, and never saved\n * itself. A fixed-size box does not clip them, as in Figma, so its visual bounds reach past the\n * box on the side away from its vertical alignment (`textLinesReach`). 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 OpenPencil 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; some may also be null. */\nexport type NumericNodeProperty = {\n [K in keyof SceneNode]-?: SceneNode[K] extends number | null\n ? number extends SceneNode[K]\n ? K\n : never\n : never\n}[keyof SceneNode]\n\nexport interface VariableCollectionMode {\n modeId: string\n name: string\n /**\n * The library mode this one came from, for a mode of a collection copied from a library. A\n * library that renames its mode renames this one with it, so the layers and the document set\n * to it keep following the library.\n */\n libraryModeId?: 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":";;AAgbA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA+lBA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAmCA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAa,wBAAwB;CAAC;CAAO;CAAW;AAAK;;;;;AAO7D,MAAa,cAAc;CAAC;CAAQ;CAAM;CAAO;CAAK;CAAM;CAAK;AAAK;;AAyFtE,SAAgB,oBAAoB,YAAsD;CACxF,OAAO,CAAC,CAAC,WAAW;AACtB;;AAGA,MAAa,yBAAyB;AAEtC,SAAgB,oBAAoB,MAAuB;CACzD,OAAO,KAAK,UAAU,OAAO,uBAAuB,KAAK,IAAI;AAC/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolution.d.ts","names":[],"sources":["../../src/variables/resolution.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"resolution.d.ts","names":[],"sources":["../../src/variables/resolution.ts"],"mappings":";;;;;;;;;iBAgBgB,sBACd,OAAO,YACP,gBACA;;iBAQc,8BACd,OAAO,YACP,gBACA;;;;;iBAec,qBACd,OAAO,YACP,aAAa,mBACZ;iBAgBa,gBACd,OAAO,YACP,oBACA,iBACA,UAAU,cACT;cAaU,gCAAgC;WAGhC;WACA;EAHF;EAEE,YAAA,wFACA,oBACT;;;;;;iBAYY,uBACd,OAAO,YACP,oBACA,UAAU,iCACV,WAAQ,aACR,OAAO,YAAY,kBACnB,YAAY,oBAAoB,iBAC/B;;iBA2Ha,oBACd,OAAO,YACP,UAAU,UACV,iBACC;KAQS,wBACV,gBACA,uBACG;;iBAGW,4BAA4B,OAAO,aAAa;iBAqBhD,qBAAqB,OAAO,YAAY,qBAAqB;iBAM7D,sBAAsB,OAAO,YAAY;iBAKzC,4BACd,OAAO,YACP,gBACA,qBACC;iBAMa,6BACd,OAAO,YACP,gBACA;;iBAOc,uBACd,OAAO,YACP,gBACA,qBACC;iBAMa,6BACd,OAAO,YACP,gBACA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { appendAll } from "../arrays.js";
|
|
2
1
|
import { VariableFormulaError } from "./formula/tree.js";
|
|
3
2
|
import { resolveVariableValue, variableValueReferences } from "./value.js";
|
|
3
|
+
import { appendAll } from "@open-pencil/std/arrays";
|
|
4
4
|
//#region src/variables/resolution.ts
|
|
5
5
|
function defaultModeId(graph, collectionId) {
|
|
6
6
|
return graph.variableCollections.get(collectionId)?.defaultModeId ?? "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolution.js","names":[],"sources":["../../src/variables/resolution.ts"],"sourcesContent":["import { appendAll } from '../arrays'\nimport type { SceneGraph } from '../graph'\nimport type { Color } from '../primitives'\nimport type { Variable, VariableLiteral, VariableValue } from '../types'\nimport { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/tree'\nimport { resolveVariableValue, variableValueReferences } from './value'\n\nfunction defaultModeId(graph: SceneGraph, collectionId: string): string {\n return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''\n}\n\n/**\n * The mode a node is in for a collection: the nearest explicit mode on it or an ancestor (the page\n * included), else the collection's default, as Figma resolves it.\n */\nexport function getNodeVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string\n): string {\n return (\n getNodeExplicitVariableModeId(graph, nodeId, collectionId) ?? defaultModeId(graph, collectionId)\n )\n}\n\n/** The nearest mode set on a node or an ancestor for a collection, or null where none is. */\nexport function getNodeExplicitVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string\n): string | null {\n let node = graph.nodes.get(nodeId)\n while (node) {\n const modeId = node.variableModes[collectionId]\n if (modeId) return modeId\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return null\n}\n\n/**\n * The collections whose modes decide what these variables resolve to: their own, and those of the\n * variables they alias, at any depth and in any mode.\n */\nexport function collectionsResolving(\n graph: SceneGraph,\n variableIds: Iterable<string>\n): Set<string> {\n const pending = [...variableIds]\n const seen = new Set<string>()\n const collections = new Set<string>()\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (seen.has(id)) continue\n seen.add(id)\n const variable = graph.variables.get(id)\n if (!variable) continue\n collections.add(variable.collectionId)\n for (const value of Object.values(variable.valuesByMode))\n appendAll(pending, variableValueReferences(value))\n }\n return collections\n}\n\nexport function resolveVariable(\n graph: SceneGraph,\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n): VariableLiteral | undefined {\n const initial = graph.variables.get(variableId)\n return resolveInModes(\n graph,\n variableId,\n (collectionId) =>\n modeId && initial?.collectionId === collectionId\n ? modeId\n : defaultModeId(graph, collectionId),\n visited\n )\n}\n\nexport class VariableResolutionError extends VariableFormulaError {\n override name = 'VariableResolutionError'\n constructor(\n readonly code: 'cycle' | 'depth' | 'missing-variable' | 'missing-value' | 'type' | 'non-finite',\n readonly variableId: string,\n message: string\n ) {\n super(message)\n }\n}\n\nconst RESULT_TYPES = { FLOAT: 'number', BOOLEAN: 'boolean', STRING: 'string', COLOR: 'object' }\n\n/**\n * Resolve a draft or saved definition with identical mode, dependency and error semantics. A\n * memo shares values between lookups in one mode context; without one, nothing is cached.\n */\nexport function resolveVariableInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting = new Set<string>(),\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n if (visiting.has(variableId))\n throw new VariableResolutionError('cycle', variableId, 'Circular variable reference')\n if (visiting.size >= MAX_FORMULA_DEPTH)\n throw new VariableResolutionError('depth', variableId, 'Too many linked variables')\n const variable = graph.variables.get(variableId)\n if (!variable)\n throw new VariableResolutionError(\n 'missing-variable',\n variableId,\n `Missing variable: ${variableId}`\n )\n const value =\n overrides?.get(variableId) ??\n variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (value === undefined)\n throw new VariableResolutionError(\n 'missing-value',\n variableId,\n `Missing value: ${variable.name}`\n )\n return evaluateDefinition(graph, variable, value, modeFor, visiting, memo, overrides)\n}\n\n/** Resolve one variable's definition in its mode context, its dependencies in theirs. */\nfunction evaluateDefinition(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting: Set<string>,\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const variableId = variable.id\n visiting.add(variableId)\n try {\n const result = resolveVariableValue(value, (id) =>\n resolveVariableInModes(graph, id, modeFor, visiting, memo, overrides)\n )\n if (result === undefined || typeof result !== RESULT_TYPES[variable.type])\n throw new VariableResolutionError('type', variableId, `Wrong result type: ${variable.name}`)\n if (typeof result === 'number' && !Number.isFinite(result))\n throw new VariableResolutionError(\n 'non-finite',\n variableId,\n `Non-finite value: ${variable.name}`\n )\n // Failures can depend on the current path's depth. Only completed values are reusable.\n memo?.set(variableId, result)\n return result\n } finally {\n visiting.delete(variableId)\n }\n}\n\n/**\n * What the canvas draws for a variable, or nothing when it cannot be resolved. Literals and alias\n * chains, which most bindings are, resolve in a loop; an expression on the way takes the full\n * resolver, whose diagnostics the canvas does not need.\n */\nfunction resolveInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n const initial = graph.variables.get(variableId)\n if (!initial) return undefined\n let id = variableId\n for (let depth = visiting?.size ?? 0; depth < MAX_FORMULA_DEPTH; depth++) {\n const variable = id === variableId ? initial : graph.variables.get(id)\n if (!variable || visiting?.has(id)) return undefined\n const value = variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (typeof value === 'object' && 'aliasId' in value) {\n id = value.aliasId\n continue\n }\n const result =\n typeof value === 'object' && 'expression' in value\n ? resolveExpression(graph, variable, value, modeFor, visiting, memo)\n : value\n return drawable(result, initial.type)\n }\n return undefined\n}\n\n/** A formula shares its dependencies' values for the length of one resolution. */\nfunction resolveExpression(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n try {\n return evaluateDefinition(\n graph,\n variable,\n value,\n modeFor,\n visiting ?? new Set(),\n memo ?? new Map()\n )\n } catch {\n return undefined\n }\n}\n\n/** A resolved value the canvas can draw for a variable of this type, or nothing. */\nfunction drawable(value: VariableValue | undefined, type: Variable['type']) {\n if (value === undefined || typeof value !== RESULT_TYPES[type]) return undefined\n if (typeof value === 'object' && !('r' in value)) return undefined\n return typeof value === 'number' && !Number.isFinite(value) ? undefined : value\n}\n\n/** Shared mode fallback for canvas resolution and formula draft validation. */\nexport function variableValueInMode(\n graph: SceneGraph,\n variable: Variable,\n modeId: string\n): VariableValue | undefined {\n const values = variable.valuesByMode\n if (Object.hasOwn(values, modeId)) return values[modeId]\n const defaultMode = graph.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''\n if (Object.hasOwn(values, defaultMode)) return values[defaultMode]\n return Object.values(values).at(0)\n}\n\nexport type NodeVariableResolver = (\n nodeId: string,\n variableId: string\n) => VariableLiteral | undefined\n\n/** One read/reconcile operation only: equal mode contexts share results, edits start a new cache. */\nexport function createBatchVariableResolver(graph: SceneGraph): NodeVariableResolver {\n const collections = [...graph.variableCollections.keys()]\n const contexts = new Map<string, Map<string, VariableLiteral>>()\n return (nodeId, variableId) => {\n const modes = collections.map((id) => getNodeVariableModeId(graph, nodeId, id))\n const key = JSON.stringify(modes)\n let memo = contexts.get(key)\n if (!memo) {\n memo = new Map()\n contexts.set(key, memo)\n }\n return resolveInModes(\n graph,\n variableId,\n (id) => modes[collections.indexOf(id)] ?? '',\n undefined,\n memo\n )\n }\n}\n\nexport function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {\n const value = resolveVariable(graph, variableId)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {\n const value = resolveVariable(graph, variableId)\n return typeof value === 'number' ? value : undefined\n}\n\nexport function resolveColorVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): Color | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): number | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId)\n return typeof value === 'number' ? value : undefined\n}\n\n/** A variable's value in the mode a node is in, aliases followed. */\nexport function resolveVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): VariableLiteral | undefined {\n return resolveInModes(graph, variableId, (collectionId) =>\n getNodeVariableModeId(graph, nodeId, collectionId)\n )\n}\n\nexport function resolveStringVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): string | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId)\n return typeof value === 'string' ? value : undefined\n}\n"],"mappings":";;;;AAOA,SAAS,cAAc,OAAmB,cAA8B;CACtE,OAAO,MAAM,oBAAoB,IAAI,YAAY,CAAC,EAAE,iBAAiB;AACvE;;;;;AAMA,SAAgB,sBACd,OACA,QACA,cACQ;CACR,OACE,8BAA8B,OAAO,QAAQ,YAAY,KAAK,cAAc,OAAO,YAAY;AAEnG;;AAGA,SAAgB,8BACd,OACA,QACA,cACe;CACf,IAAI,OAAO,MAAM,MAAM,IAAI,MAAM;CACjC,OAAO,MAAM;EACX,MAAM,SAAS,KAAK,cAAc;EAClC,IAAI,QAAQ,OAAO;EACnB,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAC1D;CACA,OAAO;AACT;;;;;AAMA,SAAgB,qBACd,OACA,aACa;CACb,MAAM,UAAU,CAAC,GAAG,WAAW;CAC/B,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,8BAAc,IAAI,IAAY;CACpC,KAAK,IAAI,KAAK,QAAQ,IAAI,GAAG,OAAO,KAAA,GAAW,KAAK,QAAQ,IAAI,GAAG;EACjE,IAAI,KAAK,IAAI,EAAE,GAAG;EAClB,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AAM,QAAQ,gBAAgB,OAAO,UAAU;CAC/C,IAAI,SAAS,OAAO,UAAU,YAAY,OAAO,OAAO,OAAO;AAEjE;AAEA,SAAgB,sBAAsB,OAAmB,YAAwC;CAC/F,MAAM,QAAQ,gBAAgB,OAAO,UAAU;CAC/C,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAgB,4BACd,OACA,QACA,YACmB;CACnB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,UAAU;CAC9D,IAAI,SAAS,OAAO,UAAU,YAAY,OAAO,OAAO,OAAO;AAEjE;AAEA,SAAgB,6BACd,OACA,QACA,YACoB;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,UAAU;CAC9D,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;AAGA,SAAgB,uBACd,OACA,QACA,YAC6B;CAC7B,OAAO,eAAe,OAAO,aAAa,iBACxC,sBAAsB,OAAO,QAAQ,YAAY,CACnD;AACF;AAEA,SAAgB,6BACd,OACA,QACA,YACoB;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,UAAU;CAC9D,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C"}
|
|
1
|
+
{"version":3,"file":"resolution.js","names":[],"sources":["../../src/variables/resolution.ts"],"sourcesContent":["import { appendAll } from '@open-pencil/std/arrays'\n\nimport type { SceneGraph } from '../graph'\nimport type { Color } from '../primitives'\nimport type { Variable, VariableLiteral, VariableValue } from '../types'\nimport { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/tree'\nimport { resolveVariableValue, variableValueReferences } from './value'\n\nfunction defaultModeId(graph: SceneGraph, collectionId: string): string {\n return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''\n}\n\n/**\n * The mode a node is in for a collection: the nearest explicit mode on it or an ancestor (the page\n * included), else the collection's default, as Figma resolves it.\n */\nexport function getNodeVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string\n): string {\n return (\n getNodeExplicitVariableModeId(graph, nodeId, collectionId) ?? defaultModeId(graph, collectionId)\n )\n}\n\n/** The nearest mode set on a node or an ancestor for a collection, or null where none is. */\nexport function getNodeExplicitVariableModeId(\n graph: SceneGraph,\n nodeId: string,\n collectionId: string\n): string | null {\n let node = graph.nodes.get(nodeId)\n while (node) {\n const modeId = node.variableModes[collectionId]\n if (modeId) return modeId\n node = node.parentId ? graph.nodes.get(node.parentId) : undefined\n }\n return null\n}\n\n/**\n * The collections whose modes decide what these variables resolve to: their own, and those of the\n * variables they alias, at any depth and in any mode.\n */\nexport function collectionsResolving(\n graph: SceneGraph,\n variableIds: Iterable<string>\n): Set<string> {\n const pending = [...variableIds]\n const seen = new Set<string>()\n const collections = new Set<string>()\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (seen.has(id)) continue\n seen.add(id)\n const variable = graph.variables.get(id)\n if (!variable) continue\n collections.add(variable.collectionId)\n for (const value of Object.values(variable.valuesByMode))\n appendAll(pending, variableValueReferences(value))\n }\n return collections\n}\n\nexport function resolveVariable(\n graph: SceneGraph,\n variableId: string,\n modeId?: string,\n visited?: Set<string>\n): VariableLiteral | undefined {\n const initial = graph.variables.get(variableId)\n return resolveInModes(\n graph,\n variableId,\n (collectionId) =>\n modeId && initial?.collectionId === collectionId\n ? modeId\n : defaultModeId(graph, collectionId),\n visited\n )\n}\n\nexport class VariableResolutionError extends VariableFormulaError {\n override name = 'VariableResolutionError'\n constructor(\n readonly code: 'cycle' | 'depth' | 'missing-variable' | 'missing-value' | 'type' | 'non-finite',\n readonly variableId: string,\n message: string\n ) {\n super(message)\n }\n}\n\nconst RESULT_TYPES = { FLOAT: 'number', BOOLEAN: 'boolean', STRING: 'string', COLOR: 'object' }\n\n/**\n * Resolve a draft or saved definition with identical mode, dependency and error semantics. A\n * memo shares values between lookups in one mode context; without one, nothing is cached.\n */\nexport function resolveVariableInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting = new Set<string>(),\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n if (visiting.has(variableId))\n throw new VariableResolutionError('cycle', variableId, 'Circular variable reference')\n if (visiting.size >= MAX_FORMULA_DEPTH)\n throw new VariableResolutionError('depth', variableId, 'Too many linked variables')\n const variable = graph.variables.get(variableId)\n if (!variable)\n throw new VariableResolutionError(\n 'missing-variable',\n variableId,\n `Missing variable: ${variableId}`\n )\n const value =\n overrides?.get(variableId) ??\n variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (value === undefined)\n throw new VariableResolutionError(\n 'missing-value',\n variableId,\n `Missing value: ${variable.name}`\n )\n return evaluateDefinition(graph, variable, value, modeFor, visiting, memo, overrides)\n}\n\n/** Resolve one variable's definition in its mode context, its dependencies in theirs. */\nfunction evaluateDefinition(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting: Set<string>,\n memo?: Map<string, VariableLiteral>,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableLiteral {\n const variableId = variable.id\n visiting.add(variableId)\n try {\n const result = resolveVariableValue(value, (id) =>\n resolveVariableInModes(graph, id, modeFor, visiting, memo, overrides)\n )\n if (result === undefined || typeof result !== RESULT_TYPES[variable.type])\n throw new VariableResolutionError('type', variableId, `Wrong result type: ${variable.name}`)\n if (typeof result === 'number' && !Number.isFinite(result))\n throw new VariableResolutionError(\n 'non-finite',\n variableId,\n `Non-finite value: ${variable.name}`\n )\n // Failures can depend on the current path's depth. Only completed values are reusable.\n memo?.set(variableId, result)\n return result\n } finally {\n visiting.delete(variableId)\n }\n}\n\n/**\n * What the canvas draws for a variable, or nothing when it cannot be resolved. Literals and alias\n * chains, which most bindings are, resolve in a loop; an expression on the way takes the full\n * resolver, whose diagnostics the canvas does not need.\n */\nfunction resolveInModes(\n graph: SceneGraph,\n variableId: string,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n const cached = memo?.get(variableId)\n if (cached !== undefined) return cached\n const initial = graph.variables.get(variableId)\n if (!initial) return undefined\n let id = variableId\n for (let depth = visiting?.size ?? 0; depth < MAX_FORMULA_DEPTH; depth++) {\n const variable = id === variableId ? initial : graph.variables.get(id)\n if (!variable || visiting?.has(id)) return undefined\n const value = variableValueInMode(graph, variable, modeFor(variable.collectionId))\n if (typeof value === 'object' && 'aliasId' in value) {\n id = value.aliasId\n continue\n }\n const result =\n typeof value === 'object' && 'expression' in value\n ? resolveExpression(graph, variable, value, modeFor, visiting, memo)\n : value\n return drawable(result, initial.type)\n }\n return undefined\n}\n\n/** A formula shares its dependencies' values for the length of one resolution. */\nfunction resolveExpression(\n graph: SceneGraph,\n variable: Variable,\n value: VariableValue,\n modeFor: (collectionId: string) => string,\n visiting?: Set<string>,\n memo?: Map<string, VariableLiteral>\n): VariableLiteral | undefined {\n try {\n return evaluateDefinition(\n graph,\n variable,\n value,\n modeFor,\n visiting ?? new Set(),\n memo ?? new Map()\n )\n } catch {\n return undefined\n }\n}\n\n/** A resolved value the canvas can draw for a variable of this type, or nothing. */\nfunction drawable(value: VariableValue | undefined, type: Variable['type']) {\n if (value === undefined || typeof value !== RESULT_TYPES[type]) return undefined\n if (typeof value === 'object' && !('r' in value)) return undefined\n return typeof value === 'number' && !Number.isFinite(value) ? undefined : value\n}\n\n/** Shared mode fallback for canvas resolution and formula draft validation. */\nexport function variableValueInMode(\n graph: SceneGraph,\n variable: Variable,\n modeId: string\n): VariableValue | undefined {\n const values = variable.valuesByMode\n if (Object.hasOwn(values, modeId)) return values[modeId]\n const defaultMode = graph.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''\n if (Object.hasOwn(values, defaultMode)) return values[defaultMode]\n return Object.values(values).at(0)\n}\n\nexport type NodeVariableResolver = (\n nodeId: string,\n variableId: string\n) => VariableLiteral | undefined\n\n/** One read/reconcile operation only: equal mode contexts share results, edits start a new cache. */\nexport function createBatchVariableResolver(graph: SceneGraph): NodeVariableResolver {\n const collections = [...graph.variableCollections.keys()]\n const contexts = new Map<string, Map<string, VariableLiteral>>()\n return (nodeId, variableId) => {\n const modes = collections.map((id) => getNodeVariableModeId(graph, nodeId, id))\n const key = JSON.stringify(modes)\n let memo = contexts.get(key)\n if (!memo) {\n memo = new Map()\n contexts.set(key, memo)\n }\n return resolveInModes(\n graph,\n variableId,\n (id) => modes[collections.indexOf(id)] ?? '',\n undefined,\n memo\n )\n }\n}\n\nexport function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {\n const value = resolveVariable(graph, variableId)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {\n const value = resolveVariable(graph, variableId)\n return typeof value === 'number' ? value : undefined\n}\n\nexport function resolveColorVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): Color | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId)\n if (value && typeof value === 'object' && 'r' in value) return value\n return undefined\n}\n\nexport function resolveNumberVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): number | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId)\n return typeof value === 'number' ? value : undefined\n}\n\n/** A variable's value in the mode a node is in, aliases followed. */\nexport function resolveVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): VariableLiteral | undefined {\n return resolveInModes(graph, variableId, (collectionId) =>\n getNodeVariableModeId(graph, nodeId, collectionId)\n )\n}\n\nexport function resolveStringVariableForNode(\n graph: SceneGraph,\n nodeId: string,\n variableId: string\n): string | undefined {\n const value = resolveVariableForNode(graph, nodeId, variableId)\n return typeof value === 'string' ? value : undefined\n}\n"],"mappings":";;;;AAQA,SAAS,cAAc,OAAmB,cAA8B;CACtE,OAAO,MAAM,oBAAoB,IAAI,YAAY,CAAC,EAAE,iBAAiB;AACvE;;;;;AAMA,S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OACA,QACA,YACoB;CACpB,MAAM,QAAQ,uBAAuB,OAAO,QAAQ,UAAU;CAC9D,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector-network.d.ts","names":[],"sources":["../src/vector-network.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"vector-network.d.ts","names":[],"sources":["../src/vector-network.ts"],"mappings":";;;;;iBAagB,oBAAoB,mBAAmB,kBAAkB;;;;;;iBAuCzD,uBAAuB,GAAG,MAAM,IAAI,gBAAgB;;iBAqBpD,eAAe,SAAS;;;;;iBAQxB,2BACd,uBAAuB,gBACvB,SAAS;;;;;iBASK,kBACd,SAAS,sBACT,qBAAqB;;;;;iBAmBP,kBACd,MAAM,WACN,SAAS,QAAQ,aAChB,KAAK,QAAQ;;iBAQA,YAAY,SAAS,uBAAuB;;iBAK5C,oBAAoB,GAAG,eAAe,GAAG;;;;;iBAYzC,sBAAsB;KAyK1B,4BAA4B,KAAK;EAC3C,UAAU;;;;;;;iBAQI,uBAAuB,IAAI,4BAA4B;iBAoCvD,wBACd,SAAS,eACT;;iBAkBc,eAAe,SAAS,eAAe;;iBAUvC,gBAAgB,UAAU,WAAW,gBAAgB;;UAMpD;EACf,aAAa;EACb;;;;;;iBAOc,mBAAmB,SAAS,gBAAgB"}
|
package/dist/vector-network.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { cloneVectorNetwork, copyVectorRegion } from "./copy.js";
|
|
2
1
|
import { addOpenSegmentsToPath, addRegionToPath } from "./paths/network.js";
|
|
2
|
+
import { cloneVectorNetwork, copyVectorRegion } from "./copy.js";
|
|
3
3
|
import { svgPathSink } from "./paths/sink.js";
|
|
4
4
|
import { isEqual } from "es-toolkit/predicate";
|
|
5
|
+
import { isRecord } from "@open-pencil/std/records";
|
|
5
6
|
//#region src/vector-network.ts
|
|
6
7
|
/** Concatenate vector networks while preserving independent geometry. */
|
|
7
8
|
function mergeVectorNetworks(networks) {
|
|
@@ -209,9 +210,6 @@ function isFiniteVector(value) {
|
|
|
209
210
|
function isInteger(value) {
|
|
210
211
|
return typeof value === "number" && Number.isInteger(value);
|
|
211
212
|
}
|
|
212
|
-
function isRecord(value) {
|
|
213
|
-
return typeof value === "object" && value !== null;
|
|
214
|
-
}
|
|
215
213
|
/**
|
|
216
214
|
* Ensure every segment has tangentStart/tangentEnd and a regions array.
|
|
217
215
|
* Missing tangents default to {x:0, y:0} (straight line segments).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector-network.js","names":[],"sources":["../src/vector-network.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport { cloneVectorNetwork, copyVectorRegion } from './copy'\nimport type { Mat3 } from './matrix'\nimport type { VectorPathWindingRule } from './parse-path'\nimport { addOpenSegmentsToPath, addRegionToPath } from './paths/network'\nimport { svgPathSink } from './paths/sink'\nimport type { Vector } from './primitives'\nimport type { Fill, GeometryPath, SceneNode, VectorNetwork, VectorSegment } from './types'\n\n/** Concatenate vector networks while preserving independent geometry. */\nexport function mergeVectorNetworks(networks: readonly VectorNetwork[]): VectorNetwork {\n const vertices: VectorNetwork['vertices'] = []\n const segments: VectorNetwork['segments'] = []\n const regions: VectorNetwork['regions'] = []\n let vertexOffset = 0\n let segmentOffset = 0\n\n for (const network of networks) {\n for (const vertex of network.vertices) vertices.push({ ...vertex })\n for (const segment of network.segments) {\n segments.push({\n ...segment,\n start: segment.start + vertexOffset,\n end: segment.end + vertexOffset,\n tangentStart: { ...segment.tangentStart },\n tangentEnd: { ...segment.tangentEnd }\n })\n }\n for (const region of network.regions) {\n const loops: number[][] = []\n for (const loop of region.loops) {\n const shifted: number[] = []\n for (const segmentIndex of loop) shifted.push(segmentIndex + segmentOffset)\n loops.push(shifted)\n }\n regions.push(copyVectorRegion(region, loops))\n }\n vertexOffset += network.vertices.length\n segmentOffset += network.segments.length\n }\n\n return { vertices, segments, regions }\n}\n\n/**\n * Map a VectorNetwork through an affine matrix: vertices as points,\n * tangents as direction vectors (linear part only, no translation).\n * Returns a deep copy; the input is not mutated.\n */\nexport function transformVectorNetwork(m: Mat3, vn: VectorNetwork): VectorNetwork {\n const mapVector = (v: Vector): Vector => ({\n x: m[0] * v.x + m[1] * v.y,\n y: m[3] * v.x + m[4] * v.y\n })\n return {\n vertices: vn.vertices.map((v) => ({\n ...v,\n x: m[0] * v.x + m[1] * v.y + m[2],\n y: m[3] * v.x + m[4] * v.y + m[5]\n })),\n segments: vn.segments.map((s) => ({\n ...s,\n tangentStart: mapVector(s.tangentStart),\n tangentEnd: mapVector(s.tangentEnd)\n })),\n regions: vn.regions.map((r) => copyVectorRegion(r))\n }\n}\n\n/** Whether any region has paints of its own, which it draws instead of the layer's fills. */\nexport function hasRegionFills(network: VectorNetwork | null): boolean {\n return network?.regions.some((region) => region.fills !== undefined) ?? false\n}\n\n/**\n * Whether fill geometry is the regions' outlines, one each, as a file or an edit writes it. A\n * pasted vector has none, and an import skips empty outlines; their regions draw traced.\n */\nexport function fillGeometryMatchesRegions(\n fillGeometry: readonly GeometryPath[],\n network: VectorNetwork\n): boolean {\n return fillGeometry.length === network.regions.length\n}\n\n/**\n * Whether a vector's regions draw different fills, each its own or else the layer's, which Figma\n * reads as mixed (live-verified: regions with equal fills of their own read the layer's).\n */\nexport function regionFillsDiffer(\n network: VectorNetwork | null,\n layerFills: readonly Fill[]\n): boolean {\n const [first, ...rest] = (network?.regions ?? []).map((region) => region.fills ?? layerFills)\n return rest.some((fills) => !isEqual(fills, first))\n}\n\n/** The network with every region drawing the layer's fills. */\nfunction withoutRegionFills(network: VectorNetwork): VectorNetwork {\n const copy = cloneVectorNetwork(network)\n return {\n ...copy,\n regions: copy.regions.map(({ windingRule, loops }) => ({ windingRule, loops }))\n }\n}\n\n/**\n * What else an edit that sets a vector's fills changes: every region draws them, its own paints\n * and style dropped, as setting fills does in Figma (live-verified). Edit entry points apply it.\n */\nexport function regionFillChanges(\n node: SceneNode,\n changes: Partial<SceneNode>\n): Pick<Partial<SceneNode>, 'vectorNetwork'> {\n const network = node.type === 'VECTOR' ? node.vectorNetwork : null\n if (!('fills' in changes) || 'vectorNetwork' in changes || !network) return {}\n const ownFills = network.regions.some((region) => region.fills || region.fillStyleId)\n return ownFills ? { vectorNetwork: withoutRegionFills(network) } : {}\n}\n\n/** The paints regions carry of their own. */\nexport function regionFills(network: VectorNetwork | null): Fill[] {\n return network?.regions.flatMap((region) => region.fills ?? []) ?? []\n}\n\n/** Structural equality of two VectorNetworks (order-sensitive, exact values). */\nexport function vectorNetworksEqual(a: VectorNetwork, b: VectorNetwork): boolean {\n return (\n isEqual(a.vertices, b.vertices) &&\n isEqual(a.segments, b.segments) &&\n isEqual(a.regions, b.regions)\n )\n}\n\n/**\n * Validate a VectorNetwork structure, returning an array of error messages.\n * Empty array means the network is valid.\n */\nexport function validateVectorNetwork(value: unknown): string[] {\n if (!isRecord(value)) return ['network must be an object']\n if (!Array.isArray(value.vertices)) return ['vertices must be an array']\n if (!Array.isArray(value.segments)) return ['segments must be an array']\n\n const errors: string[] = []\n validateVertices(value.vertices, errors)\n validateSegments(value.segments, value.vertices.length, errors)\n const typedSegments = value.segments.filter(isSegmentRecord)\n if (value.regions !== undefined) {\n if (Array.isArray(value.regions)) {\n validateRegions(\n value.regions,\n value.segments.length,\n typedSegments.length === value.segments.length ? typedSegments : null,\n errors\n )\n } else {\n errors.push('regions must be an array when provided')\n }\n }\n return errors\n}\n\nfunction validateVertices(vertices: unknown[], errors: string[]): void {\n for (let index = 0; index < vertices.length; index++) {\n if (!isFiniteVector(vertices[index])) {\n errors.push(`vertex[${index}]: x and y must be finite numbers`)\n }\n }\n}\n\nfunction validateSegments(segments: unknown[], vertexCount: number, errors: string[]): void {\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index]\n if (!isRecord(segment)) {\n errors.push(`segment[${index}] must be an object`)\n continue\n }\n if (!isInteger(segment.start) || !isInteger(segment.end)) {\n errors.push(`segment[${index}]: start and end must be integers`)\n continue\n }\n if (segment.start < 0 || segment.start >= vertexCount) {\n errors.push(`segment[${index}]: start index ${segment.start} out of range`)\n }\n if (segment.end < 0 || segment.end >= vertexCount) {\n errors.push(`segment[${index}]: end index ${segment.end} out of range`)\n }\n validateSegmentTangents(segment, index, errors)\n }\n}\n\nfunction validateSegmentTangents(\n segment: Record<string, unknown>,\n index: number,\n errors: string[]\n): void {\n for (const tangentKey of ['tangentStart', 'tangentEnd'] as const) {\n const tangent = segment[tangentKey]\n if (tangent !== undefined && !isFiniteVector(tangent)) {\n errors.push(`segment[${index}]: ${tangentKey} must contain finite x and y numbers`)\n }\n }\n}\n\nfunction validateRegions(\n regions: unknown[],\n segmentCount: number,\n segments: Array<Record<'start' | 'end', number>> | null,\n errors: string[]\n): void {\n for (let regionIndex = 0; regionIndex < regions.length; regionIndex++) {\n const region = regions[regionIndex]\n if (!isRecord(region) || !Array.isArray(region.loops)) {\n errors.push(`region[${regionIndex}]: loops must be an array`)\n continue\n }\n if (region.windingRule !== 'NONZERO' && region.windingRule !== 'EVENODD') {\n errors.push(`region[${regionIndex}]: windingRule must be NONZERO or EVENODD`)\n }\n if (region.loops.length === 0) {\n errors.push(`region[${regionIndex}]: loops must contain at least one loop`)\n }\n validateRegionLoops(region.loops, regionIndex, segmentCount, segments, errors)\n }\n}\n\nfunction validateRegionLoops(\n loops: unknown[],\n regionIndex: number,\n segmentCount: number,\n segments: Array<Record<'start' | 'end', number>> | null,\n errors: string[]\n): void {\n for (let loopIndex = 0; loopIndex < loops.length; loopIndex++) {\n const loop = loops[loopIndex]\n if (!Array.isArray(loop)) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] must be an array`)\n continue\n }\n if (loop.length === 0) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] must contain at least one segment`)\n continue\n }\n\n const segmentIndices: number[] = []\n for (const segmentIndex of loop) {\n if (!isInteger(segmentIndex) || segmentIndex < 0 || segmentIndex >= segmentCount) {\n errors.push(\n `region[${regionIndex}].loop[${loopIndex}]: segment index ${String(segmentIndex)} out of range`\n )\n } else {\n segmentIndices.push(segmentIndex)\n }\n }\n if (segmentIndices.length !== loop.length) continue\n if (new Set(segmentIndices).size !== segmentIndices.length) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] must not repeat segments`)\n continue\n }\n if (segments && !formsContinuousChain(segmentIndices, segments)) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] segments must form a continuous chain`)\n }\n }\n}\n\nfunction formsContinuousChain(\n indices: number[],\n segments: Array<Record<'start' | 'end', number>>\n): boolean {\n if (indices.length <= 1) return true\n const first = segments[indices[0]]\n return followsChain(indices, segments, first.end) || followsChain(indices, segments, first.start)\n}\n\nfunction followsChain(\n indices: number[],\n segments: Array<Record<'start' | 'end', number>>,\n initialEnd: number\n): boolean {\n let current = initialEnd\n for (let index = 1; index < indices.length; index++) {\n const segment = segments[indices[index]]\n if (segment.start === current) current = segment.end\n else if (segment.end === current) current = segment.start\n else return false\n }\n return true\n}\n\nfunction isSegmentRecord(value: unknown): value is Record<'start' | 'end', number> {\n return isRecord(value) && isInteger(value.start) && isInteger(value.end)\n}\n\nfunction isFiniteVector(value: unknown): value is Vector {\n return (\n isRecord(value) &&\n typeof value.x === 'number' &&\n Number.isFinite(value.x) &&\n typeof value.y === 'number' &&\n Number.isFinite(value.y)\n )\n}\n\nfunction isInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nexport type NormalizableVectorNetwork = Omit<VectorNetwork, 'regions'> & {\n regions?: VectorNetwork['regions']\n}\n\n/**\n * Ensure every segment has tangentStart/tangentEnd and a regions array.\n * Missing tangents default to {x:0, y:0} (straight line segments).\n * Use at system boundaries where input may come from JSON/MCP.\n */\nexport function normalizeVectorNetwork(vn: NormalizableVectorNetwork): VectorNetwork {\n const ZERO: Vector = { x: 0, y: 0 }\n return {\n vertices: vn.vertices,\n segments: vn.segments.map((s) => ({\n start: s.start,\n end: s.end,\n tangentStart: (s as Partial<VectorSegment>).tangentStart ?? { ...ZERO },\n tangentEnd: (s as Partial<VectorSegment>).tangentEnd ?? { ...ZERO }\n })),\n regions: vn.regions ?? []\n }\n}\n\nfunction coordinate(value: number, decimals: number | null): number {\n if (decimals === null) return value\n const factor = 10 ** decimals\n return Math.round(value * factor) / factor\n}\n\n/** Coordinates written at `decimals`, or as they are for `null`. */\nfunction coordinateFormat(decimals: number | null): (value: number) => number {\n return (value) => coordinate(value, decimals)\n}\n\n/** A network's segments as one open path, chained as the canvas draws them. */\nfunction unfilledSegmentsToPath(network: VectorNetwork, decimals: number | null): string {\n const parts: string[] = []\n addOpenSegmentsToPath(\n svgPathSink(parts, coordinateFormat(decimals)),\n network.segments,\n network.vertices\n )\n return parts.join('')\n}\n\nexport function vectorNetworkToSVGPaths(\n network: VectorNetwork,\n decimals: number | null = 2\n): string[] {\n const { vertices, regions } = network\n\n if (regions.length === 0) {\n const path = unfilledSegmentsToPath(network, decimals)\n return path ? [path] : []\n }\n const paths = regionSVGPaths(network, decimals)\n // Segments no region encloses, such as an icon's open strokes beside its filled shapes,\n // draw as open paths after the regions.\n const open = looseSegments(network)\n const loose =\n open.length > 0 && unfilledSegmentsToPath({ vertices, segments: open, regions: [] }, decimals)\n return loose ? [...paths, loose] : paths\n}\n\n/** Each region of a vector network as path data, its loops traced in turn. */\nexport function regionSVGPaths(network: VectorNetwork, decimals: number | null = 2): string[] {\n const { vertices, segments, regions } = network\n return regions.map((region) => {\n const parts: string[] = []\n addRegionToPath(svgPathSink(parts, coordinateFormat(decimals)), region, segments, vertices)\n return parts.join('')\n })\n}\n\n/** The segments of a vector network that no region encloses. */\nexport function looseSegments({ segments, regions }: VectorNetwork): VectorNetwork['segments'] {\n const enclosed = new Set(regions.flatMap((region) => region.loops.flat()))\n return segments.filter((_, index) => !enclosed.has(index))\n}\n\n/** A path of a vector network as Figma's `vectorPaths` gives it. */\nexport interface VectorPath {\n windingRule: VectorPathWindingRule\n data: string\n}\n\n/**\n * A vector network as Figma's `vectorPaths`: each region as a path with its winding rule, then\n * the segments no region encloses as one open path, at full precision.\n */\nexport function vectorNetworkPaths(network: VectorNetwork): VectorPath[] {\n if (network.segments.length === 0) return []\n const paths: VectorPath[] = regionSVGPaths(network, null).flatMap((data, index) =>\n data ? [{ windingRule: network.regions[index].windingRule, data }] : []\n )\n const open = looseSegments(network)\n if (open.length === 0) return paths\n const data = vectorNetworkToSVGPaths(\n { vertices: network.vertices, segments: open, regions: [] },\n null\n ).join('')\n return data ? [...paths, { windingRule: 'NONE', data }] : paths\n}\n"],"mappings":";;;;;;AAWA,SAAgB,oBAAoB,UAAmD;CACrF,MAAM,WAAsC,CAAC;CAC7C,MAAM,WAAsC,CAAC;CAC7C,MAAM,UAAoC,CAAC;CAC3C,IAAI,eAAe;CACnB,IAAI,gBAAgB;CAEpB,KAAK,MAAM,WAAW,UAAU;EAC9B,KAAK,MAAM,UAAU,QAAQ,UAAU,SAAS,KAAK,EAAE,GAAG,OAAO,CAAC;EAClE,KAAK,MAAM,WAAW,QAAQ,UAC5B,SAAS,KAAK;GACZ,GAAG;GACH,OAAO,QAAQ,QAAQ;GACvB,KAAK,QAAQ,MAAM;GACnB,cAAc,EAAE,GAAG,QAAQ,aAAa;GACxC,YAAY,EAAE,GAAG,QAAQ,WAAW;EACtC,CAAC;EAEH,KAAK,MAAM,UAAU,QAAQ,SAAS;GACpC,MAAM,QAAoB,CAAC;GAC3B,KAAK,MAAM,QAAQ,OAAO,OAAO;IAC/B,MAAM,UAAoB,CAAC;IAC3B,KAAK,MAAM,gBAAgB,MAAM,QAAQ,KAAK,eAAe,aAAa;IAC1E,MAAM,KAAK,OAAO;GACpB;GACA,QAAQ,KAAK,iBAAiB,QAAQ,KAAK,CAAC;EAC9C;EACA,gBAAgB,QAAQ,SAAS;EACjC,iBAAiB,QAAQ,SAAS;CACpC;CAEA,OAAO;EAAE;E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O,CAAC,GAAG,OAAO;EAAE,aAAa;EAAQ;CAAK,CAAC,IAAI;AAC5D"}
|
|
1
|
+
{"version":3,"file":"vector-network.js","names":[],"sources":["../src/vector-network.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport { isRecord } from '@open-pencil/std/records'\n\nimport { cloneVectorNetwork, copyVectorRegion } from './copy'\nimport type { Mat3 } from './matrix'\nimport type { VectorPathWindingRule } from './parse-path'\nimport { addOpenSegmentsToPath, addRegionToPath } from './paths/network'\nimport { svgPathSink } from './paths/sink'\nimport type { Vector } from './primitives'\nimport type { Fill, GeometryPath, SceneNode, VectorNetwork, VectorSegment } from './types'\n\n/** Concatenate vector networks while preserving independent geometry. */\nexport function mergeVectorNetworks(networks: readonly VectorNetwork[]): VectorNetwork {\n const vertices: VectorNetwork['vertices'] = []\n const segments: VectorNetwork['segments'] = []\n const regions: VectorNetwork['regions'] = []\n let vertexOffset = 0\n let segmentOffset = 0\n\n for (const network of networks) {\n for (const vertex of network.vertices) vertices.push({ ...vertex })\n for (const segment of network.segments) {\n segments.push({\n ...segment,\n start: segment.start + vertexOffset,\n end: segment.end + vertexOffset,\n tangentStart: { ...segment.tangentStart },\n tangentEnd: { ...segment.tangentEnd }\n })\n }\n for (const region of network.regions) {\n const loops: number[][] = []\n for (const loop of region.loops) {\n const shifted: number[] = []\n for (const segmentIndex of loop) shifted.push(segmentIndex + segmentOffset)\n loops.push(shifted)\n }\n regions.push(copyVectorRegion(region, loops))\n }\n vertexOffset += network.vertices.length\n segmentOffset += network.segments.length\n }\n\n return { vertices, segments, regions }\n}\n\n/**\n * Map a VectorNetwork through an affine matrix: vertices as points,\n * tangents as direction vectors (linear part only, no translation).\n * Returns a deep copy; the input is not mutated.\n */\nexport function transformVectorNetwork(m: Mat3, vn: VectorNetwork): VectorNetwork {\n const mapVector = (v: Vector): Vector => ({\n x: m[0] * v.x + m[1] * v.y,\n y: m[3] * v.x + m[4] * v.y\n })\n return {\n vertices: vn.vertices.map((v) => ({\n ...v,\n x: m[0] * v.x + m[1] * v.y + m[2],\n y: m[3] * v.x + m[4] * v.y + m[5]\n })),\n segments: vn.segments.map((s) => ({\n ...s,\n tangentStart: mapVector(s.tangentStart),\n tangentEnd: mapVector(s.tangentEnd)\n })),\n regions: vn.regions.map((r) => copyVectorRegion(r))\n }\n}\n\n/** Whether any region has paints of its own, which it draws instead of the layer's fills. */\nexport function hasRegionFills(network: VectorNetwork | null): boolean {\n return network?.regions.some((region) => region.fills !== undefined) ?? false\n}\n\n/**\n * Whether fill geometry is the regions' outlines, one each, as a file or an edit writes it. A\n * pasted vector has none, and an import skips empty outlines; their regions draw traced.\n */\nexport function fillGeometryMatchesRegions(\n fillGeometry: readonly GeometryPath[],\n network: VectorNetwork\n): boolean {\n return fillGeometry.length === network.regions.length\n}\n\n/**\n * Whether a vector's regions draw different fills, each its own or else the layer's, which Figma\n * reads as mixed (live-verified: regions with equal fills of their own read the layer's).\n */\nexport function regionFillsDiffer(\n network: VectorNetwork | null,\n layerFills: readonly Fill[]\n): boolean {\n const [first, ...rest] = (network?.regions ?? []).map((region) => region.fills ?? layerFills)\n return rest.some((fills) => !isEqual(fills, first))\n}\n\n/** The network with every region drawing the layer's fills. */\nfunction withoutRegionFills(network: VectorNetwork): VectorNetwork {\n const copy = cloneVectorNetwork(network)\n return {\n ...copy,\n regions: copy.regions.map(({ windingRule, loops }) => ({ windingRule, loops }))\n }\n}\n\n/**\n * What else an edit that sets a vector's fills changes: every region draws them, its own paints\n * and style dropped, as setting fills does in Figma (live-verified). Edit entry points apply it.\n */\nexport function regionFillChanges(\n node: SceneNode,\n changes: Partial<SceneNode>\n): Pick<Partial<SceneNode>, 'vectorNetwork'> {\n const network = node.type === 'VECTOR' ? node.vectorNetwork : null\n if (!('fills' in changes) || 'vectorNetwork' in changes || !network) return {}\n const ownFills = network.regions.some((region) => region.fills || region.fillStyleId)\n return ownFills ? { vectorNetwork: withoutRegionFills(network) } : {}\n}\n\n/** The paints regions carry of their own. */\nexport function regionFills(network: VectorNetwork | null): Fill[] {\n return network?.regions.flatMap((region) => region.fills ?? []) ?? []\n}\n\n/** Structural equality of two VectorNetworks (order-sensitive, exact values). */\nexport function vectorNetworksEqual(a: VectorNetwork, b: VectorNetwork): boolean {\n return (\n isEqual(a.vertices, b.vertices) &&\n isEqual(a.segments, b.segments) &&\n isEqual(a.regions, b.regions)\n )\n}\n\n/**\n * Validate a VectorNetwork structure, returning an array of error messages.\n * Empty array means the network is valid.\n */\nexport function validateVectorNetwork(value: unknown): string[] {\n if (!isRecord(value)) return ['network must be an object']\n if (!Array.isArray(value.vertices)) return ['vertices must be an array']\n if (!Array.isArray(value.segments)) return ['segments must be an array']\n\n const errors: string[] = []\n validateVertices(value.vertices, errors)\n validateSegments(value.segments, value.vertices.length, errors)\n const typedSegments = value.segments.filter(isSegmentRecord)\n if (value.regions !== undefined) {\n if (Array.isArray(value.regions)) {\n validateRegions(\n value.regions,\n value.segments.length,\n typedSegments.length === value.segments.length ? typedSegments : null,\n errors\n )\n } else {\n errors.push('regions must be an array when provided')\n }\n }\n return errors\n}\n\nfunction validateVertices(vertices: unknown[], errors: string[]): void {\n for (let index = 0; index < vertices.length; index++) {\n if (!isFiniteVector(vertices[index])) {\n errors.push(`vertex[${index}]: x and y must be finite numbers`)\n }\n }\n}\n\nfunction validateSegments(segments: unknown[], vertexCount: number, errors: string[]): void {\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index]\n if (!isRecord(segment)) {\n errors.push(`segment[${index}] must be an object`)\n continue\n }\n if (!isInteger(segment.start) || !isInteger(segment.end)) {\n errors.push(`segment[${index}]: start and end must be integers`)\n continue\n }\n if (segment.start < 0 || segment.start >= vertexCount) {\n errors.push(`segment[${index}]: start index ${segment.start} out of range`)\n }\n if (segment.end < 0 || segment.end >= vertexCount) {\n errors.push(`segment[${index}]: end index ${segment.end} out of range`)\n }\n validateSegmentTangents(segment, index, errors)\n }\n}\n\nfunction validateSegmentTangents(\n segment: Record<string, unknown>,\n index: number,\n errors: string[]\n): void {\n for (const tangentKey of ['tangentStart', 'tangentEnd'] as const) {\n const tangent = segment[tangentKey]\n if (tangent !== undefined && !isFiniteVector(tangent)) {\n errors.push(`segment[${index}]: ${tangentKey} must contain finite x and y numbers`)\n }\n }\n}\n\nfunction validateRegions(\n regions: unknown[],\n segmentCount: number,\n segments: Array<Record<'start' | 'end', number>> | null,\n errors: string[]\n): void {\n for (let regionIndex = 0; regionIndex < regions.length; regionIndex++) {\n const region = regions[regionIndex]\n if (!isRecord(region) || !Array.isArray(region.loops)) {\n errors.push(`region[${regionIndex}]: loops must be an array`)\n continue\n }\n if (region.windingRule !== 'NONZERO' && region.windingRule !== 'EVENODD') {\n errors.push(`region[${regionIndex}]: windingRule must be NONZERO or EVENODD`)\n }\n if (region.loops.length === 0) {\n errors.push(`region[${regionIndex}]: loops must contain at least one loop`)\n }\n validateRegionLoops(region.loops, regionIndex, segmentCount, segments, errors)\n }\n}\n\nfunction validateRegionLoops(\n loops: unknown[],\n regionIndex: number,\n segmentCount: number,\n segments: Array<Record<'start' | 'end', number>> | null,\n errors: string[]\n): void {\n for (let loopIndex = 0; loopIndex < loops.length; loopIndex++) {\n const loop = loops[loopIndex]\n if (!Array.isArray(loop)) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] must be an array`)\n continue\n }\n if (loop.length === 0) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] must contain at least one segment`)\n continue\n }\n\n const segmentIndices: number[] = []\n for (const segmentIndex of loop) {\n if (!isInteger(segmentIndex) || segmentIndex < 0 || segmentIndex >= segmentCount) {\n errors.push(\n `region[${regionIndex}].loop[${loopIndex}]: segment index ${String(segmentIndex)} out of range`\n )\n } else {\n segmentIndices.push(segmentIndex)\n }\n }\n if (segmentIndices.length !== loop.length) continue\n if (new Set(segmentIndices).size !== segmentIndices.length) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] must not repeat segments`)\n continue\n }\n if (segments && !formsContinuousChain(segmentIndices, segments)) {\n errors.push(`region[${regionIndex}].loop[${loopIndex}] segments must form a continuous chain`)\n }\n }\n}\n\nfunction formsContinuousChain(\n indices: number[],\n segments: Array<Record<'start' | 'end', number>>\n): boolean {\n if (indices.length <= 1) return true\n const first = segments[indices[0]]\n return followsChain(indices, segments, first.end) || followsChain(indices, segments, first.start)\n}\n\nfunction followsChain(\n indices: number[],\n segments: Array<Record<'start' | 'end', number>>,\n initialEnd: number\n): boolean {\n let current = initialEnd\n for (let index = 1; index < indices.length; index++) {\n const segment = segments[indices[index]]\n if (segment.start === current) current = segment.end\n else if (segment.end === current) current = segment.start\n else return false\n }\n return true\n}\n\nfunction isSegmentRecord(value: unknown): value is Record<'start' | 'end', number> {\n return isRecord(value) && isInteger(value.start) && isInteger(value.end)\n}\n\nfunction isFiniteVector(value: unknown): value is Vector {\n return (\n isRecord(value) &&\n typeof value.x === 'number' &&\n Number.isFinite(value.x) &&\n typeof value.y === 'number' &&\n Number.isFinite(value.y)\n )\n}\n\nfunction isInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value)\n}\n\nexport type NormalizableVectorNetwork = Omit<VectorNetwork, 'regions'> & {\n regions?: VectorNetwork['regions']\n}\n\n/**\n * Ensure every segment has tangentStart/tangentEnd and a regions array.\n * Missing tangents default to {x:0, y:0} (straight line segments).\n * Use at system boundaries where input may come from JSON/MCP.\n */\nexport function normalizeVectorNetwork(vn: NormalizableVectorNetwork): VectorNetwork {\n const ZERO: Vector = { x: 0, y: 0 }\n return {\n vertices: vn.vertices,\n segments: vn.segments.map((s) => ({\n start: s.start,\n end: s.end,\n tangentStart: (s as Partial<VectorSegment>).tangentStart ?? { ...ZERO },\n tangentEnd: (s as Partial<VectorSegment>).tangentEnd ?? { ...ZERO }\n })),\n regions: vn.regions ?? []\n }\n}\n\nfunction coordinate(value: number, decimals: number | null): number {\n if (decimals === null) return value\n const factor = 10 ** decimals\n return Math.round(value * factor) / factor\n}\n\n/** Coordinates written at `decimals`, or as they are for `null`. */\nfunction coordinateFormat(decimals: number | null): (value: number) => number {\n return (value) => coordinate(value, decimals)\n}\n\n/** A network's segments as one open path, chained as the canvas draws them. */\nfunction unfilledSegmentsToPath(network: VectorNetwork, decimals: number | null): string {\n const parts: string[] = []\n addOpenSegmentsToPath(\n svgPathSink(parts, coordinateFormat(decimals)),\n network.segments,\n network.vertices\n )\n return parts.join('')\n}\n\nexport function vectorNetworkToSVGPaths(\n network: VectorNetwork,\n decimals: number | null = 2\n): string[] {\n const { vertices, regions } = network\n\n if (regions.length === 0) {\n const path = unfilledSegmentsToPath(network, decimals)\n return path ? [path] : []\n }\n const paths = regionSVGPaths(network, decimals)\n // Segments no region encloses, such as an icon's open strokes beside its filled shapes,\n // draw as open paths after the regions.\n const open = looseSegments(network)\n const loose =\n open.length > 0 && unfilledSegmentsToPath({ vertices, segments: open, regions: [] }, decimals)\n return loose ? [...paths, loose] : paths\n}\n\n/** Each region of a vector network as path data, its loops traced in turn. */\nexport function regionSVGPaths(network: VectorNetwork, decimals: number | null = 2): string[] {\n const { vertices, segments, regions } = network\n return regions.map((region) => {\n const parts: string[] = []\n addRegionToPath(svgPathSink(parts, coordinateFormat(decimals)), region, segments, vertices)\n return parts.join('')\n })\n}\n\n/** The segments of a vector network that no region encloses. */\nexport function looseSegments({ segments, regions }: VectorNetwork): VectorNetwork['segments'] {\n const enclosed = new Set(regions.flatMap((region) => region.loops.flat()))\n return segments.filter((_, index) => !enclosed.has(index))\n}\n\n/** A path of a vector network as Figma's `vectorPaths` gives it. */\nexport interface VectorPath {\n windingRule: VectorPathWindingRule\n data: string\n}\n\n/**\n * A vector network as Figma's `vectorPaths`: each region as a path with its winding rule, then\n * the segments no region encloses as one open path, at full precision.\n */\nexport function vectorNetworkPaths(network: VectorNetwork): VectorPath[] {\n if (network.segments.length === 0) return []\n const paths: VectorPath[] = regionSVGPaths(network, null).flatMap((data, index) =>\n data ? [{ windingRule: network.regions[index].windingRule, data }] : []\n )\n const open = looseSegments(network)\n if (open.length === 0) return paths\n const data = vectorNetworkToSVGPaths(\n { vertices: network.vertices, segments: open, regions: [] },\n null\n ).join('')\n return data ? [...paths, { windingRule: 'NONE', data }] : paths\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,oBAAoB,UAAmD;CACrF,MAAM,WAAsC,CAAC;CAC7C,MAAM,WAAsC,CAAC;CAC7C,MAAM,UAAoC,CAAC;CAC3C,IAAI,eAAe;CACnB,IAAI,gBAAgB;CAEpB,KAAK,MAAM,WAAW,UAAU;EAC9B,KAAK,MAAM,UAAU,QAAQ,UAAU,SAAS,KAAK,EAAE,GAAG,OAAO,CAAC;EAClE,KAAK,MAAM,WAAW,QAAQ,UAC5B,SAAS,KAAK;GACZ,GAAG;GACH,OAAO,QAAQ,QAAQ;GACvB,KAAK,QAAQ,MAAM;GACnB,cAAc,EAAE,GAAG,QAAQ,aAAa;GACxC,YAAY,EAAE,GAAG,QAAQ,WAAW;EACtC,CAAC;EAEH,KAAK,MAAM,UAAU,QAAQ,SAAS;GACpC,MAAM,QAAoB,CAAC;GAC3B,KAAK,MAAM,QAAQ,OAAO,OAAO;IAC/B,MAAM,UAAoB,CAAC;IAC3B,KAAK,MAAM,gBAAgB,MAAM,QAAQ,KAAK,eAAe,aAAa;IAC1E,MAAM,KAAK,OAAO;GACpB;GACA,QAAQ,KAAK,iBAAiB,QAAQ,KAAK,CAAC;EAC9C;EACA,gBAAgB,QAAQ,SAAS;EACjC,iBAAiB,QAAQ,SAAS;CACpC;CAEA,OAAO;EAAE;EAAU;EAAU;CAAQ;AACvC;;;;;;AAOA,SAAgB,uBAAuB,GAAS,IAAkC;CAChF,MAAM,aAAa,OAAuB;EACxC,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE;EACzB,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE;CAC3B;CACA,OAAO;EACL,UAAU,GAAG,SAAS,KAAK,OAAO;GAChC,GAAG;GACH,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE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,WAA0B,GAAa;CAC5F,MAAM,EAAE,UAAU,UAAU,YAAY;CACxC,OAAO,QAAQ,KAAK,WAAW;EAC7B,MAAM,QAAkB,CAAC;EACzB,gBAAgB,YAAY,OAAO,iBAAiB,QAAQ,CAAC,GAAG,QAAQ,UAAU,QAAQ;EAC1F,OAAO,MAAM,KAAK,EAAE;CACtB,CAAC;AACH;;AAGA,SAAgB,cAAc,EAAE,UAAU,WAAqD;CAC7F,MAAM,WAAW,IAAI,IAAI,QAAQ,SAAS,WAAW,OAAO,MAAM,KAAK,CAAC,CAAC;CACzE,OAAO,SAAS,QAAQ,GAAG,UAAU,CAAC,SAAS,IAAI,KAAK,CAAC;AAC3D;;;;;AAYA,SAAgB,mBAAmB,SAAsC;CACvE,IAAI,QAAQ,SAAS,WAAW,GAAG,OAAO,CAAC;CAC3C,MAAM,QAAsB,eAAe,SAAS,IAAI,CAAC,CAAC,SAAS,MAAM,UACvE,OAAO,CAAC;EAAE,aAAa,QAAQ,QAAQ,MAAM,CAAC;EAAa;CAAK,CAAC,IAAI,CAAC,CACxE;CACA,MAAM,OAAO,cAAc,OAAO;CAClC,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,MAAM,OAAO,wBACX;EAAE,UAAU,QAAQ;EAAU,UAAU;EAAM,SAAS,CAAC;CAAE,GAC1D,IACF,CAAC,CAAC,KAAK,EAAE;CACT,OAAO,OAAO,CAAC,GAAG,OAAO;EAAE,aAAa;EAAQ;CAAK,CAAC,IAAI;AAC5D"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-pencil/scene-graph",
|
|
3
|
-
"version": "0.17.0-beta.
|
|
3
|
+
"version": "0.17.0-beta.6",
|
|
4
4
|
"license": "MIT",
|
|
5
|
+
"funding": "https://ko-fi.com/dannote",
|
|
5
6
|
"files": [
|
|
6
7
|
"dist",
|
|
7
8
|
"src",
|
|
@@ -11,6 +12,7 @@
|
|
|
11
12
|
"types": "./dist/index.d.ts",
|
|
12
13
|
"dependencies": {
|
|
13
14
|
"@noble/hashes": "^2.4.0",
|
|
15
|
+
"@open-pencil/std": "^0.17.0-beta.6",
|
|
14
16
|
"culori": "^4.0.2",
|
|
15
17
|
"es-toolkit": "^1.52.0",
|
|
16
18
|
"image-size": "^2.0.4",
|
|
@@ -18,6 +20,7 @@
|
|
|
18
20
|
"nanoevents": "^9.1.0",
|
|
19
21
|
"postcss-value-parser": "^4.2.0",
|
|
20
22
|
"svgpath": "^2.6.0",
|
|
23
|
+
"ufo": "^1.6.4",
|
|
21
24
|
"valibot": "^1.5.0"
|
|
22
25
|
},
|
|
23
26
|
"exports": {
|
|
@@ -27,12 +30,6 @@
|
|
|
27
30
|
"import": "./dist/index.js",
|
|
28
31
|
"default": "./dist/index.js"
|
|
29
32
|
},
|
|
30
|
-
"./arrays": {
|
|
31
|
-
"types": "./dist/arrays.d.ts",
|
|
32
|
-
"bun": "./src/arrays.ts",
|
|
33
|
-
"import": "./dist/arrays.js",
|
|
34
|
-
"default": "./dist/arrays.js"
|
|
35
|
-
},
|
|
36
33
|
"./arrow-caps": {
|
|
37
34
|
"types": "./dist/arrow-caps.d.ts",
|
|
38
35
|
"bun": "./src/arrow-caps.ts",
|
|
@@ -303,12 +300,6 @@
|
|
|
303
300
|
"import": "./dist/primitives/index.js",
|
|
304
301
|
"default": "./dist/primitives/index.js"
|
|
305
302
|
},
|
|
306
|
-
"./random": {
|
|
307
|
-
"types": "./dist/random.d.ts",
|
|
308
|
-
"bun": "./src/random.ts",
|
|
309
|
-
"import": "./dist/random.js",
|
|
310
|
-
"default": "./dist/random.js"
|
|
311
|
-
},
|
|
312
303
|
"./resize": {
|
|
313
304
|
"types": "./dist/resize.d.ts",
|
|
314
305
|
"bun": "./src/resize.ts",
|
|
@@ -363,6 +354,12 @@
|
|
|
363
354
|
"import": "./dist/statuses/index.js",
|
|
364
355
|
"default": "./dist/statuses/index.js"
|
|
365
356
|
},
|
|
357
|
+
"./strokes": {
|
|
358
|
+
"types": "./dist/strokes.d.ts",
|
|
359
|
+
"bun": "./src/strokes.ts",
|
|
360
|
+
"import": "./dist/strokes.js",
|
|
361
|
+
"default": "./dist/strokes.js"
|
|
362
|
+
},
|
|
366
363
|
"./text": {
|
|
367
364
|
"types": "./dist/text/index.d.ts",
|
|
368
365
|
"bun": "./src/text/index.ts",
|
package/src/comments/schema.ts
CHANGED
|
@@ -13,6 +13,7 @@ const commentAuthorColorSchema = v.fallback(
|
|
|
13
13
|
const commentEntry = {
|
|
14
14
|
author: v.fallback(v.string(), ''),
|
|
15
15
|
authorColor: commentAuthorColorSchema,
|
|
16
|
+
agent: v.fallback(v.optional(v.string()), undefined),
|
|
16
17
|
text: v.fallback(v.string(), ''),
|
|
17
18
|
createdAt: v.fallback(v.string(), ''),
|
|
18
19
|
deleted: v.optional(v.boolean())
|
package/src/comments/threads.ts
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
import type { SceneGraph } from '../graph'
|
|
2
2
|
import type { Color, Vector } from '../primitives'
|
|
3
|
-
import { randomHex } from '../random'
|
|
4
3
|
import type { CommentReply, CommentThread, SceneNode } from '../types'
|
|
5
4
|
|
|
6
5
|
/** Who writes a comment: their name and, in a collaboration room, their color. */
|
|
7
6
|
export interface CommentAuthor {
|
|
8
7
|
name: string
|
|
9
8
|
color?: Color
|
|
9
|
+
/** The agent writing, when one writes rather than the person. */
|
|
10
|
+
agent?: string
|
|
10
11
|
}
|
|
11
12
|
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* A new thread's or reply's ID: a UUID, so a server that keeps comments, as Cloud does, takes the
|
|
15
|
+
* ID the editor chose and a retried request finds the comment it already made. Files from older
|
|
16
|
+
* versions keep their own IDs.
|
|
17
|
+
*/
|
|
18
|
+
function newCommentId(): string {
|
|
19
|
+
return crypto.randomUUID()
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
/** When a comment is written or changed, as stored: an ISO timestamp. */
|
|
@@ -94,12 +100,13 @@ export function createCommentThread(
|
|
|
94
100
|
): CommentThread {
|
|
95
101
|
const { pageId, at, node, author, text, now } = options
|
|
96
102
|
return {
|
|
97
|
-
id: newCommentId(
|
|
103
|
+
id: newCommentId(),
|
|
98
104
|
pageId,
|
|
99
105
|
pageName: graph.getNode(pageId)?.name,
|
|
100
106
|
...commentAnchor(graph, pageId, at, node),
|
|
101
107
|
author: author.name,
|
|
102
108
|
authorColor: author.color,
|
|
109
|
+
...(author.agent ? { agent: author.agent } : {}),
|
|
103
110
|
text,
|
|
104
111
|
createdAt: now,
|
|
105
112
|
updatedAt: now,
|
|
@@ -110,9 +117,10 @@ export function createCommentThread(
|
|
|
110
117
|
|
|
111
118
|
export function createCommentReply(author: CommentAuthor, text: string, now: string): CommentReply {
|
|
112
119
|
return {
|
|
113
|
-
id: newCommentId(
|
|
120
|
+
id: newCommentId(),
|
|
114
121
|
author: author.name,
|
|
115
122
|
authorColor: author.color,
|
|
123
|
+
...(author.agent ? { agent: author.agent } : {}),
|
|
116
124
|
text,
|
|
117
125
|
createdAt: now
|
|
118
126
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { randomHex } from '@open-pencil/std/random'
|
|
2
|
+
|
|
1
3
|
import type { SceneGraph } from '../graph'
|
|
2
4
|
import { findInstanceAncestor, instanceMainComponent } from '../instances/main-component'
|
|
3
5
|
import { assignmentOverrideField, setInstanceOverride } from '../instances/overrides'
|
|
4
6
|
import { walkInstanceSources } from '../instances/source-walk'
|
|
5
|
-
import { randomHex } from '../random'
|
|
6
7
|
import type {
|
|
7
8
|
ComponentPropertyDefinition,
|
|
8
9
|
ComponentPropertyReferenceField,
|