@open-pencil/scene-graph 0.16.0-beta.1 → 0.16.0-beta.3
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/chunks/asset-keys.js +27 -0
- package/dist/chunks/asset-keys.js.map +1 -0
- package/dist/chunks/behaviours/layers.js +16 -1
- package/dist/chunks/behaviours/layers.js.map +1 -1
- package/dist/chunks/color/contrast.js +23 -1
- package/dist/chunks/color/contrast.js.map +1 -1
- package/dist/chunks/color/index.js +43 -4
- package/dist/chunks/color/index.js.map +1 -1
- package/dist/chunks/components/exposure.js +273 -3
- package/dist/chunks/components/exposure.js.map +1 -1
- package/dist/chunks/index.js +247 -150
- package/dist/chunks/index.js.map +1 -1
- package/dist/color.d.ts +7 -1
- package/dist/color.d.ts.map +1 -1
- package/dist/color.js +2 -2
- package/dist/geometry.d.ts +2 -2
- package/dist/hit-test.js +24 -18
- package/dist/hit-test.js.map +1 -1
- package/dist/images.d.ts +2 -2
- package/dist/images.js +21 -38
- package/dist/images.js.map +1 -1
- package/dist/images2.d.ts +12 -1
- package/dist/images2.d.ts.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +6 -6
- package/dist/layout.d.ts +2 -2
- package/dist/layout.js +3 -3
- package/dist/text.d.ts +2 -2
- package/dist/text.js +2 -2
- package/dist/types.d.ts +129 -12
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -2
- package/dist/types2.d.ts +2 -2
- package/package.json +2 -1
- package/src/asset-keys.ts +25 -0
- package/src/color/contrast.ts +28 -0
- package/src/copy.ts +4 -1
- package/src/geometry.ts +64 -14
- package/src/hit-test.ts +45 -23
- package/src/images.ts +24 -32
- package/src/index.ts +8 -4
- package/src/instances/content-size.ts +63 -0
- package/src/instances/fields.ts +1 -1
- package/src/instances/sync.ts +7 -6
- package/src/instances/vector-geometry.ts +81 -0
- package/src/instances.ts +3 -0
- package/src/layout/guides.ts +40 -11
- package/src/shaders/model.ts +4 -2
- package/src/shaders/still.ts +41 -0
- package/src/shared-styles.ts +5 -2
- package/src/text/index.ts +1 -0
- package/src/text/references.ts +50 -0
- package/src/transfer/nodes.ts +12 -0
- package/src/transfer/plan.ts +25 -2
- package/src/transfer/validation.ts +6 -1
- package/src/types.ts +50 -2
- package/src/variables/bindings.ts +110 -8
- package/dist/chunks/fields/text.js +0 -36
- package/dist/chunks/fields/text.js.map +0 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { sha1 } from "@noble/hashes/legacy.js";
|
|
2
|
+
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
3
|
+
//#region src/asset-keys.ts
|
|
4
|
+
/**
|
|
5
|
+
* A key shaped as Figma's asset keys, 40 hex digits, derived from `seed` so the same seed always
|
|
6
|
+
* gives the same key. The Figma clipboard names variables and collections by key; one made in
|
|
7
|
+
* OpenPencil has none, so copying it gives it this one, and copying it again gives the same.
|
|
8
|
+
*/
|
|
9
|
+
function derivedAssetKey(seed) {
|
|
10
|
+
return bytesToHex(sha1(utf8ToBytes(seed)));
|
|
11
|
+
}
|
|
12
|
+
/** Largest part of a Figma GUID, which Figma reads as a signed 32-bit integer. */
|
|
13
|
+
const MAX_GUID_PART = 2147483647;
|
|
14
|
+
/**
|
|
15
|
+
* A version shaped as Figma's asset versions, `session:local`, derived from `content` so that
|
|
16
|
+
* copying an unchanged asset again gives the same version and copying a changed one gives another.
|
|
17
|
+
* Figma keeps the first value it pasted for a key and version, so a version that stayed the same
|
|
18
|
+
* across an edit would bring the old value back.
|
|
19
|
+
*/
|
|
20
|
+
function derivedAssetVersion(content) {
|
|
21
|
+
const view = new DataView(sha1(utf8ToBytes(content)).buffer);
|
|
22
|
+
return `${view.getUint32(0) & MAX_GUID_PART}:${view.getUint32(4) & MAX_GUID_PART}`;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
export { derivedAssetKey, derivedAssetVersion };
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=asset-keys.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"asset-keys.js","names":[],"sources":["../../src/asset-keys.ts"],"sourcesContent":["import { sha1 } from '@noble/hashes/legacy.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\n\n/**\n * A key shaped as Figma's asset keys, 40 hex digits, derived from `seed` so the same seed always\n * gives the same key. The Figma clipboard names variables and collections by key; one made in\n * OpenPencil has none, so copying it gives it this one, and copying it again gives the same.\n */\nexport function derivedAssetKey(seed: string): string {\n return bytesToHex(sha1(utf8ToBytes(seed)))\n}\n\n/** Largest part of a Figma GUID, which Figma reads as a signed 32-bit integer. */\nconst MAX_GUID_PART = 0x7fffffff\n\n/**\n * A version shaped as Figma's asset versions, `session:local`, derived from `content` so that\n * copying an unchanged asset again gives the same version and copying a changed one gives another.\n * Figma keeps the first value it pasted for a key and version, so a version that stayed the same\n * across an edit would bring the old value back.\n */\nexport function derivedAssetVersion(content: string): string {\n const view = new DataView(sha1(utf8ToBytes(content)).buffer)\n return `${view.getUint32(0) & MAX_GUID_PART}:${view.getUint32(4) & MAX_GUID_PART}`\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,WAAW,KAAK,YAAY,IAAI,CAAC,CAAC;AAC3C;;AAGA,MAAM,gBAAgB;;;;;;;AAQtB,SAAgB,oBAAoB,SAAyB;CAC3D,MAAM,OAAO,IAAI,SAAS,KAAK,YAAY,OAAO,CAAC,CAAC,CAAC,MAAM;CAC3D,OAAO,GAAG,KAAK,UAAU,CAAC,IAAI,cAAc,GAAG,KAAK,UAAU,CAAC,IAAI;AACrE"}
|
|
@@ -189,6 +189,17 @@ const shaderPaintSchema = v.object({
|
|
|
189
189
|
});
|
|
190
190
|
//#endregion
|
|
191
191
|
//#region src/types.ts
|
|
192
|
+
/** The text fields a range of characters can bind to a variable, as Figma lists them. */
|
|
193
|
+
const TEXT_BINDABLE_FIELDS = [
|
|
194
|
+
"fontFamily",
|
|
195
|
+
"fontSize",
|
|
196
|
+
"fontStyle",
|
|
197
|
+
"fontWeight",
|
|
198
|
+
"letterSpacing",
|
|
199
|
+
"lineHeight",
|
|
200
|
+
"paragraphSpacing",
|
|
201
|
+
"paragraphIndent"
|
|
202
|
+
];
|
|
192
203
|
/** Property pickers a variable is offered in, as Figma names them. */
|
|
193
204
|
const VARIABLE_SCOPES = [
|
|
194
205
|
"ALL_SCOPES",
|
|
@@ -233,6 +244,10 @@ const TOKEN_UNITS = [
|
|
|
233
244
|
"s",
|
|
234
245
|
"deg"
|
|
235
246
|
];
|
|
247
|
+
/** Whether a collection is a library's copy, which takes no variables or modes of the file's. */
|
|
248
|
+
function isLibraryCollection(collection) {
|
|
249
|
+
return !!collection.key;
|
|
250
|
+
}
|
|
236
251
|
/** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */
|
|
237
252
|
const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\w-]*$/;
|
|
238
253
|
function isModeAttributeName(name) {
|
|
@@ -591,6 +606,6 @@ function findLayerByPath(graph, rootId, path) {
|
|
|
591
606
|
return current;
|
|
592
607
|
}
|
|
593
608
|
//#endregion
|
|
594
|
-
export { CODE_SYNTAX_PLATFORMS, DEFAULT_NUMBER_SETTINGS, EXPORT_FORMAT_IDS, ICON_NAME, ICON_PAINTS, MAX_EXPORT_SCALE, MIN_EXPORT_SCALE, MODE_ATTRIBUTE_PATTERN, OPEN_PENCIL_PLUGIN_DATA, OPEN_PENCIL_PLUGIN_ID, TOKEN_UNITS, VARIABLE_SCOPES, behaviourOwner, behaviourProperties, booleanBinding, clampExportScale, contentPluginData, emptyBehaviour, findLayerByPath, guessInteractionStates, hasBehaviour, hasPluginData, iconSchema, iconTintSchema, interactionStateValues, isExportFormatId, isModeAttributeName, isNumberRange, isPluginDataEntry, isValidExportScale, jsonPluginDataField, layerPath, missingBindings, numberSettings, partBinding, pluginDataEntry, readAllPluginData, readBehaviour, readPluginData, renameBehaviourProperties, shaderPaintSchema, shaderPresetSchema, textBinding, textPluginDataField, withAllPluginData, withBehaviour, withPluginData, withoutPluginData };
|
|
609
|
+
export { CODE_SYNTAX_PLATFORMS, DEFAULT_NUMBER_SETTINGS, EXPORT_FORMAT_IDS, ICON_NAME, ICON_PAINTS, MAX_EXPORT_SCALE, MIN_EXPORT_SCALE, MODE_ATTRIBUTE_PATTERN, OPEN_PENCIL_PLUGIN_DATA, OPEN_PENCIL_PLUGIN_ID, TEXT_BINDABLE_FIELDS, TOKEN_UNITS, VARIABLE_SCOPES, behaviourOwner, behaviourProperties, booleanBinding, clampExportScale, contentPluginData, emptyBehaviour, findLayerByPath, guessInteractionStates, hasBehaviour, hasPluginData, iconSchema, iconTintSchema, interactionStateValues, isExportFormatId, isLibraryCollection, isModeAttributeName, isNumberRange, isPluginDataEntry, isValidExportScale, jsonPluginDataField, layerPath, missingBindings, numberSettings, partBinding, pluginDataEntry, readAllPluginData, readBehaviour, readPluginData, renameBehaviourProperties, shaderPaintSchema, shaderPresetSchema, textBinding, textPluginDataField, withAllPluginData, withBehaviour, withPluginData, withoutPluginData };
|
|
595
610
|
|
|
596
611
|
//# sourceMappingURL=layers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layers.js","names":[],"sources":["../../../src/plugin-data/field.ts","../../../src/behaviours/schema.ts","../../../src/export-format.ts","../../../src/export-scale.ts","../../../src/icons/schema.ts","../../../src/shaders/schema.ts","../../../src/types.ts","../../../src/plugin-data/fields.ts","../../../src/behaviours/model.ts","../../../src/behaviours/layers.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { PluginDataEntry } from '../types'\n\n/** The plugin id OpenPencil keeps its own state under, on nodes and in `.fig` files. */\nexport const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'\n\n/**\n * What a field holds:\n * - `content` belongs to the node like its fills do and exists only as plugin data, so it\n * travels with a component copied into a library or another document;\n * - `format` repeats a node or variable field for files that have no slot for it, where the\n * node field is what counts;\n * - `bookkeeping` records where a node or document came from and stays behind.\n */\nexport type PluginDataRole = 'content' | 'format' | 'bookkeeping'\n\n/** One OpenPencil plugin-data key. */\nexport interface PluginDataKey {\n readonly key: string\n readonly role: PluginDataRole\n}\n\n/** A plugin-data key and how its string value is read and written. */\nexport interface PluginDataField<T> extends PluginDataKey {\n /** The stored value, or `undefined` when it is missing or not a valid value. */\n decode(value: string | null | undefined): T | undefined\n encode(value: T): string\n}\n\n/**\n * A value stored as JSON. Invalid JSON and a wrong shape both read as missing: plugin data\n * comes from files anyone can edit, so a bad entry is ignored rather than thrown on.\n */\nexport function jsonPluginDataField<T>(\n key: string,\n role: PluginDataRole,\n schema: v.GenericSchema<unknown, T>\n): PluginDataField<T> {\n const stored = v.pipe(v.string(), v.parseJson(), schema)\n return {\n key,\n role,\n decode(value) {\n const parsed = v.safeParse(stored, value)\n return parsed.success ? parsed.output : undefined\n },\n encode: (value) => JSON.stringify(value)\n }\n}\n\n/** A value stored as one of a fixed set of plain strings. */\nexport function textPluginDataField<const T extends string>(\n key: string,\n role: PluginDataRole,\n values: readonly T[]\n): PluginDataField<T> {\n const schema = v.picklist(values)\n return {\n key,\n role,\n decode(value) {\n const parsed = v.safeParse(schema, value)\n return parsed.success ? parsed.output : undefined\n },\n encode: (value) => value\n }\n}\n\nexport function isPluginDataEntry(entry: PluginDataEntry, field: PluginDataKey): boolean {\n return entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === field.key\n}\n\nexport function hasPluginData(\n entries: readonly PluginDataEntry[] | undefined,\n field: PluginDataKey\n): boolean {\n return entries?.some((entry) => isPluginDataEntry(entry, field)) ?? false\n}\n\nexport function readPluginData<T>(\n entries: readonly PluginDataEntry[] | undefined,\n field: PluginDataField<T>\n): T | undefined {\n return field.decode(entries?.find((entry) => isPluginDataEntry(entry, field))?.value)\n}\n\n/** Every valid value of a field kept as several entries under one key. */\nexport function readAllPluginData<T>(\n entries: readonly PluginDataEntry[] | undefined,\n field: PluginDataField<T>\n): T[] {\n return (entries ?? []).flatMap((entry) => {\n if (!isPluginDataEntry(entry, field)) return []\n const value = field.decode(entry.value)\n return value === undefined ? [] : [value]\n })\n}\n\nexport function pluginDataEntry<T>(field: PluginDataField<T>, value: T): PluginDataEntry {\n return { pluginId: OPEN_PENCIL_PLUGIN_ID, key: field.key, value: field.encode(value) }\n}\n\n/** Entries other than those of `fields`; other plugins' entries are always kept. */\nexport function withoutPluginData(\n entries: readonly PluginDataEntry[],\n fields: readonly PluginDataKey[]\n): PluginDataEntry[] {\n return entries.filter((entry) => !fields.some((field) => isPluginDataEntry(entry, field)))\n}\n\n/** Entries with `field` set to `value`, appended last; `undefined` removes the field. */\nexport function withPluginData<T>(\n entries: readonly PluginDataEntry[],\n field: PluginDataField<T>,\n value: T | undefined\n): PluginDataEntry[] {\n return withAllPluginData(entries, field, value === undefined ? [] : [value])\n}\n\n/** Entries with every entry of `field` replaced by one per value. */\nexport function withAllPluginData<T>(\n entries: readonly PluginDataEntry[],\n field: PluginDataField<T>,\n values: readonly T[]\n): PluginDataEntry[] {\n return [\n ...withoutPluginData(entries, [field]),\n ...values.map((value) => pluginDataEntry(field, value))\n ]\n}\n","import * as v from 'valibot'\n\nimport { BEHAVIOUR_KINDS, type InteractionState } from './kinds'\n\nconst BooleanBinding = v.object({\n propertyId: v.string(),\n /** For a variant property: the values that mean on and off. */\n on: v.optional(v.string()),\n off: v.optional(v.string())\n})\n\n/** Whether a number value's range can be stepped through: `max` above `min`, a positive step. */\nexport function isNumberRange(settings: { min: number; max: number; step: number }): boolean {\n return settings.max > settings.min && settings.step > 0\n}\n\nconst NumberSettings = v.pipe(\n v.object({\n min: v.pipe(v.number(), v.finite()),\n max: v.pipe(v.number(), v.finite()),\n step: v.pipe(v.number(), v.finite()),\n default: v.pipe(v.number(), v.finite())\n }),\n v.check(\n (settings) => isNumberRange(settings),\n 'A number value needs max above min and a positive step'\n )\n)\n\n/** Each interaction state's variant value, by state; a state left out shows the rest value. */\nexport const interactionStateValues = {\n rest: v.optional(v.string()),\n hover: v.optional(v.string()),\n pressed: v.optional(v.string()),\n focus: v.optional(v.string()),\n disabled: v.optional(v.string())\n} satisfies Record<InteractionState, unknown>\n\nconst InteractionStates = v.object({ propertyId: v.string(), ...interactionStateValues })\n\nexport const behaviourSchema = v.object({\n kind: v.picklist(BEHAVIOUR_KINDS),\n /** Boolean values, by value id, bound to component properties. */\n booleans: v.record(v.string(), BooleanBinding),\n /** Text values, by value id, bound to text properties. */\n texts: v.optional(v.record(v.string(), v.object({ propertyId: v.string() })), {}),\n /** Number values, by value id: the range the behaviour keeps itself. */\n numbers: v.record(v.string(), NumberSettings),\n /** Parts, by part id, bound to slot properties. */\n parts: v.record(v.string(), v.string()),\n states: v.optional(InteractionStates)\n})\n\n/** How a main component behaves as a control, as kept in its plugin data. */\nexport type Behaviour = v.InferOutput<typeof behaviourSchema>\nexport type BehaviourBooleanBinding = v.InferOutput<typeof BooleanBinding>\nexport type BehaviourNumberSettings = v.InferOutput<typeof NumberSettings>\nexport type BehaviourInteractionStates = v.InferOutput<typeof InteractionStates>\n","/**\n * Formats a node's export settings may persist. Each id must name a Core IO\n * export adapter that supports node export; labels and options come from that\n * adapter, so this list only decides what the Export panel offers.\n */\nexport const EXPORT_FORMAT_IDS = ['png', 'jpg', 'webp', 'svg', 'pdf', 'pptx'] as const\n\nexport type ExportFormatId = (typeof EXPORT_FORMAT_IDS)[number]\n\nexport function isExportFormatId(value: unknown): value is ExportFormatId {\n return EXPORT_FORMAT_IDS.some((id) => id === value)\n}\n","/**\n * Bounds for export scale multipliers. A huge multiplier would allocate an\n * enormous canvas and crash the renderer, so clamp at every boundary the value\n * can enter from: the UI (edits) and the file format (imported/plugin .fig data).\n */\nexport const MIN_EXPORT_SCALE = 0.01\nexport const MAX_EXPORT_SCALE = 1024\n\nexport function clampExportScale(scale: number): number {\n return Math.min(MAX_EXPORT_SCALE, Math.max(MIN_EXPORT_SCALE, scale))\n}\n\n/** Accept a scale only if it is finite and within bounds (no silent clamping). */\nexport function isValidExportScale(scale: number): boolean {\n return Number.isFinite(scale) && scale >= MIN_EXPORT_SCALE && scale <= MAX_EXPORT_SCALE\n}\n","import * as v from 'valibot'\n\n/** An icon's name in its set, `prefix:name`, as Iconify names icons. */\nexport const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_][a-z0-9]+)*$/\n\nexport const iconSchema = v.object({\n name: v.pipe(v.string(), v.regex(ICON_NAME)),\n /** A fingerprint of the glyph as placed, to tell when its paths were edited; see `iconGlyph`. */\n glyph: v.optional(v.string())\n})\n\n/** An icon a frame draws. */\nexport type Icon = v.InferOutput<typeof iconSchema>\n\nexport const ICON_PAINTS = ['fill', 'stroke'] as const\nexport type IconPaint = (typeof ICON_PAINTS)[number]\n\nexport const iconTintSchema = v.pipe(v.array(v.picklist(ICON_PAINTS)), v.minLength(1))\n","import * as v from 'valibot'\n\n/** One effect of a shader preset, as the `shaders` library names it, with the effects it holds. */\nexport interface ShaderComponent {\n type: string\n id?: string\n props?: Record<string, unknown>\n children?: ShaderComponent[]\n}\n\nconst shaderComponent: v.GenericSchema<unknown, ShaderComponent> = v.object({\n type: v.pipe(v.string(), v.nonEmpty(), v.maxLength(100)),\n id: v.optional(v.string()),\n props: v.optional(v.record(v.string(), v.unknown())),\n children: v.optional(v.array(v.lazy(() => shaderComponent)))\n})\n\n/**\n * A shader as the `shaders` library describes it and shaders.com exports it: a tree of effects,\n * drawn first to last.\n */\nexport const shaderPresetSchema = v.object({\n components: v.pipe(v.array(shaderComponent), v.minLength(1)),\n structureVersion: v.optional(v.number())\n})\n\nexport type ShaderPreset = v.InferOutput<typeof shaderPresetSchema>\n\n/**\n * A paint that draws a shader. The paint itself is an image fill of the shader's still frame, so\n * every format and renderer that reads images shows it; this entry says which image it is, the\n * preset that draws it, and the layer size and preset the frame was rendered for, which is\n * missing until it is first rendered.\n */\nexport const shaderPaintSchema = v.object({\n image: v.pipe(v.string(), v.nonEmpty()),\n preset: shaderPresetSchema,\n frame: v.optional(\n v.object({\n width: v.pipe(v.number(), v.finite(), v.minValue(0)),\n height: v.pipe(v.number(), v.finite(), v.minValue(0)),\n /** The preset's key (`shaderPresetKey`) when the frame was rendered. */\n preset: v.pipe(v.string(), v.nonEmpty())\n })\n )\n})\n\nexport type ShaderPaint = v.InferOutput<typeof shaderPaintSchema>\n","/* 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 './instance-overrides'\nimport type { Color, Matrix, Rect, Vector } from './primitives'\n\nexport interface SceneGraphEvents {\n 'node:created': (node: SceneNode) => void\n 'node:updated': (id: string, changes: Partial<SceneNode>) => void\n 'node:previewUpdated': (id: string, changes: Partial<SceneNode>) => void\n 'node:deleted': (id: string, parentId: string | null) => void\n 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void\n 'node:reordered': (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}\n\nexport type SceneGraphEventHandlers = Partial<{\n created: (node: SceneNode) => void\n updated: (id: string, changes: Partial<SceneNode>) => void\n previewUpdated: (id: string, changes: Partial<SceneNode>) => void\n deleted: (id: string, parentId: string | null) => void\n reparented: (nodeId: string, oldParentId: string | null, newParentId: string) => void\n reordered: (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}>\n\n/** Hears about nodes as an edit adds and changes them, synchronously and before each change. */\nexport interface NodeChangeObserver {\n /** A node is about to change and is still as it was. */\n before: (node: SceneNode) => void\n /** A node was just added. */\n created: (node: SceneNode) => void\n}\n\nexport type DocumentColorSpace = 'srgb' | 'display-p3'\n\nexport interface FigmaSourcePayload {\n rawSize: Vector | null\n rawTransform: Matrix | null\n rawNodeFields: Record<string, unknown>\n layout: FigmaLayoutMetadata | null\n symbolOverrides: unknown[]\n componentPropAssignments: unknown[]\n derivedSymbolData: unknown[]\n derivedSymbolDataLayoutVersion: number | null\n uniformScaleFactor: number | null\n}\n\nexport interface SourceMetadata {\n format: 'fig' | null\n id: string | null\n orderKey: string | null\n editedFields: string[]\n fig: FigmaSourcePayload\n}\n\nexport type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'\nexport type WindingRule = 'NONZERO' | 'EVENODD'\n\nexport interface VectorVertex {\n x: number\n y: number\n strokeCap?: string\n strokeJoin?: string\n cornerRadius?: number\n handleMirroring?: HandleMirroring\n}\n\nexport interface VectorSegment {\n start: number\n end: number\n tangentStart: Vector\n tangentEnd: Vector\n}\n\nexport interface VectorRegion {\n windingRule: WindingRule\n loops: number[][]\n}\n\nexport interface VectorNetwork {\n vertices: VectorVertex[]\n segments: VectorSegment[]\n regions: VectorRegion[]\n}\n\nexport interface GeometryPath {\n windingRule: WindingRule\n commandsBlob: Uint8Array\n /** Resolved paints for geometry using a format-specific style override. */\n fills?: Fill[]\n /** Shared fill style attached to this geometry region, when available. */\n fillStyleId?: string\n}\n\nexport type NodeType =\n | 'CANVAS'\n | 'FRAME'\n | 'RECTANGLE'\n | 'ROUNDED_RECTANGLE'\n | 'ELLIPSE'\n | 'TEXT'\n | 'LINE'\n | 'STAR'\n | 'POLYGON'\n | 'VECTOR'\n | 'BOOLEAN_OPERATION'\n | 'GROUP'\n | 'SECTION'\n | 'COMPONENT'\n | 'COMPONENT_SET'\n | 'INSTANCE'\n | 'CONNECTOR'\n | 'SHAPE_WITH_TEXT'\n\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 | 'COLOR_BURN'\n | 'LIGHTEN'\n | 'SCREEN'\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 imageHash?: string\n imageScaleMode?: ImageScaleMode\n imageTransform?: GradientTransform\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 = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'\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 pattern?: 'COLUMNS' | 'ROWS' | 'GRID'\n axis?: 'X' | 'Y'\n type?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n alignment?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n numSections?: number\n count?: number\n offset?: number\n sectionSize?: number\n gutterSize?: number\n}\n\nexport interface SharedStyle {\n id: string\n nodeId: string\n name: string\n type: SharedStyleType\n}\n\n/** A stroke is a paint with the geometry that decides where it is drawn. */\nexport interface Stroke extends Fill {\n weight: number\n align: 'INSIDE' | 'CENTER' | 'OUTSIDE'\n cap?: StrokeCap\n join?: StrokeJoin\n dashPattern?: number[]\n}\n\nexport interface Effect {\n type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'\n color: Color\n offset: Vector\n radius: number\n spread: number\n visible: boolean\n blendMode?: BlendMode\n showShadowBehindNode?: boolean\n}\n\nexport type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'\nexport type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'\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\nexport interface CharacterStyleOverride {\n fontWeight?: number\n italic?: boolean\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?: number\n lineHeight?: number | null\n fills?: Fill[]\n fontVariations?: FontVariation[]\n fontFeatures?: FontFeature[]\n textLanguage?: string | null\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\nexport interface ExportSetting {\n scale: number\n format: ExportFormatId\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 tValue: number\n forward: boolean\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\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 Yoga layout pass. */\n derivedLayout: Partial<Rect> | null\n\n fills: Fill[]\n strokes: Stroke[]\n effects: Effect[]\n layoutGrids: LayoutGrid[]\n guides: CanvasGuide[]\n fillStyleId: string | null\n strokeStyleId: string | null\n textStyleId: string | null\n effectStyleId: string | null\n gridStyleId: string | null\n sharedStyleType: SharedStyleType | null\n opacity: number\n\n cornerRadius: number\n topLeftRadius: number\n topRightRadius: number\n bottomRightRadius: number\n bottomLeftRadius: number\n independentCorners: boolean\n cornerSmoothing: number\n\n visible: boolean\n locked: boolean\n clipsContent: boolean\n\n blendMode: BlendMode\n\n text: string\n fontSize: number\n fontFamily: string\n fontWeight: number\n italic: boolean\n 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 lineHeight: number | null\n letterSpacing: number\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 fontFeatures: FontFeature[]\n\n horizontalConstraint: ConstraintType\n verticalConstraint: ConstraintType\n\n layoutMode: LayoutMode\n layoutDirection: LayoutDirection\n layoutWrap: LayoutWrap\n primaryAxisAlign: LayoutAlign\n counterAxisAlign: LayoutCounterAlign\n primaryAxisSizing: AxisSizingMode\n counterAxisSizing: AxisSizingMode\n itemSpacing: number\n counterAxisSpacing: number\n paddingTop: number\n paddingRight: number\n paddingBottom: number\n paddingLeft: number\n\n layoutPositioning: 'AUTO' | 'ABSOLUTE'\n layoutGrow: number\n layoutAlignSelf: LayoutAlignSelf\n\n vectorNetwork: VectorNetwork | null\n handleMirroring: HandleMirroring\n booleanOperation: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE' | undefined\n fillGeometry: GeometryPath[]\n strokeGeometry: GeometryPath[]\n\n arcData: ArcData | null\n\n strokeCap: StrokeCap\n strokeJoin: StrokeJoin\n dashPattern: number[]\n\n borderTopWeight: number\n borderRightWeight: number\n borderBottomWeight: number\n borderLeftWeight: number\n independentStrokeWeights: boolean\n\n /**\n * The weight and alignment a node keeps for its strokes, as Figma keeps them on the node: they\n * last while it has no strokes, and a stroke added to it takes them. Each stroke still carries\n * its own `weight` and `align`, which win while the node has strokes.\n */\n strokeWeight: number\n strokeAlign: Stroke['align']\n\n strokeMiterLimit: number\n\n minWidth: number | null\n maxWidth: number | null\n minHeight: number | null\n maxHeight: number | null\n /**\n * The size whose proportions the layer keeps, as Figma stores it: the width and height it had\n * when the ratio was locked, not a reduced ratio. Null leaves the proportions free.\n */\n targetAspectRatio: Vector | null\n\n 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\n componentId: string | null\n instanceOverrides: InstanceOverrideState\n componentPropertyDefinitions: ComponentPropertyDefinition[]\n componentPropertyReferences: ComponentPropertyReference[]\n componentPropertyAssignments: Record<string, string>\n componentPropertyValues: Record<string, string>\n componentKey: string | null\n sourceLibraryKey: string | null\n publishId: string | null\n overrideKey: string | null\n sharedSymbolVersion: string | null\n publishedVersion: string | null\n librarySource: LibraryAssetSource | null\n isPublishable: boolean\n isSymbolPublishable: boolean\n /**\n * On an instance inside a component: its properties show on instances of that component,\n * as Figma's `isExposedInstance`.\n */\n isExposedInstance: boolean\n symbolDescription: string\n symbolLinks: SymbolLink[]\n variantPropSpecs: VariantPropSpec[]\n\n boundVariables: Record<string, string>\n /** Multipliers from bound numeric values to this occurrence's scene units. */\n variableBindingScales: Partial<Record<string, number>>\n /** Numeric units for new declarations owned by this node's occurrence scope. */\n variableAssignmentScales: Partial<Record<string, number>>\n /** Explicit coordinate scale relative to the containing component definition. */\n componentScale: number\n variableModes: VariableModeMap\n exportSettings: ExportSetting[]\n\n 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 /** 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 type VariableValue = Color | number | string | boolean | { aliasId: string }\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/** A mode value authored as raw CSS. `resolved` is the number the canvas drew for it. */\nexport interface TokenExpression {\n css: string\n resolved: number\n}\n\nexport interface Variable {\n id: string\n name: string\n type: VariableType\n collectionId: string\n valuesByMode: Record<string, VariableValue>\n description: string\n hiddenFromPublishing: boolean\n /** Absent means every scope. */\n scopes?: VariableScope[]\n /**\n * Per-platform code snippets, as Figma's Dev Mode shows them. A `WEB` snippet of `--x` or\n * `var(--x)` names the token's CSS custom property; otherwise the name is derived.\n */\n codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>\n /** FLOAT only. Absent means inferred when written as CSS. */\n unit?: TokenUnit\n /** Raw CSS by mode id, for values a number cannot express (`clamp()`, `calc()`). */\n expressions?: Record<string, TokenExpression>\n pluginData?: PluginDataEntry[]\n /** Published library key (from NodeChange.key). Used for assetRef resolution in colorVar. */\n key?: string\n /** Published library version (from NodeChange.version). Used for assetRef resolution in colorVar. */\n version?: string\n}\n\n/** Scalar numeric node fields accepted by numeric property controls. */\nexport type NumericNodeProperty = {\n [K in keyof SceneNode]-?: SceneNode[K] extends number ? K : never\n}[keyof SceneNode]\n\nexport interface VariableCollectionMode {\n modeId: string\n name: string\n /**\n * Where the mode applies in CSS: a selector (`[data-theme=\"dark\"]`, `.compact`) or an\n * at-rule prelude (`@media (max-width: 640px)`). Absent means the default for its axis.\n */\n condition?: string\n}\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\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","import * as v from 'valibot'\n\nimport { behaviourSchema } from '../behaviours/schema'\nimport type { OkHCLPayload } from '../color/okhcl'\nimport { isExportFormatId, type ExportFormatId } from '../export-format'\nimport { clampExportScale } from '../export-scale'\nimport { iconSchema, iconTintSchema } from '../icons/schema'\nimport type { Rect } from '../primitives'\nimport { shaderPaintSchema } from '../shaders/schema'\nimport {\n MODE_ATTRIBUTE_PATTERN,\n TOKEN_UNITS,\n type CommentThread,\n type EnabledLibraryBinding,\n type ExportSetting,\n type LayoutDirection,\n type LibraryAssetSource,\n type PluginDataEntry,\n type SourceLibraryPublication,\n type TextDirection,\n type TokenUnit\n} from '../types'\nimport {\n jsonPluginDataField,\n textPluginDataField,\n withoutPluginData,\n type PluginDataKey\n} from './field'\n\nconst DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (\n | TextDirection\n | LayoutDirection\n)[]\n\nconst textPathBox: v.GenericSchema<unknown, Rect> = v.pipe(\n v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }),\n v.check(\n ({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0\n )\n)\n\n/** String-valued entries of a JSON object; other entries are dropped, not rejected. */\nconst boundVariables = v.pipe(\n v.custom<Record<string, unknown>>(\n (value) => typeof value === 'object' && value !== null && !Array.isArray(value)\n ),\n v.transform((value) =>\n Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string'\n )\n )\n )\n)\n\n/** Every entry must be valid, or the whole value is ignored in favour of native settings. */\nconst exportSettings: v.GenericSchema<unknown, ExportSetting[]> = v.array(\n v.pipe(\n v.object({\n scale: v.pipe(v.number(), v.finite()),\n format: v.custom<ExportFormatId>(isExportFormatId)\n }),\n // Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.\n v.transform(({ scale, format }) => ({ scale: clampExportScale(scale), format }))\n )\n)\n\nconst librarySource: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(\n v.object({\n identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),\n sourceNodeId: v.optional(v.unknown()),\n readOnly: v.optional(v.unknown())\n }),\n v.transform(({ identity, sourceNodeId, readOnly }) => ({\n identity,\n sourceNodeId: typeof sourceNodeId === 'string' ? sourceNodeId : null,\n readOnly: readOnly === true\n }))\n)\n\nconst enabledLibrary = v.object({\n libraryId: v.string(),\n revisionId: v.string(),\n enabled: v.optional(v.unknown())\n})\n\n/** Invalid entries are skipped one by one, so one bad binding keeps the others. */\nconst enabledLibraries: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(\n v.array(v.unknown()),\n v.transform((items) =>\n items.flatMap((item) => {\n const parsed = v.safeParse(enabledLibrary, item)\n if (!parsed.success) return []\n const { libraryId, revisionId, enabled } = parsed.output\n return [{ libraryId, revisionId, enabled: enabled === true }]\n })\n )\n)\n\n// Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.\nconst cssText = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))\n\n/** Token fields Figma has no slot for, with mode ids as the file spells them. */\nexport interface StoredToken {\n unit?: TokenUnit\n expressions?: Record<string, { css: string; resolved: number }>\n}\n\nconst token: v.GenericSchema<unknown, StoredToken> = v.object({\n unit: v.optional(v.picklist(TOKEN_UNITS)),\n expressions: v.optional(\n v.record(v.string(), v.object({ css: cssText, resolved: v.pipe(v.number(), v.finite()) }))\n )\n})\n\nconst okhcl: v.GenericSchema<unknown, OkHCLPayload> = v.object({\n version: v.literal(1),\n kind: v.picklist(['fill', 'stroke']),\n index: v.number(),\n color: v.object({\n h: v.number(),\n c: v.number(),\n l: v.number(),\n a: v.fallback(v.optional(v.number()), undefined)\n })\n})\n\nconst sourceLibraryPublication: v.GenericSchema<unknown, SourceLibraryPublication> = v.object({\n libraryId: v.string(),\n revisionId: v.string(),\n name: v.string(),\n catalogSource: v.optional(v.string())\n})\n\n// Lenient on purpose: other tools may write comments, so missing fields get defaults and one\n// malformed thread is skipped instead of hiding every comment.\nconst commentAuthorColor = v.fallback(\n v.optional(v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })),\n undefined\n)\n\n/** What a comment and each reply say, who wrote them and when, and whether they were deleted. */\nconst commentEntry = {\n author: v.fallback(v.string(), ''),\n authorColor: commentAuthorColor,\n text: v.fallback(v.string(), ''),\n createdAt: v.fallback(v.string(), ''),\n deleted: v.optional(v.boolean())\n}\n\nconst commentReply = v.object({ id: v.string(), ...commentEntry })\n\nconst commentThread = v.object({\n id: v.string(),\n pageId: v.string(),\n pageName: v.optional(v.string()),\n nodeId: v.optional(v.nullable(v.string())),\n nodeName: v.optional(v.nullable(v.string())),\n offsetX: v.optional(v.number()),\n offsetY: v.optional(v.number()),\n x: v.fallback(v.number(), 0),\n y: v.fallback(v.number(), 0),\n ...commentEntry,\n updatedAt: v.fallback(v.string(), ''),\n resolved: v.fallback(v.boolean(), false),\n resolvedAt: v.optional(v.nullable(v.string())),\n replies: v.fallback(v.array(commentReply), [])\n})\n\nconst comments: v.GenericSchema<unknown, CommentThread[]> = v.pipe(\n v.array(v.unknown()),\n v.transform((items) =>\n items.flatMap((item) => {\n const parsed = v.safeParse(commentThread, item)\n if (!parsed.success) return []\n const thread = parsed.output\n return [{ ...thread, updatedAt: thread.updatedAt || thread.createdAt }]\n })\n )\n)\n\n/**\n * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's\n * format has no field for. Add a key here, never as a string elsewhere, so reading and writing\n * it share one schema.\n */\nexport const OPEN_PENCIL_PLUGIN_DATA = {\n /** A text node's direction, on TEXT nodes. */\n textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),\n /** An auto-layout frame's direction. */\n layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),\n /** Marks a component set Figma would read as a plain frame. */\n nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),\n /** Variable bindings by field path, including those Figma cannot store natively. */\n boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariables),\n exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettings),\n /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */\n textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBox),\n /** The library asset a node was inserted from. */\n librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySource),\n /** Libraries enabled for the document, on the DOCUMENT node. */\n enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibraries),\n /** The library this document publishes as, on the DOCUMENT node. */\n sourceLibraryPublication: jsonPluginDataField(\n 'sourceLibraryPublication',\n 'bookkeeping',\n sourceLibraryPublication\n ),\n /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */\n comments: jsonPluginDataField('comments', 'bookkeeping', comments),\n /** Unit and CSS expressions, on each VARIABLE. */\n token: jsonPluginDataField('token', 'format', token),\n /** Mode conditions by mode id, on each VARIABLE_SET. */\n modeConditions: jsonPluginDataField('modeConditions', 'format', v.record(v.string(), cssText)),\n /** The attribute that switches manual modes, on each VARIABLE_SET. */\n modeAttribute: jsonPluginDataField(\n 'modeAttribute',\n 'format',\n v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))\n ),\n /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */\n okhcl: jsonPluginDataField('okhcl', 'content', okhcl),\n /** How a main component or component set behaves as a control in preview. */\n behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),\n /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */\n icon: jsonPluginDataField('icon', 'content', iconSchema),\n /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */\n iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema),\n /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */\n shader: jsonPluginDataField('shader', 'content', shaderPaintSchema)\n} satisfies Record<string, PluginDataKey>\n\nconst NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(\n (field) => field.role !== 'content'\n)\n\n/**\n * A node's plugin data that is part of its content, in a stable order: OpenPencil's content\n * fields and every other plugin's entries, which the node carries wherever it goes. Format\n * copies of node fields and bookkeeping are left out.\n */\nexport function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {\n return withoutPluginData(entries, NOT_CONTENT).sort(\n (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)\n )\n}\n","import type { SceneGraph } from '../index'\nimport { readPluginData, withPluginData } from '../plugin-data/field'\nimport { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'\nimport type { ComponentPropertyDefinition, SceneNode } from '../types'\nimport {\n behaviourContract,\n INTERACTION_STATES,\n type BehaviourKind,\n type InteractionState\n} from './kinds'\nimport type {\n Behaviour,\n BehaviourBooleanBinding,\n BehaviourInteractionStates,\n BehaviourNumberSettings\n} from './schema'\n\nexport type {\n Behaviour,\n BehaviourBooleanBinding,\n BehaviourInteractionStates,\n BehaviourNumberSettings\n} from './schema'\nexport { isNumberRange } from './schema'\n\nexport const DEFAULT_NUMBER_SETTINGS: BehaviourNumberSettings = {\n min: 0,\n max: 100,\n step: 1,\n default: 50\n}\n\n/** A boolean value's binding, if the behaviour has one. */\nexport function booleanBinding(\n behaviour: Behaviour,\n valueId: string\n): BehaviourBooleanBinding | undefined {\n return Object.hasOwn(behaviour.booleans, valueId) ? behaviour.booleans[valueId] : undefined\n}\n\n/** The slot property a part is bound to, if any. */\nexport function partBinding(behaviour: Behaviour, partId: string): string | undefined {\n return Object.hasOwn(behaviour.parts, partId) ? behaviour.parts[partId] : undefined\n}\n\n/** The text property a text value is bound to, if any. */\nexport function textBinding(behaviour: Behaviour, valueId: string): string | undefined {\n return Object.hasOwn(behaviour.texts, valueId) ? behaviour.texts[valueId].propertyId : undefined\n}\n\n/** A number value's range, if the behaviour has one. */\nexport function numberSettings(\n behaviour: Behaviour,\n valueId: string\n): BehaviourNumberSettings | undefined {\n return Object.hasOwn(behaviour.numbers, valueId) ? behaviour.numbers[valueId] : undefined\n}\n\n/** A new behaviour of a kind, its number values at their defaults and nothing bound. */\nexport function emptyBehaviour(kind: BehaviourKind): Behaviour {\n const contract = behaviourContract(kind)\n const numbers = Object.fromEntries(\n contract.values\n .filter((value) => value.type === 'number')\n .map((value) => [value.id, { ...DEFAULT_NUMBER_SETTINGS }])\n )\n return { kind, booleans: {}, texts: {}, numbers, parts: {} }\n}\n\n/**\n * The node that keeps the behaviour: a component set for its variants, otherwise the main\n * component itself.\n */\nexport function behaviourOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n if (node.type === 'COMPONENT_SET') return node\n if (node.type !== 'COMPONENT') return undefined\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n return parent?.type === 'COMPONENT_SET' ? parent : node\n}\n\n/** The behaviour a component or component set keeps, or null when it has none or it is unreadable. */\nexport function readBehaviour(owner: SceneNode): Behaviour | null {\n return readPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour) ?? null\n}\n\n/** The owner's plugin data with the behaviour set, or removed when null. */\nexport function withBehaviour(\n owner: SceneNode,\n behaviour: Behaviour | null\n): SceneNode['pluginData'] {\n return withPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour, behaviour ?? undefined)\n}\n\n/** Component properties the behaviour can bind to: the owner's, and a set's variants' own. */\nexport function behaviourProperties(\n graph: SceneGraph,\n owner: SceneNode\n): ComponentPropertyDefinition[] {\n const variants =\n owner.type === 'COMPONENT_SET'\n ? owner.childIds.flatMap((id) => graph.getNode(id)?.componentPropertyDefinitions ?? [])\n : []\n const seen = new Set<string>()\n return [...owner.componentPropertyDefinitions, ...variants].filter((definition) => {\n if (seen.has(definition.id)) return false\n seen.add(definition.id)\n return true\n })\n}\n\n/**\n * Required values and parts that are unbound, or bound to a property the component no longer\n * has, by value or part id; `states` when the interaction states lost their variant property.\n */\nexport function missingBindings(\n graph: SceneGraph,\n owner: SceneNode,\n behaviour: Behaviour\n): string[] {\n const contract = behaviourContract(behaviour.kind)\n const properties = new Map(\n behaviourProperties(graph, owner).map((definition) => [definition.id, definition])\n )\n const bound = (propertyId: string | undefined, type: ComponentPropertyDefinition['type'][]) => {\n const definition = propertyId ? properties.get(propertyId) : undefined\n return !!definition && type.includes(definition.type)\n }\n const values = contract.values\n .filter((value) => value.required)\n .filter((value) =>\n value.type === 'text'\n ? !bound(textBinding(behaviour, value.id), ['TEXT'])\n : value.type === 'boolean' &&\n !bound(booleanBinding(behaviour, value.id)?.propertyId, ['VARIANT', 'BOOLEAN'])\n )\n .map((value) => value.id)\n const parts = contract.parts\n .filter((part) => part.required && !bound(partBinding(behaviour, part.id), ['SLOT']))\n .map((part) => part.id)\n const states =\n behaviour.states && !bound(behaviour.states.propertyId, ['VARIANT']) ? ['states'] : []\n return [...values, ...parts, ...states]\n}\n\n/** Variant value names that usually mean each interaction state, compared case-insensitively. */\nconst STATE_NAMES: Record<InteractionState, readonly string[]> = {\n rest: ['default', 'rest', 'idle', 'normal', 'enabled'],\n hover: ['hover', 'hovered', 'hovering'],\n pressed: ['pressed', 'active', 'down', 'pressing'],\n focus: ['focus', 'focused', 'focus visible', 'focus-visible'],\n disabled: ['disabled', 'inactive']\n}\n\n/**\n * Interaction states for a variant property, each mapped to the value whose name means it, such\n * as `Hover` or `Pressed`; states without such a value are left unset.\n */\nexport function guessInteractionStates(\n propertyId: string,\n values: readonly string[]\n): BehaviourInteractionStates {\n const states: BehaviourInteractionStates = { propertyId }\n for (const state of INTERACTION_STATES) {\n const match = values.find((value) => STATE_NAMES[state].includes(value.trim().toLowerCase()))\n if (match) states[state] = match\n }\n return states\n}\n\n/**\n * The behaviour with every component property id it binds renamed by `rename`, for formats that\n * give properties new ids on write, such as `.fig` with its GUIDs.\n */\nexport function renameBehaviourProperties(\n behaviour: Behaviour,\n rename: (propertyId: string) => string\n): Behaviour {\n const mapValues = <T>(record: Record<string, T>, change: (value: T) => T) =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, change(value)]))\n return {\n ...behaviour,\n booleans: mapValues(behaviour.booleans, (binding) => ({\n ...binding,\n propertyId: rename(binding.propertyId)\n })),\n texts: mapValues(behaviour.texts, (binding) => ({ propertyId: rename(binding.propertyId) })),\n parts: mapValues(behaviour.parts, rename),\n ...(behaviour.states\n ? { states: { ...behaviour.states, propertyId: rename(behaviour.states.propertyId) } }\n : {})\n }\n}\n","import type { SceneGraph } from '../index'\nimport type { SceneNode } from '../types'\nimport { behaviourOwner, readBehaviour } from './model'\n\n/** Whether an instance's main component, or its set, has a behaviour. */\nexport function hasBehaviour(graph: SceneGraph, node: SceneNode): boolean {\n if (node.type !== 'INSTANCE' || !node.componentId) return false\n const component = graph.getNode(node.componentId)\n const owner = component && behaviourOwner(graph, component)\n return !!owner && !!readBehaviour(owner)\n}\n\n/** A name as a path segment: `/` separates segments and `#` the twin index, so both are escaped. */\nconst pathName = (name: string) => name.replace(/[%/#]/g, (char) => encodeURIComponent(char))\n\n/**\n * A layer's path below a root: the names of the layers down to it, with the position among\n * same-named siblings when names repeat. It stays the same when a variant switch rebuilds an\n * instance's layers, so it identifies controls and keeps their DOM in place.\n */\nexport function layerPath(graph: SceneGraph, rootId: string, nodeId: string): string {\n const segments: string[] = []\n // `closest` stops on a parent cycle in bad data, where a hand-written walk would not.\n graph.closest(nodeId, (node) => {\n if (node.id === rootId) return true\n const twins = node.parentId\n ? graph.getChildren(node.parentId).filter((child) => child.name === node.name)\n : []\n const index = twins.findIndex((child) => child.id === node.id)\n segments.unshift(twins.length > 1 ? `${pathName(node.name)}#${index}` : pathName(node.name))\n return false\n })\n return segments.join('/')\n}\n\n/** The layer at `path` below a root, the inverse of `layerPath`. */\nexport function findLayerByPath(\n graph: SceneGraph,\n rootId: string,\n path: string\n): SceneNode | undefined {\n let current = graph.getNode(rootId)\n for (const segment of path ? path.split('/') : []) {\n if (!current) return undefined\n const hash = segment.lastIndexOf('#')\n const name = hash === -1 ? segment : segment.slice(0, hash)\n const twins = graph.getChildren(current.id).filter((child) => pathName(child.name) === name)\n current = twins.at(hash === -1 ? 0 : Number(segment.slice(hash + 1)))\n }\n return current\n}\n"],"mappings":";;;;AAKA,MAAa,wBAAwB;;;;;AA6BrC,SAAgB,oBACd,KACA,MACA,QACoB;CACpB,MAAM,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,MAAM;CACvD,OAAO;EACL;EACA;EACA,OAAO,OAAO;GACZ,MAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;GACxC,OAAO,OAAO,UAAU,OAAO,SAAS,KAAA;EAC1C;EACA,SAAS,UAAU,KAAK,UAAU,KAAK;CACzC;AACF;;AAGA,SAAgB,oBACd,KACA,MACA,QACoB;CACpB,MAAM,SAAS,EAAE,SAAS,MAAM;CAChC,OAAO;EACL;EACA;EACA,OAAO,OAAO;GACZ,MAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;GACxC,OAAO,OAAO,UAAU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,OAAmB,QAAgB,QAAwB;CACnF,MAAM,WAAqB,CAAC;CAE5B,MAAM,QAAQ,SAAS,SAAS;EAC9B,IAAI,KAAK,OAAO,QAAQ,OAAO;EAC/B,MAAM,QAAQ,KAAK,WACf,MAAM,YAAY,KAAK,QAAQ,CAAC,CAAC,QAAQ,UAAU,MAAM,SAAS,KAAK,IAAI,IAC3E,CAAC;EACL,MAAM,QAAQ,MAAM,WAAW,UAAU,MAAM,OAAO,KAAK,EAAE;EAC7D,SAAS,QAAQ,MAAM,SAAS,IAAI,GAAG,SAAS,KAAK,IAAI,EAAE,GAAG,UAAU,SAAS,KAAK,IAAI,CAAC;EAC3F,OAAO;CACT,CAAC;CACD,OAAO,SAAS,KAAK,GAAG;AAC1B;;AAGA,SAAgB,gBACd,OACA,QACA,MACuB;CACvB,IAAI,UAAU,MAAM,QAAQ,MAAM;CAClC,KAAK,MAAM,WAAW,OAAO,KAAK,MAAM,GAAG,IAAI,CAAC,GAAG;EACjD,IAAI,CAAC,SAAS,OAAO,KAAA;EACrB,MAAM,OAAO,QAAQ,YAAY,GAAG;EACpC,MAAM,OAAO,SAAS,KAAK,UAAU,QAAQ,MAAM,GAAG,IAAI;EAE1D,UADc,MAAM,YAAY,QAAQ,EAAE,CAAC,CAAC,QAAQ,UAAU,SAAS,MAAM,IAAI,MAAM,IACzE,CAAC,CAAC,GAAG,SAAS,KAAK,IAAI,OAAO,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC;CACtE;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"layers.js","names":[],"sources":["../../../src/plugin-data/field.ts","../../../src/behaviours/schema.ts","../../../src/export-format.ts","../../../src/export-scale.ts","../../../src/icons/schema.ts","../../../src/shaders/schema.ts","../../../src/types.ts","../../../src/plugin-data/fields.ts","../../../src/behaviours/model.ts","../../../src/behaviours/layers.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { PluginDataEntry } from '../types'\n\n/** The plugin id OpenPencil keeps its own state under, on nodes and in `.fig` files. */\nexport const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'\n\n/**\n * What a field holds:\n * - `content` belongs to the node like its fills do and exists only as plugin data, so it\n * travels with a component copied into a library or another document;\n * - `format` repeats a node or variable field for files that have no slot for it, where the\n * node field is what counts;\n * - `bookkeeping` records where a node or document came from and stays behind.\n */\nexport type PluginDataRole = 'content' | 'format' | 'bookkeeping'\n\n/** One OpenPencil plugin-data key. */\nexport interface PluginDataKey {\n readonly key: string\n readonly role: PluginDataRole\n}\n\n/** A plugin-data key and how its string value is read and written. */\nexport interface PluginDataField<T> extends PluginDataKey {\n /** The stored value, or `undefined` when it is missing or not a valid value. */\n decode(value: string | null | undefined): T | undefined\n encode(value: T): string\n}\n\n/**\n * A value stored as JSON. Invalid JSON and a wrong shape both read as missing: plugin data\n * comes from files anyone can edit, so a bad entry is ignored rather than thrown on.\n */\nexport function jsonPluginDataField<T>(\n key: string,\n role: PluginDataRole,\n schema: v.GenericSchema<unknown, T>\n): PluginDataField<T> {\n const stored = v.pipe(v.string(), v.parseJson(), schema)\n return {\n key,\n role,\n decode(value) {\n const parsed = v.safeParse(stored, value)\n return parsed.success ? parsed.output : undefined\n },\n encode: (value) => JSON.stringify(value)\n }\n}\n\n/** A value stored as one of a fixed set of plain strings. */\nexport function textPluginDataField<const T extends string>(\n key: string,\n role: PluginDataRole,\n values: readonly T[]\n): PluginDataField<T> {\n const schema = v.picklist(values)\n return {\n key,\n role,\n decode(value) {\n const parsed = v.safeParse(schema, value)\n return parsed.success ? parsed.output : undefined\n },\n encode: (value) => value\n }\n}\n\nexport function isPluginDataEntry(entry: PluginDataEntry, field: PluginDataKey): boolean {\n return entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === field.key\n}\n\nexport function hasPluginData(\n entries: readonly PluginDataEntry[] | undefined,\n field: PluginDataKey\n): boolean {\n return entries?.some((entry) => isPluginDataEntry(entry, field)) ?? false\n}\n\nexport function readPluginData<T>(\n entries: readonly PluginDataEntry[] | undefined,\n field: PluginDataField<T>\n): T | undefined {\n return field.decode(entries?.find((entry) => isPluginDataEntry(entry, field))?.value)\n}\n\n/** Every valid value of a field kept as several entries under one key. */\nexport function readAllPluginData<T>(\n entries: readonly PluginDataEntry[] | undefined,\n field: PluginDataField<T>\n): T[] {\n return (entries ?? []).flatMap((entry) => {\n if (!isPluginDataEntry(entry, field)) return []\n const value = field.decode(entry.value)\n return value === undefined ? [] : [value]\n })\n}\n\nexport function pluginDataEntry<T>(field: PluginDataField<T>, value: T): PluginDataEntry {\n return { pluginId: OPEN_PENCIL_PLUGIN_ID, key: field.key, value: field.encode(value) }\n}\n\n/** Entries other than those of `fields`; other plugins' entries are always kept. */\nexport function withoutPluginData(\n entries: readonly PluginDataEntry[],\n fields: readonly PluginDataKey[]\n): PluginDataEntry[] {\n return entries.filter((entry) => !fields.some((field) => isPluginDataEntry(entry, field)))\n}\n\n/** Entries with `field` set to `value`, appended last; `undefined` removes the field. */\nexport function withPluginData<T>(\n entries: readonly PluginDataEntry[],\n field: PluginDataField<T>,\n value: T | undefined\n): PluginDataEntry[] {\n return withAllPluginData(entries, field, value === undefined ? [] : [value])\n}\n\n/** Entries with every entry of `field` replaced by one per value. */\nexport function withAllPluginData<T>(\n entries: readonly PluginDataEntry[],\n field: PluginDataField<T>,\n values: readonly T[]\n): PluginDataEntry[] {\n return [\n ...withoutPluginData(entries, [field]),\n ...values.map((value) => pluginDataEntry(field, value))\n ]\n}\n","import * as v from 'valibot'\n\nimport { BEHAVIOUR_KINDS, type InteractionState } from './kinds'\n\nconst BooleanBinding = v.object({\n propertyId: v.string(),\n /** For a variant property: the values that mean on and off. */\n on: v.optional(v.string()),\n off: v.optional(v.string())\n})\n\n/** Whether a number value's range can be stepped through: `max` above `min`, a positive step. */\nexport function isNumberRange(settings: { min: number; max: number; step: number }): boolean {\n return settings.max > settings.min && settings.step > 0\n}\n\nconst NumberSettings = v.pipe(\n v.object({\n min: v.pipe(v.number(), v.finite()),\n max: v.pipe(v.number(), v.finite()),\n step: v.pipe(v.number(), v.finite()),\n default: v.pipe(v.number(), v.finite())\n }),\n v.check(\n (settings) => isNumberRange(settings),\n 'A number value needs max above min and a positive step'\n )\n)\n\n/** Each interaction state's variant value, by state; a state left out shows the rest value. */\nexport const interactionStateValues = {\n rest: v.optional(v.string()),\n hover: v.optional(v.string()),\n pressed: v.optional(v.string()),\n focus: v.optional(v.string()),\n disabled: v.optional(v.string())\n} satisfies Record<InteractionState, unknown>\n\nconst InteractionStates = v.object({ propertyId: v.string(), ...interactionStateValues })\n\nexport const behaviourSchema = v.object({\n kind: v.picklist(BEHAVIOUR_KINDS),\n /** Boolean values, by value id, bound to component properties. */\n booleans: v.record(v.string(), BooleanBinding),\n /** Text values, by value id, bound to text properties. */\n texts: v.optional(v.record(v.string(), v.object({ propertyId: v.string() })), {}),\n /** Number values, by value id: the range the behaviour keeps itself. */\n numbers: v.record(v.string(), NumberSettings),\n /** Parts, by part id, bound to slot properties. */\n parts: v.record(v.string(), v.string()),\n states: v.optional(InteractionStates)\n})\n\n/** How a main component behaves as a control, as kept in its plugin data. */\nexport type Behaviour = v.InferOutput<typeof behaviourSchema>\nexport type BehaviourBooleanBinding = v.InferOutput<typeof BooleanBinding>\nexport type BehaviourNumberSettings = v.InferOutput<typeof NumberSettings>\nexport type BehaviourInteractionStates = v.InferOutput<typeof InteractionStates>\n","/**\n * Formats a node's export settings may persist. Each id must name a Core IO\n * export adapter that supports node export; labels and options come from that\n * adapter, so this list only decides what the Export panel offers.\n */\nexport const EXPORT_FORMAT_IDS = ['png', 'jpg', 'webp', 'svg', 'pdf', 'pptx'] as const\n\nexport type ExportFormatId = (typeof EXPORT_FORMAT_IDS)[number]\n\nexport function isExportFormatId(value: unknown): value is ExportFormatId {\n return EXPORT_FORMAT_IDS.some((id) => id === value)\n}\n","/**\n * Bounds for export scale multipliers. A huge multiplier would allocate an\n * enormous canvas and crash the renderer, so clamp at every boundary the value\n * can enter from: the UI (edits) and the file format (imported/plugin .fig data).\n */\nexport const MIN_EXPORT_SCALE = 0.01\nexport const MAX_EXPORT_SCALE = 1024\n\nexport function clampExportScale(scale: number): number {\n return Math.min(MAX_EXPORT_SCALE, Math.max(MIN_EXPORT_SCALE, scale))\n}\n\n/** Accept a scale only if it is finite and within bounds (no silent clamping). */\nexport function isValidExportScale(scale: number): boolean {\n return Number.isFinite(scale) && scale >= MIN_EXPORT_SCALE && scale <= MAX_EXPORT_SCALE\n}\n","import * as v from 'valibot'\n\n/** An icon's name in its set, `prefix:name`, as Iconify names icons. */\nexport const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_][a-z0-9]+)*$/\n\nexport const iconSchema = v.object({\n name: v.pipe(v.string(), v.regex(ICON_NAME)),\n /** A fingerprint of the glyph as placed, to tell when its paths were edited; see `iconGlyph`. */\n glyph: v.optional(v.string())\n})\n\n/** An icon a frame draws. */\nexport type Icon = v.InferOutput<typeof iconSchema>\n\nexport const ICON_PAINTS = ['fill', 'stroke'] as const\nexport type IconPaint = (typeof ICON_PAINTS)[number]\n\nexport const iconTintSchema = v.pipe(v.array(v.picklist(ICON_PAINTS)), v.minLength(1))\n","import * as v from 'valibot'\n\n/** One effect of a shader preset, as the `shaders` library names it, with the effects it holds. */\nexport interface ShaderComponent {\n type: string\n id?: string\n props?: Record<string, unknown>\n children?: ShaderComponent[]\n}\n\nconst shaderComponent: v.GenericSchema<unknown, ShaderComponent> = v.object({\n type: v.pipe(v.string(), v.nonEmpty(), v.maxLength(100)),\n id: v.optional(v.string()),\n props: v.optional(v.record(v.string(), v.unknown())),\n children: v.optional(v.array(v.lazy(() => shaderComponent)))\n})\n\n/**\n * A shader as the `shaders` library describes it and shaders.com exports it: a tree of effects,\n * drawn first to last.\n */\nexport const shaderPresetSchema = v.object({\n components: v.pipe(v.array(shaderComponent), v.minLength(1)),\n structureVersion: v.optional(v.number())\n})\n\nexport type ShaderPreset = v.InferOutput<typeof shaderPresetSchema>\n\n/**\n * A paint that draws a shader. The paint itself is an image fill of the shader's still frame, so\n * every format and renderer that reads images shows it; this entry says which image it is, the\n * preset that draws it, and the layer size and preset the frame was rendered for, which is\n * missing until it is first rendered.\n */\nexport const shaderPaintSchema = v.object({\n image: v.pipe(v.string(), v.nonEmpty()),\n preset: shaderPresetSchema,\n frame: v.optional(\n v.object({\n width: v.pipe(v.number(), v.finite(), v.minValue(0)),\n height: v.pipe(v.number(), v.finite(), v.minValue(0)),\n /** The preset's key (`shaderPresetKey`) when the frame was rendered. */\n preset: v.pipe(v.string(), v.nonEmpty())\n })\n )\n})\n\nexport type ShaderPaint = v.InferOutput<typeof shaderPaintSchema>\n","/* 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 './instance-overrides'\nimport type { Color, Matrix, Rect, Vector } from './primitives'\n\nexport interface SceneGraphEvents {\n 'node:created': (node: SceneNode) => void\n 'node:updated': (id: string, changes: Partial<SceneNode>) => void\n 'node:previewUpdated': (id: string, changes: Partial<SceneNode>) => void\n 'node:deleted': (id: string, parentId: string | null) => void\n 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void\n 'node:reordered': (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}\n\nexport type SceneGraphEventHandlers = Partial<{\n created: (node: SceneNode) => void\n updated: (id: string, changes: Partial<SceneNode>) => void\n previewUpdated: (id: string, changes: Partial<SceneNode>) => void\n deleted: (id: string, parentId: string | null) => void\n reparented: (nodeId: string, oldParentId: string | null, newParentId: string) => void\n reordered: (\n nodeId: string,\n parentId: string,\n index: number,\n previousParentId: string | null\n ) => void\n}>\n\n/** Hears about nodes as an edit adds and changes them, synchronously and before each change. */\nexport interface NodeChangeObserver {\n /** A node is about to change and is still as it was. */\n before: (node: SceneNode) => void\n /** A node was just added. */\n created: (node: SceneNode) => void\n}\n\nexport type DocumentColorSpace = 'srgb' | 'display-p3'\n\nexport interface FigmaSourcePayload {\n rawSize: Vector | null\n rawTransform: Matrix | null\n rawNodeFields: Record<string, unknown>\n layout: FigmaLayoutMetadata | null\n symbolOverrides: unknown[]\n componentPropAssignments: unknown[]\n derivedSymbolData: unknown[]\n derivedSymbolDataLayoutVersion: number | null\n uniformScaleFactor: number | null\n}\n\nexport interface SourceMetadata {\n format: 'fig' | null\n id: string | null\n orderKey: string | null\n editedFields: string[]\n fig: FigmaSourcePayload\n}\n\nexport type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'\nexport type WindingRule = 'NONZERO' | 'EVENODD'\n\nexport interface VectorVertex {\n x: number\n y: number\n strokeCap?: string\n strokeJoin?: string\n cornerRadius?: number\n handleMirroring?: HandleMirroring\n}\n\nexport interface VectorSegment {\n start: number\n end: number\n tangentStart: Vector\n tangentEnd: Vector\n}\n\nexport interface VectorRegion {\n windingRule: WindingRule\n loops: number[][]\n}\n\nexport interface VectorNetwork {\n vertices: VectorVertex[]\n segments: VectorSegment[]\n regions: VectorRegion[]\n}\n\nexport interface GeometryPath {\n windingRule: WindingRule\n commandsBlob: Uint8Array\n /** Resolved paints for geometry using a format-specific style override. */\n fills?: Fill[]\n /** Shared fill style attached to this geometry region, when available. */\n fillStyleId?: string\n}\n\nexport type NodeType =\n | 'CANVAS'\n | 'FRAME'\n | 'RECTANGLE'\n | 'ROUNDED_RECTANGLE'\n | 'ELLIPSE'\n | 'TEXT'\n | 'LINE'\n | 'STAR'\n | 'POLYGON'\n | 'VECTOR'\n | 'BOOLEAN_OPERATION'\n | 'GROUP'\n | 'SECTION'\n | 'COMPONENT'\n | 'COMPONENT_SET'\n | 'INSTANCE'\n | 'CONNECTOR'\n | 'SHAPE_WITH_TEXT'\n\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 | 'COLOR_BURN'\n | 'LIGHTEN'\n | 'SCREEN'\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 imageHash?: string\n imageScaleMode?: ImageScaleMode\n imageTransform?: GradientTransform\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 = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'\nexport type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'\nexport type SharedStyleType = 'FILL' | 'TEXT' | 'EFFECT' | 'GRID'\nexport type SharedStyleKind = 'fill' | 'stroke' | 'text' | 'effect' | 'grid'\nexport type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'\n\nexport interface LayoutGrid {\n visible?: boolean\n color?: Color\n /** `STRIPES` is the archive's name for columns or rows, along `axis`. */\n pattern?: 'COLUMNS' | 'ROWS' | 'GRID' | 'STRIPES'\n axis?: 'X' | 'Y'\n type?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n alignment?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'\n numSections?: number\n /** Figma's plugin API reports an Auto count as `null` and accepts `Infinity` for it. */\n count?: number | null\n offset?: number\n sectionSize?: number\n gutterSize?: number\n}\n\nexport interface SharedStyle {\n id: string\n nodeId: string\n name: string\n type: SharedStyleType\n}\n\n/** A stroke is a paint with the geometry that decides where it is drawn. */\nexport interface Stroke extends Fill {\n weight: number\n align: 'INSIDE' | 'CENTER' | 'OUTSIDE'\n cap?: StrokeCap\n join?: StrokeJoin\n dashPattern?: number[]\n}\n\nexport interface Effect {\n type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'\n color: Color\n offset: Vector\n radius: number\n spread: number\n visible: boolean\n blendMode?: BlendMode\n showShadowBehindNode?: boolean\n}\n\nexport type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'\nexport type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'\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\nexport interface CharacterStyleOverride {\n fontWeight?: number\n italic?: boolean\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?: number\n lineHeight?: number | null\n fills?: Fill[]\n fontVariations?: FontVariation[]\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\nexport interface ExportSetting {\n scale: number\n format: ExportFormatId\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 tValue: number\n forward: boolean\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\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 Yoga layout pass. */\n derivedLayout: Partial<Rect> | null\n\n fills: Fill[]\n strokes: Stroke[]\n effects: Effect[]\n layoutGrids: LayoutGrid[]\n guides: CanvasGuide[]\n fillStyleId: string | null\n strokeStyleId: string | null\n textStyleId: string | null\n effectStyleId: string | null\n gridStyleId: string | null\n sharedStyleType: SharedStyleType | null\n opacity: number\n\n cornerRadius: number\n topLeftRadius: number\n topRightRadius: number\n bottomRightRadius: number\n bottomLeftRadius: number\n independentCorners: boolean\n cornerSmoothing: number\n\n visible: boolean\n locked: boolean\n clipsContent: boolean\n\n blendMode: BlendMode\n\n text: string\n fontSize: number\n fontFamily: string\n fontWeight: number\n italic: boolean\n 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 lineHeight: number | null\n letterSpacing: number\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 fontFeatures: FontFeature[]\n\n horizontalConstraint: ConstraintType\n verticalConstraint: ConstraintType\n\n layoutMode: LayoutMode\n layoutDirection: LayoutDirection\n layoutWrap: LayoutWrap\n primaryAxisAlign: LayoutAlign\n counterAxisAlign: LayoutCounterAlign\n primaryAxisSizing: AxisSizingMode\n counterAxisSizing: AxisSizingMode\n itemSpacing: number\n counterAxisSpacing: number\n paddingTop: number\n paddingRight: number\n paddingBottom: number\n paddingLeft: number\n\n layoutPositioning: 'AUTO' | 'ABSOLUTE'\n layoutGrow: number\n layoutAlignSelf: LayoutAlignSelf\n\n vectorNetwork: VectorNetwork | null\n handleMirroring: HandleMirroring\n booleanOperation: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE' | undefined\n fillGeometry: GeometryPath[]\n strokeGeometry: GeometryPath[]\n\n arcData: ArcData | null\n\n strokeCap: StrokeCap\n strokeJoin: StrokeJoin\n dashPattern: number[]\n\n borderTopWeight: number\n borderRightWeight: number\n borderBottomWeight: number\n borderLeftWeight: number\n independentStrokeWeights: boolean\n\n /**\n * The weight and alignment a node keeps for its strokes, as Figma keeps them on the node: they\n * last while it has no strokes, and a stroke added to it takes them. Each stroke still carries\n * its own `weight` and `align`, which win while the node has strokes.\n */\n strokeWeight: number\n strokeAlign: Stroke['align']\n\n strokeMiterLimit: number\n\n minWidth: number | null\n maxWidth: number | null\n minHeight: number | null\n maxHeight: number | null\n /**\n * The size whose proportions the layer keeps, as Figma stores it: the width and height it had\n * when the ratio was locked, not a reduced ratio. Null leaves the proportions free.\n */\n targetAspectRatio: Vector | null\n\n 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\n componentId: string | null\n instanceOverrides: InstanceOverrideState\n componentPropertyDefinitions: ComponentPropertyDefinition[]\n componentPropertyReferences: ComponentPropertyReference[]\n componentPropertyAssignments: Record<string, string>\n componentPropertyValues: Record<string, string>\n componentKey: string | null\n sourceLibraryKey: string | null\n publishId: string | null\n overrideKey: string | null\n sharedSymbolVersion: string | null\n publishedVersion: string | null\n librarySource: LibraryAssetSource | null\n isPublishable: boolean\n isSymbolPublishable: boolean\n /**\n * On an instance inside a component: its properties show on instances of that component,\n * as Figma's `isExposedInstance`.\n */\n isExposedInstance: boolean\n symbolDescription: string\n symbolLinks: SymbolLink[]\n variantPropSpecs: VariantPropSpec[]\n\n boundVariables: Record<string, string>\n /** Multipliers from bound numeric values to this occurrence's scene units. */\n variableBindingScales: Partial<Record<string, number>>\n /** Numeric units for new declarations owned by this node's occurrence scope. */\n variableAssignmentScales: Partial<Record<string, number>>\n /** Explicit coordinate scale relative to the containing component definition. */\n componentScale: number\n variableModes: VariableModeMap\n exportSettings: ExportSetting[]\n\n 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 /** 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 type VariableValue = Color | number | string | boolean | { aliasId: string }\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/** A mode value authored as raw CSS. `resolved` is the number the canvas drew for it. */\nexport interface TokenExpression {\n css: string\n resolved: number\n}\n\nexport interface Variable {\n id: string\n name: string\n type: VariableType\n collectionId: string\n valuesByMode: Record<string, VariableValue>\n description: string\n hiddenFromPublishing: boolean\n /** Absent means every scope. */\n scopes?: VariableScope[]\n /**\n * Per-platform code snippets, as Figma's Dev Mode shows them. A `WEB` snippet of `--x` or\n * `var(--x)` names the token's CSS custom property; otherwise the name is derived.\n */\n codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>\n /** FLOAT only. Absent means inferred when written as CSS. */\n unit?: TokenUnit\n /** Raw CSS by mode id, for values a number cannot express (`clamp()`, `calc()`). */\n expressions?: Record<string, TokenExpression>\n pluginData?: PluginDataEntry[]\n /** Published library key (from NodeChange.key). Used for assetRef resolution in colorVar. */\n key?: string\n /** Published library version (from NodeChange.version). Used for assetRef resolution in colorVar. */\n version?: string\n}\n\n/** Scalar numeric node fields accepted by numeric property controls. */\nexport type NumericNodeProperty = {\n [K in keyof SceneNode]-?: SceneNode[K] extends number ? K : never\n}[keyof SceneNode]\n\nexport interface VariableCollectionMode {\n modeId: string\n name: string\n /**\n * Where the mode applies in CSS: a selector (`[data-theme=\"dark\"]`, `.compact`) or an\n * at-rule prelude (`@media (max-width: 640px)`). Absent means the default for its axis.\n */\n condition?: string\n /** Where Figma lists the mode, as the file saved it; Figma orders a collection's modes by it. */\n sortPosition?: string\n}\n\nexport interface VariableCollection {\n id: string\n name: string\n /** The default mode comes first, as in Figma. */\n modes: VariableCollectionMode[]\n defaultModeId: string\n variableIds: string[]\n /**\n * The attribute that switches a mode with no condition of its own, `data-theme` for\n * `[data-theme=\"dark\"]`. Absent means one named after the collection.\n */\n modeAttribute?: string\n pluginData?: PluginDataEntry[]\n /**\n * Published library key, for a collection the file copies from a library. Such a collection\n * belongs to the library: Figma lists it with the library's, not the file's own.\n */\n key?: string\n /** Published library version, which references by key carry with it. */\n version?: string\n}\n\n/** Whether a collection is a library's copy, which takes no variables or modes of the file's. */\nexport function isLibraryCollection(collection: Pick<VariableCollection, 'key'>): boolean {\n return !!collection.key\n}\n\n/** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */\nexport const MODE_ATTRIBUTE_PATTERN = /^[A-Za-z_][\\w-]*$/\n\nexport function isModeAttributeName(name: string): boolean {\n return name.length <= 100 && MODE_ATTRIBUTE_PATTERN.test(name)\n}\n","import * as v from 'valibot'\n\nimport { behaviourSchema } from '../behaviours/schema'\nimport type { OkHCLPayload } from '../color/okhcl'\nimport { isExportFormatId, type ExportFormatId } from '../export-format'\nimport { clampExportScale } from '../export-scale'\nimport { iconSchema, iconTintSchema } from '../icons/schema'\nimport type { Rect } from '../primitives'\nimport { shaderPaintSchema } from '../shaders/schema'\nimport {\n MODE_ATTRIBUTE_PATTERN,\n TOKEN_UNITS,\n type CommentThread,\n type EnabledLibraryBinding,\n type ExportSetting,\n type LayoutDirection,\n type LibraryAssetSource,\n type PluginDataEntry,\n type SourceLibraryPublication,\n type TextDirection,\n type TokenUnit\n} from '../types'\nimport {\n jsonPluginDataField,\n textPluginDataField,\n withoutPluginData,\n type PluginDataKey\n} from './field'\n\nconst DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (\n | TextDirection\n | LayoutDirection\n)[]\n\nconst textPathBox: v.GenericSchema<unknown, Rect> = v.pipe(\n v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }),\n v.check(\n ({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0\n )\n)\n\n/** String-valued entries of a JSON object; other entries are dropped, not rejected. */\nconst boundVariables = v.pipe(\n v.custom<Record<string, unknown>>(\n (value) => typeof value === 'object' && value !== null && !Array.isArray(value)\n ),\n v.transform((value) =>\n Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string'\n )\n )\n )\n)\n\n/** Every entry must be valid, or the whole value is ignored in favour of native settings. */\nconst exportSettings: v.GenericSchema<unknown, ExportSetting[]> = v.array(\n v.pipe(\n v.object({\n scale: v.pipe(v.number(), v.finite()),\n format: v.custom<ExportFormatId>(isExportFormatId)\n }),\n // Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.\n v.transform(({ scale, format }) => ({ scale: clampExportScale(scale), format }))\n )\n)\n\nconst librarySource: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(\n v.object({\n identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),\n sourceNodeId: v.optional(v.unknown()),\n readOnly: v.optional(v.unknown())\n }),\n v.transform(({ identity, sourceNodeId, readOnly }) => ({\n identity,\n sourceNodeId: typeof sourceNodeId === 'string' ? sourceNodeId : null,\n readOnly: readOnly === true\n }))\n)\n\nconst enabledLibrary = v.object({\n libraryId: v.string(),\n revisionId: v.string(),\n enabled: v.optional(v.unknown())\n})\n\n/** Invalid entries are skipped one by one, so one bad binding keeps the others. */\nconst enabledLibraries: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(\n v.array(v.unknown()),\n v.transform((items) =>\n items.flatMap((item) => {\n const parsed = v.safeParse(enabledLibrary, item)\n if (!parsed.success) return []\n const { libraryId, revisionId, enabled } = parsed.output\n return [{ libraryId, revisionId, enabled: enabled === true }]\n })\n )\n)\n\n// Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.\nconst cssText = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))\n\n/** Token fields Figma has no slot for, with mode ids as the file spells them. */\nexport interface StoredToken {\n unit?: TokenUnit\n expressions?: Record<string, { css: string; resolved: number }>\n}\n\nconst token: v.GenericSchema<unknown, StoredToken> = v.object({\n unit: v.optional(v.picklist(TOKEN_UNITS)),\n expressions: v.optional(\n v.record(v.string(), v.object({ css: cssText, resolved: v.pipe(v.number(), v.finite()) }))\n )\n})\n\nconst okhcl: v.GenericSchema<unknown, OkHCLPayload> = v.object({\n version: v.literal(1),\n kind: v.picklist(['fill', 'stroke']),\n index: v.number(),\n color: v.object({\n h: v.number(),\n c: v.number(),\n l: v.number(),\n a: v.fallback(v.optional(v.number()), undefined)\n })\n})\n\nconst sourceLibraryPublication: v.GenericSchema<unknown, SourceLibraryPublication> = v.object({\n libraryId: v.string(),\n revisionId: v.string(),\n name: v.string(),\n catalogSource: v.optional(v.string())\n})\n\n// Lenient on purpose: other tools may write comments, so missing fields get defaults and one\n// malformed thread is skipped instead of hiding every comment.\nconst commentAuthorColor = v.fallback(\n v.optional(v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })),\n undefined\n)\n\n/** What a comment and each reply say, who wrote them and when, and whether they were deleted. */\nconst commentEntry = {\n author: v.fallback(v.string(), ''),\n authorColor: commentAuthorColor,\n text: v.fallback(v.string(), ''),\n createdAt: v.fallback(v.string(), ''),\n deleted: v.optional(v.boolean())\n}\n\nconst commentReply = v.object({ id: v.string(), ...commentEntry })\n\nconst commentThread = v.object({\n id: v.string(),\n pageId: v.string(),\n pageName: v.optional(v.string()),\n nodeId: v.optional(v.nullable(v.string())),\n nodeName: v.optional(v.nullable(v.string())),\n offsetX: v.optional(v.number()),\n offsetY: v.optional(v.number()),\n x: v.fallback(v.number(), 0),\n y: v.fallback(v.number(), 0),\n ...commentEntry,\n updatedAt: v.fallback(v.string(), ''),\n resolved: v.fallback(v.boolean(), false),\n resolvedAt: v.optional(v.nullable(v.string())),\n replies: v.fallback(v.array(commentReply), [])\n})\n\nconst comments: v.GenericSchema<unknown, CommentThread[]> = v.pipe(\n v.array(v.unknown()),\n v.transform((items) =>\n items.flatMap((item) => {\n const parsed = v.safeParse(commentThread, item)\n if (!parsed.success) return []\n const thread = parsed.output\n return [{ ...thread, updatedAt: thread.updatedAt || thread.createdAt }]\n })\n )\n)\n\n/**\n * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's\n * format has no field for. Add a key here, never as a string elsewhere, so reading and writing\n * it share one schema.\n */\nexport const OPEN_PENCIL_PLUGIN_DATA = {\n /** A text node's direction, on TEXT nodes. */\n textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),\n /** An auto-layout frame's direction. */\n layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),\n /** Marks a component set Figma would read as a plain frame. */\n nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),\n /** Variable bindings by field path, including those Figma cannot store natively. */\n boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariables),\n exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettings),\n /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */\n textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBox),\n /** The library asset a node was inserted from. */\n librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySource),\n /** Libraries enabled for the document, on the DOCUMENT node. */\n enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibraries),\n /** The library this document publishes as, on the DOCUMENT node. */\n sourceLibraryPublication: jsonPluginDataField(\n 'sourceLibraryPublication',\n 'bookkeeping',\n sourceLibraryPublication\n ),\n /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */\n comments: jsonPluginDataField('comments', 'bookkeeping', comments),\n /** Unit and CSS expressions, on each VARIABLE. */\n token: jsonPluginDataField('token', 'format', token),\n /** Mode conditions by mode id, on each VARIABLE_SET. */\n modeConditions: jsonPluginDataField('modeConditions', 'format', v.record(v.string(), cssText)),\n /** The attribute that switches manual modes, on each VARIABLE_SET. */\n modeAttribute: jsonPluginDataField(\n 'modeAttribute',\n 'format',\n v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))\n ),\n /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */\n okhcl: jsonPluginDataField('okhcl', 'content', okhcl),\n /** How a main component or component set behaves as a control in preview. */\n behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),\n /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */\n icon: jsonPluginDataField('icon', 'content', iconSchema),\n /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */\n iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema),\n /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */\n shader: jsonPluginDataField('shader', 'content', shaderPaintSchema)\n} satisfies Record<string, PluginDataKey>\n\nconst NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(\n (field) => field.role !== 'content'\n)\n\n/**\n * A node's plugin data that is part of its content, in a stable order: OpenPencil's content\n * fields and every other plugin's entries, which the node carries wherever it goes. Format\n * copies of node fields and bookkeeping are left out.\n */\nexport function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {\n return withoutPluginData(entries, NOT_CONTENT).sort(\n (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)\n )\n}\n","import type { SceneGraph } from '../index'\nimport { readPluginData, withPluginData } from '../plugin-data/field'\nimport { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'\nimport type { ComponentPropertyDefinition, SceneNode } from '../types'\nimport {\n behaviourContract,\n INTERACTION_STATES,\n type BehaviourKind,\n type InteractionState\n} from './kinds'\nimport type {\n Behaviour,\n BehaviourBooleanBinding,\n BehaviourInteractionStates,\n BehaviourNumberSettings\n} from './schema'\n\nexport type {\n Behaviour,\n BehaviourBooleanBinding,\n BehaviourInteractionStates,\n BehaviourNumberSettings\n} from './schema'\nexport { isNumberRange } from './schema'\n\nexport const DEFAULT_NUMBER_SETTINGS: BehaviourNumberSettings = {\n min: 0,\n max: 100,\n step: 1,\n default: 50\n}\n\n/** A boolean value's binding, if the behaviour has one. */\nexport function booleanBinding(\n behaviour: Behaviour,\n valueId: string\n): BehaviourBooleanBinding | undefined {\n return Object.hasOwn(behaviour.booleans, valueId) ? behaviour.booleans[valueId] : undefined\n}\n\n/** The slot property a part is bound to, if any. */\nexport function partBinding(behaviour: Behaviour, partId: string): string | undefined {\n return Object.hasOwn(behaviour.parts, partId) ? behaviour.parts[partId] : undefined\n}\n\n/** The text property a text value is bound to, if any. */\nexport function textBinding(behaviour: Behaviour, valueId: string): string | undefined {\n return Object.hasOwn(behaviour.texts, valueId) ? behaviour.texts[valueId].propertyId : undefined\n}\n\n/** A number value's range, if the behaviour has one. */\nexport function numberSettings(\n behaviour: Behaviour,\n valueId: string\n): BehaviourNumberSettings | undefined {\n return Object.hasOwn(behaviour.numbers, valueId) ? behaviour.numbers[valueId] : undefined\n}\n\n/** A new behaviour of a kind, its number values at their defaults and nothing bound. */\nexport function emptyBehaviour(kind: BehaviourKind): Behaviour {\n const contract = behaviourContract(kind)\n const numbers = Object.fromEntries(\n contract.values\n .filter((value) => value.type === 'number')\n .map((value) => [value.id, { ...DEFAULT_NUMBER_SETTINGS }])\n )\n return { kind, booleans: {}, texts: {}, numbers, parts: {} }\n}\n\n/**\n * The node that keeps the behaviour: a component set for its variants, otherwise the main\n * component itself.\n */\nexport function behaviourOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n if (node.type === 'COMPONENT_SET') return node\n if (node.type !== 'COMPONENT') return undefined\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n return parent?.type === 'COMPONENT_SET' ? parent : node\n}\n\n/** The behaviour a component or component set keeps, or null when it has none or it is unreadable. */\nexport function readBehaviour(owner: SceneNode): Behaviour | null {\n return readPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour) ?? null\n}\n\n/** The owner's plugin data with the behaviour set, or removed when null. */\nexport function withBehaviour(\n owner: SceneNode,\n behaviour: Behaviour | null\n): SceneNode['pluginData'] {\n return withPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour, behaviour ?? undefined)\n}\n\n/** Component properties the behaviour can bind to: the owner's, and a set's variants' own. */\nexport function behaviourProperties(\n graph: SceneGraph,\n owner: SceneNode\n): ComponentPropertyDefinition[] {\n const variants =\n owner.type === 'COMPONENT_SET'\n ? owner.childIds.flatMap((id) => graph.getNode(id)?.componentPropertyDefinitions ?? [])\n : []\n const seen = new Set<string>()\n return [...owner.componentPropertyDefinitions, ...variants].filter((definition) => {\n if (seen.has(definition.id)) return false\n seen.add(definition.id)\n return true\n })\n}\n\n/**\n * Required values and parts that are unbound, or bound to a property the component no longer\n * has, by value or part id; `states` when the interaction states lost their variant property.\n */\nexport function missingBindings(\n graph: SceneGraph,\n owner: SceneNode,\n behaviour: Behaviour\n): string[] {\n const contract = behaviourContract(behaviour.kind)\n const properties = new Map(\n behaviourProperties(graph, owner).map((definition) => [definition.id, definition])\n )\n const bound = (propertyId: string | undefined, type: ComponentPropertyDefinition['type'][]) => {\n const definition = propertyId ? properties.get(propertyId) : undefined\n return !!definition && type.includes(definition.type)\n }\n const values = contract.values\n .filter((value) => value.required)\n .filter((value) =>\n value.type === 'text'\n ? !bound(textBinding(behaviour, value.id), ['TEXT'])\n : value.type === 'boolean' &&\n !bound(booleanBinding(behaviour, value.id)?.propertyId, ['VARIANT', 'BOOLEAN'])\n )\n .map((value) => value.id)\n const parts = contract.parts\n .filter((part) => part.required && !bound(partBinding(behaviour, part.id), ['SLOT']))\n .map((part) => part.id)\n const states =\n behaviour.states && !bound(behaviour.states.propertyId, ['VARIANT']) ? ['states'] : []\n return [...values, ...parts, ...states]\n}\n\n/** Variant value names that usually mean each interaction state, compared case-insensitively. */\nconst STATE_NAMES: Record<InteractionState, readonly string[]> = {\n rest: ['default', 'rest', 'idle', 'normal', 'enabled'],\n hover: ['hover', 'hovered', 'hovering'],\n pressed: ['pressed', 'active', 'down', 'pressing'],\n focus: ['focus', 'focused', 'focus visible', 'focus-visible'],\n disabled: ['disabled', 'inactive']\n}\n\n/**\n * Interaction states for a variant property, each mapped to the value whose name means it, such\n * as `Hover` or `Pressed`; states without such a value are left unset.\n */\nexport function guessInteractionStates(\n propertyId: string,\n values: readonly string[]\n): BehaviourInteractionStates {\n const states: BehaviourInteractionStates = { propertyId }\n for (const state of INTERACTION_STATES) {\n const match = values.find((value) => STATE_NAMES[state].includes(value.trim().toLowerCase()))\n if (match) states[state] = match\n }\n return states\n}\n\n/**\n * The behaviour with every component property id it binds renamed by `rename`, for formats that\n * give properties new ids on write, such as `.fig` with its GUIDs.\n */\nexport function renameBehaviourProperties(\n behaviour: Behaviour,\n rename: (propertyId: string) => string\n): Behaviour {\n const mapValues = <T>(record: Record<string, T>, change: (value: T) => T) =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, change(value)]))\n return {\n ...behaviour,\n booleans: mapValues(behaviour.booleans, (binding) => ({\n ...binding,\n propertyId: rename(binding.propertyId)\n })),\n texts: mapValues(behaviour.texts, (binding) => ({ propertyId: rename(binding.propertyId) })),\n parts: mapValues(behaviour.parts, rename),\n ...(behaviour.states\n ? { states: { ...behaviour.states, propertyId: rename(behaviour.states.propertyId) } }\n : {})\n }\n}\n","import type { SceneGraph } from '../index'\nimport type { SceneNode } from '../types'\nimport { behaviourOwner, readBehaviour } from './model'\n\n/** Whether an instance's main component, or its set, has a behaviour. */\nexport function hasBehaviour(graph: SceneGraph, node: SceneNode): boolean {\n if (node.type !== 'INSTANCE' || !node.componentId) return false\n const component = graph.getNode(node.componentId)\n const owner = component && behaviourOwner(graph, component)\n return !!owner && !!readBehaviour(owner)\n}\n\n/** A name as a path segment: `/` separates segments and `#` the twin index, so both are escaped. */\nconst pathName = (name: string) => name.replace(/[%/#]/g, (char) => encodeURIComponent(char))\n\n/**\n * A layer's path below a root: the names of the layers down to it, with the position among\n * same-named siblings when names repeat. It stays the same when a variant switch rebuilds an\n * instance's layers, so it identifies controls and keeps their DOM in place.\n */\nexport function layerPath(graph: SceneGraph, rootId: string, nodeId: string): string {\n const segments: string[] = []\n // `closest` stops on a parent cycle in bad data, where a hand-written walk would not.\n graph.closest(nodeId, (node) => {\n if (node.id === rootId) return true\n const twins = node.parentId\n ? graph.getChildren(node.parentId).filter((child) => child.name === node.name)\n : []\n const index = twins.findIndex((child) => child.id === node.id)\n segments.unshift(twins.length > 1 ? `${pathName(node.name)}#${index}` : pathName(node.name))\n return false\n })\n return segments.join('/')\n}\n\n/** The layer at `path` below a root, the inverse of `layerPath`. */\nexport function findLayerByPath(\n graph: SceneGraph,\n rootId: string,\n path: string\n): SceneNode | undefined {\n let current = graph.getNode(rootId)\n for (const segment of path ? path.split('/') : []) {\n if (!current) return undefined\n const hash = segment.lastIndexOf('#')\n const name = hash === -1 ? segment : segment.slice(0, hash)\n const twins = graph.getChildren(current.id).filter((child) => pathName(child.name) === name)\n current = twins.at(hash === -1 ? 0 : Number(segment.slice(hash + 1)))\n }\n return current\n}\n"],"mappings":";;;;AAKA,MAAa,wBAAwB;;;;;AA6BrC,SAAgB,oBACd,KACA,MACA,QACoB;CACpB,MAAM,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,MAAM;CACvD,OAAO;EACL;EACA;EACA,OAAO,OAAO;GACZ,MAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;GACxC,OAAO,OAAO,UAAU,OAAO,SAAS,KAAA;EAC1C;EACA,SAAS,UAAU,KAAK,UAAU,KAAK;CACzC;AACF;;AAGA,SAAgB,oBACd,KACA,MACA,QACoB;CACpB,MAAM,SAAS,EAAE,SAAS,MAAM;CAChC,OAAO;EACL;EACA;EACA,OAAO,OAAO;GACZ,MAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;GACxC,OAAO,OAAO,UAAU,OAAO,SAAS,KAAA;EAC1C;EACA,SAAS,UAAU;CACrB;AACF;AAEA,SAAgB,kBAAkB,OAAwB,OAA+B;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AAmB,IAAI,CAAC;;;;;;AAO5F,SAAgB,UAAU,OAAmB,QAAgB,QAAwB;CACnF,MAAM,WAAqB,CAAC;CAE5B,MAAM,QAAQ,SAAS,SAAS;EAC9B,IAAI,KAAK,OAAO,QAAQ,OAAO;EAC/B,MAAM,QAAQ,KAAK,WACf,MAAM,YAAY,KAAK,QAAQ,CAAC,CAAC,QAAQ,UAAU,MAAM,SAAS,KAAK,IAAI,IAC3E,CAAC;EACL,MAAM,QAAQ,MAAM,WAAW,UAAU,MAAM,OAAO,KAAK,EAAE;EAC7D,SAAS,QAAQ,MAAM,SAAS,IAAI,GAAG,SAAS,KAAK,IAAI,EAAE,GAAG,UAAU,SAAS,KAAK,IAAI,CAAC;EAC3F,OAAO;CACT,CAAC;CACD,OAAO,SAAS,KAAK,GAAG;AAC1B;;AAGA,SAAgB,gBACd,OACA,QACA,MACuB;CACvB,IAAI,UAAU,MAAM,QAAQ,MAAM;CAClC,KAAK,MAAM,WAAW,OAAO,KAAK,MAAM,GAAG,IAAI,CAAC,GAAG;EACjD,IAAI,CAAC,SAAS,OAAO,KAAA;EACrB,MAAM,OAAO,QAAQ,YAAY,GAAG;EACpC,MAAM,OAAO,SAAS,KAAK,UAAU,QAAQ,MAAM,GAAG,IAAI;EAE1D,UADc,MAAM,YAAY,QAAQ,EAAE,CAAC,CAAC,QAAQ,UAAU,SAAS,MAAM,IAAI,MAAM,IACzE,CAAC,CAAC,GAAG,SAAS,KAAK,IAAI,OAAO,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC;CACtE;CACA,OAAO;AACT"}
|
|
@@ -47,11 +47,33 @@ function contrastRatio(a, b) {
|
|
|
47
47
|
b: b.b
|
|
48
48
|
});
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* `background` darkened just enough for light `text` to reach `ratio` on it, by scaling its
|
|
52
|
+
* channels toward black, which keeps its hue; returned as it is when the text already does.
|
|
53
|
+
* The default is white text at WCAG AA's 4.5:1 for normal text.
|
|
54
|
+
*/
|
|
55
|
+
function darkenForContrast(background, text = WHITE, ratio = 4.5) {
|
|
56
|
+
if (contrastRatio(background, text) >= ratio) return background;
|
|
57
|
+
const scaled = (factor) => ({
|
|
58
|
+
...background,
|
|
59
|
+
r: background.r * factor,
|
|
60
|
+
g: background.g * factor,
|
|
61
|
+
b: background.b * factor
|
|
62
|
+
});
|
|
63
|
+
let enough = 0;
|
|
64
|
+
let short = 1;
|
|
65
|
+
for (let step = 0; step < 20; step++) {
|
|
66
|
+
const middle = (enough + short) / 2;
|
|
67
|
+
if (contrastRatio(scaled(middle), text) >= ratio) enough = middle;
|
|
68
|
+
else short = middle;
|
|
69
|
+
}
|
|
70
|
+
return scaled(enough);
|
|
71
|
+
}
|
|
50
72
|
/** Black or white, whichever reads better on an opaque `background`. */
|
|
51
73
|
function readableForeground(background) {
|
|
52
74
|
return contrastRatio(background, BLACK) >= contrastRatio(background, WHITE) ? BLACK : WHITE;
|
|
53
75
|
}
|
|
54
76
|
//#endregion
|
|
55
|
-
export { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT, DEFAULT_STROKE_WEIGHT, TRANSPARENT, WHITE, compositeOver, contrastRatio, readableForeground };
|
|
77
|
+
export { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT, DEFAULT_STROKE_WEIGHT, TRANSPARENT, WHITE, compositeOver, contrastRatio, darkenForContrast, readableForeground };
|
|
56
78
|
|
|
57
79
|
//# sourceMappingURL=contrast.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contrast.js","names":[],"sources":["../../../src/constants.ts","../../../src/color/contrast.ts"],"sourcesContent":["import type { Color } from './primitives'\n\nexport const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }\nexport const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }\nexport const TRANSPARENT: Color = { r: 0, g: 0, b: 0, a: 0 }\nexport const DEFAULT_FONT_FAMILY = 'Inter'\nexport const DEFAULT_STROKE_MITER_LIMIT = 4\nexport const DEFAULT_STROKE_WEIGHT = 1\n","import { wcagContrast } from 'culori'\n\nimport { BLACK, WHITE } from '../constants'\nimport type { Color } from '../primitives'\n\n/** Opaque color seen when `foreground` at `alpha` is drawn over an opaque `background`. */\nexport function compositeOver(foreground: Color, background: Color, alpha = foreground.a): Color {\n const mix = (top: number, bottom: number) => top * alpha + bottom * (1 - alpha)\n return {\n r: mix(foreground.r, background.r),\n g: mix(foreground.g, background.g),\n b: mix(foreground.b, background.b),\n a: 1\n }\n}\n\n/** WCAG 2 contrast ratio of two colors, from 1 to 21; alpha is ignored, so composite first. */\nexport function contrastRatio(\n a: Pick<Color, 'r' | 'g' | 'b'>,\n b: Pick<Color, 'r' | 'g' | 'b'>\n): number {\n return wcagContrast(\n { mode: 'rgb', r: a.r, g: a.g, b: a.b },\n { mode: 'rgb', r: b.r, g: b.g, b: b.b }\n )\n}\n\n/** Black or white, whichever reads better on an opaque `background`. */\nexport function readableForeground(background: Pick<Color, 'r' | 'g' | 'b'>): Color {\n return contrastRatio(background, BLACK) >= contrastRatio(background, WHITE) ? BLACK : WHITE\n}\n"],"mappings":";;AAEA,MAAa,QAAe;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AACrD,MAAa,QAAe;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AACrD,MAAa,cAAqB;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AAC3D,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAC1C,MAAa,wBAAwB;;;;ACDrC,SAAgB,cAAc,YAAmB,YAAmB,QAAQ,WAAW,GAAU;CAC/F,MAAM,OAAO,KAAa,WAAmB,MAAM,QAAQ,UAAU,IAAI;CACzE,OAAO;EACL,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC;EACjC,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC;EACjC,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC;EACjC,GAAG;CACL;AACF;;AAGA,SAAgB,cACd,GACA,GACQ;CACR,OAAO,aACL;EAAE,MAAM;EAAO,GAAG,EAAE;EAAG,GAAG,EAAE;EAAG,GAAG,EAAE;CAAE,GACtC;EAAE,MAAM;EAAO,GAAG,EAAE;EAAG,GAAG,EAAE;EAAG,GAAG,EAAE;CAAE,CACxC;AACF;;AAGA,SAAgB,mBAAmB,YAAiD;CAClF,OAAO,cAAc,YAAY,KAAK,KAAK,cAAc,YAAY,KAAK,IAAI,QAAQ;AACxF"}
|
|
1
|
+
{"version":3,"file":"contrast.js","names":[],"sources":["../../../src/constants.ts","../../../src/color/contrast.ts"],"sourcesContent":["import type { Color } from './primitives'\n\nexport const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }\nexport const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }\nexport const TRANSPARENT: Color = { r: 0, g: 0, b: 0, a: 0 }\nexport const DEFAULT_FONT_FAMILY = 'Inter'\nexport const DEFAULT_STROKE_MITER_LIMIT = 4\nexport const DEFAULT_STROKE_WEIGHT = 1\n","import { wcagContrast } from 'culori'\n\nimport { BLACK, WHITE } from '../constants'\nimport type { Color } from '../primitives'\n\n/** Opaque color seen when `foreground` at `alpha` is drawn over an opaque `background`. */\nexport function compositeOver(foreground: Color, background: Color, alpha = foreground.a): Color {\n const mix = (top: number, bottom: number) => top * alpha + bottom * (1 - alpha)\n return {\n r: mix(foreground.r, background.r),\n g: mix(foreground.g, background.g),\n b: mix(foreground.b, background.b),\n a: 1\n }\n}\n\n/** WCAG 2 contrast ratio of two colors, from 1 to 21; alpha is ignored, so composite first. */\nexport function contrastRatio(\n a: Pick<Color, 'r' | 'g' | 'b'>,\n b: Pick<Color, 'r' | 'g' | 'b'>\n): number {\n return wcagContrast(\n { mode: 'rgb', r: a.r, g: a.g, b: a.b },\n { mode: 'rgb', r: b.r, g: b.g, b: b.b }\n )\n}\n\n/**\n * `background` darkened just enough for light `text` to reach `ratio` on it, by scaling its\n * channels toward black, which keeps its hue; returned as it is when the text already does.\n * The default is white text at WCAG AA's 4.5:1 for normal text.\n */\nexport function darkenForContrast(\n background: Color,\n text: Pick<Color, 'r' | 'g' | 'b'> = WHITE,\n ratio = 4.5\n): Color {\n if (contrastRatio(background, text) >= ratio) return background\n const scaled = (factor: number): Color => ({\n ...background,\n r: background.r * factor,\n g: background.g * factor,\n b: background.b * factor\n })\n // Darker always contrasts more with light text, so the smallest darkening is found by halving.\n let enough = 0\n let short = 1\n for (let step = 0; step < 20; step++) {\n const middle = (enough + short) / 2\n if (contrastRatio(scaled(middle), text) >= ratio) enough = middle\n else short = middle\n }\n return scaled(enough)\n}\n\n/** Black or white, whichever reads better on an opaque `background`. */\nexport function readableForeground(background: Pick<Color, 'r' | 'g' | 'b'>): Color {\n return contrastRatio(background, BLACK) >= contrastRatio(background, WHITE) ? BLACK : WHITE\n}\n"],"mappings":";;AAEA,MAAa,QAAe;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AACrD,MAAa,QAAe;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AACrD,MAAa,cAAqB;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AAC3D,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAC1C,MAAa,wBAAwB;;;;ACDrC,SAAgB,cAAc,YAAmB,YAAmB,QAAQ,WAAW,GAAU;CAC/F,MAAM,OAAO,KAAa,WAAmB,MAAM,QAAQ,UAAU,IAAI;CACzE,OAAO;EACL,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC;EACjC,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC;EACjC,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC;EACjC,GAAG;CACL;AACF;;AAGA,SAAgB,cACd,GACA,GACQ;CACR,OAAO,aACL;EAAE,MAAM;EAAO,GAAG,EAAE;EAAG,GAAG,EAAE;EAAG,GAAG,EAAE;CAAE,GACtC;EAAE,MAAM;EAAO,GAAG,EAAE;EAAG,GAAG,EAAE;EAAG,GAAG,EAAE;CAAE,CACxC;AACF;;;;;;AAOA,SAAgB,kBACd,YACA,OAAqC,OACrC,QAAQ,KACD;CACP,IAAI,cAAc,YAAY,IAAI,KAAK,OAAO,OAAO;CACrD,MAAM,UAAU,YAA2B;EACzC,GAAG;EACH,GAAG,WAAW,IAAI;EAClB,GAAG,WAAW,IAAI;EAClB,GAAG,WAAW,IAAI;CACpB;CAEA,IAAI,SAAS;CACb,IAAI,QAAQ;CACZ,KAAK,IAAI,OAAO,GAAG,OAAO,IAAI,QAAQ;EACpC,MAAM,UAAU,SAAS,SAAS;EAClC,IAAI,cAAc,OAAO,MAAM,GAAG,IAAI,KAAK,OAAO,SAAS;OACtD,QAAQ;CACf;CACA,OAAO,OAAO,MAAM;AACtB;;AAGA,SAAgB,mBAAmB,YAAiD;CAClF,OAAO,cAAc,YAAY,KAAK,KAAK,cAAc,YAAY,KAAK,IAAI,QAAQ;AACxF"}
|
|
@@ -122,17 +122,53 @@ function polygonVertices(node) {
|
|
|
122
122
|
};
|
|
123
123
|
});
|
|
124
124
|
}
|
|
125
|
-
function strokeOverflow(strokes, fallbackCap, network) {
|
|
125
|
+
function strokeOverflow(strokes, fallbackCap, network, corners) {
|
|
126
126
|
let overflow = 0;
|
|
127
127
|
for (const stroke of strokes ?? []) {
|
|
128
128
|
if (!stroke.visible) continue;
|
|
129
129
|
let extra = 0;
|
|
130
130
|
if (stroke.align === "OUTSIDE") extra = stroke.weight;
|
|
131
131
|
else if (stroke.align === "CENTER") extra = stroke.weight / 2;
|
|
132
|
-
|
|
132
|
+
const miter = network ? miterRatio(network, stroke.join ?? corners?.strokeJoin, corners?.strokeMiterLimit) : 1;
|
|
133
|
+
overflow = Math.max(overflow, extra * miter);
|
|
133
134
|
}
|
|
134
135
|
return Math.max(overflow, arrowCapOverflow(strokes, fallbackCap, network));
|
|
135
136
|
}
|
|
137
|
+
/** The direction a segment leaves `vertex` in, along its handle when it has one. */
|
|
138
|
+
function leaving(network, index, vertex) {
|
|
139
|
+
const segment = network.segments[index];
|
|
140
|
+
const atStart = segment.start === vertex;
|
|
141
|
+
const handle = atStart ? segment.tangentStart : segment.tangentEnd;
|
|
142
|
+
if (handle.x !== 0 || handle.y !== 0) return handle;
|
|
143
|
+
const from = network.vertices[vertex];
|
|
144
|
+
const to = network.vertices[atStart ? segment.end : segment.start];
|
|
145
|
+
return {
|
|
146
|
+
x: to.x - from.x,
|
|
147
|
+
y: to.y - from.y
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* How far past half the stroke the sharpest mitered corner reaches, as a multiple: a corner of
|
|
152
|
+
* angle θ mitres out to 1/sin(θ/2), unless that passes the miter limit and it bevels instead.
|
|
153
|
+
* Corners are the vertices exactly two segments meet at, as the stroke joins them.
|
|
154
|
+
*/
|
|
155
|
+
function miterRatio(network, join, limit = 4) {
|
|
156
|
+
const meeting = /* @__PURE__ */ new Map();
|
|
157
|
+
for (const [index, segment] of network.segments.entries()) for (const vertex of /* @__PURE__ */ new Set([segment.start, segment.end])) meeting.set(vertex, [...meeting.get(vertex) ?? [], index]);
|
|
158
|
+
let ratio = 1;
|
|
159
|
+
for (const [vertex, indices] of meeting) {
|
|
160
|
+
if (indices.length !== 2) continue;
|
|
161
|
+
if ((network.vertices[vertex].strokeJoin ?? join ?? "MITER") !== "MITER") continue;
|
|
162
|
+
const a = leaving(network, indices[0], vertex);
|
|
163
|
+
const b = leaving(network, indices[1], vertex);
|
|
164
|
+
const lengths = Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y);
|
|
165
|
+
if (lengths === 0) continue;
|
|
166
|
+
const angle = Math.acos(Math.max(-1, Math.min(1, (a.x * b.x + a.y * b.y) / lengths)));
|
|
167
|
+
const miter = 1 / Math.sin(angle / 2);
|
|
168
|
+
if (miter <= limit) ratio = Math.max(ratio, miter);
|
|
169
|
+
}
|
|
170
|
+
return ratio;
|
|
171
|
+
}
|
|
136
172
|
function effectOverflow(effects) {
|
|
137
173
|
let left = 0;
|
|
138
174
|
let right = 0;
|
|
@@ -172,7 +208,7 @@ function computeVisualBounds(nodes, getAbsolutePosition) {
|
|
|
172
208
|
for (const n of nodes) {
|
|
173
209
|
const abs = getAbsolutePosition(n.id);
|
|
174
210
|
const bbox = rotatedBBox(abs.x, abs.y, n.width, n.height, n.rotation ?? 0);
|
|
175
|
-
const stroke = strokeOverflow(n.strokes, n.strokeCap, n.vectorNetwork);
|
|
211
|
+
const stroke = strokeOverflow(n.strokes, n.strokeCap, n.vectorNetwork, n);
|
|
176
212
|
const effects = effectOverflow(n.effects);
|
|
177
213
|
includePoint(bounds, bbox.left - stroke - effects.left, bbox.top - stroke - effects.top);
|
|
178
214
|
includePoint(bounds, bbox.right + stroke + effects.right, bbox.bottom + stroke + effects.bottom);
|
|
@@ -1006,7 +1042,7 @@ function copyEffect(e) {
|
|
|
1006
1042
|
};
|
|
1007
1043
|
}
|
|
1008
1044
|
function copyStyleRun(r) {
|
|
1009
|
-
|
|
1045
|
+
const copy = {
|
|
1010
1046
|
...r,
|
|
1011
1047
|
style: {
|
|
1012
1048
|
...r.style,
|
|
@@ -1016,6 +1052,9 @@ function copyStyleRun(r) {
|
|
|
1016
1052
|
fontFeatures: r.style.fontFeatures ? r.style.fontFeatures.map((v) => ({ ...v })) : void 0
|
|
1017
1053
|
}
|
|
1018
1054
|
};
|
|
1055
|
+
if (r.style.hyperlink) copy.style.hyperlink = { ...r.style.hyperlink };
|
|
1056
|
+
if (r.style.boundVariables) copy.style.boundVariables = { ...r.style.boundVariables };
|
|
1057
|
+
return copy;
|
|
1019
1058
|
}
|
|
1020
1059
|
const internalCopySources = /* @__PURE__ */ new WeakMap();
|
|
1021
1060
|
/** Record immutable lineage for an internal deep copy without sharing mutable values. */
|