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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +607 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +577 -522
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2291 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/group-bounds.js +104 -0
  34. package/dist/chunks/group-bounds.js.map +1 -0
  35. package/dist/chunks/icons/glyph.js +147 -0
  36. package/dist/chunks/icons/glyph.js.map +1 -0
  37. package/dist/chunks/index.js +1724 -663
  38. package/dist/chunks/index.js.map +1 -1
  39. package/dist/color.d.ts +72 -0
  40. package/dist/color.d.ts.map +1 -0
  41. package/dist/color.js +3 -0
  42. package/dist/constants.d.ts +2 -2
  43. package/dist/constants.js +2 -2
  44. package/dist/constants2.d.ts +3 -1
  45. package/dist/constants2.d.ts.map +1 -1
  46. package/dist/coordinate.d.ts +2 -448
  47. package/dist/coordinate.js +2 -2
  48. package/dist/copy.d.ts +1 -1
  49. package/dist/copy.js +1 -1
  50. package/dist/css.d.ts +39 -0
  51. package/dist/css.d.ts.map +1 -0
  52. package/dist/css.js +3 -0
  53. package/dist/geometry.d.ts +1 -1
  54. package/dist/geometry.js +1 -1
  55. package/dist/gradient.d.ts +51 -0
  56. package/dist/gradient.d.ts.map +1 -0
  57. package/dist/gradient.js +132 -0
  58. package/dist/gradient.js.map +1 -0
  59. package/dist/guides.d.ts +2 -2
  60. package/dist/guides.js +39 -0
  61. package/dist/guides.js.map +1 -0
  62. package/dist/hit-test.d.ts +2 -9
  63. package/dist/hit-test.js +176 -34
  64. package/dist/hit-test.js.map +1 -1
  65. package/dist/index.d.ts +4 -8
  66. package/dist/index.js +19 -5
  67. package/dist/instances.d.ts +2 -2
  68. package/dist/instances.js +2 -2
  69. package/dist/layout.d.ts +2 -0
  70. package/dist/layout.js +4 -0
  71. package/dist/node-defaults.d.ts +2 -8
  72. package/dist/node-defaults.js +2 -2
  73. package/dist/order-keys.d.ts +39 -0
  74. package/dist/order-keys.d.ts.map +1 -0
  75. package/dist/order-keys.js +136 -0
  76. package/dist/order-keys.js.map +1 -0
  77. package/dist/parse-path.d.ts +7 -1
  78. package/dist/parse-path.d.ts.map +1 -1
  79. package/dist/parse-path.js +6 -2
  80. package/dist/parse-path.js.map +1 -1
  81. package/dist/polygon.d.ts +53 -0
  82. package/dist/polygon.d.ts.map +1 -0
  83. package/dist/polygon.js +205 -0
  84. package/dist/polygon.js.map +1 -0
  85. package/dist/preview.d.ts +1 -1
  86. package/dist/random.d.ts +7 -0
  87. package/dist/random.d.ts.map +1 -0
  88. package/dist/random.js +2 -0
  89. package/dist/resize.d.ts +11 -2
  90. package/dist/resize.d.ts.map +1 -1
  91. package/dist/resize.js +2 -184
  92. package/dist/snap.d.ts +1 -1
  93. package/dist/text-direction.d.ts +13 -0
  94. package/dist/text-direction.d.ts.map +1 -0
  95. package/dist/text-direction.js +31 -0
  96. package/dist/text-direction.js.map +1 -0
  97. package/dist/text-picture.d.ts +1 -1
  98. package/dist/text-picture.d.ts.map +1 -1
  99. package/dist/text.d.ts +2 -0
  100. package/dist/text.js +3 -0
  101. package/dist/types.d.ts +2121 -15
  102. package/dist/types.d.ts.map +1 -1
  103. package/dist/types.js +2 -1
  104. package/dist/types2.d.ts +2 -2
  105. package/dist/undo.d.ts +2 -2
  106. package/dist/undo.js +2 -2
  107. package/dist/undo2.d.ts +29 -1
  108. package/dist/undo2.d.ts.map +1 -1
  109. package/dist/variables.d.ts +2 -29
  110. package/dist/variables.js +2 -2
  111. package/dist/variant-properties.d.ts +9 -1
  112. package/dist/variant-properties.d.ts.map +1 -1
  113. package/dist/variant-properties.js +36 -1
  114. package/dist/variant-properties.js.map +1 -1
  115. package/dist/vector-network.d.ts +1 -1
  116. package/dist/vector-network.js +1 -1
  117. package/package.json +60 -9
  118. package/src/behaviours/kinds.ts +185 -0
  119. package/src/behaviours/layers.ts +51 -0
  120. package/src/behaviours/model.ts +192 -0
  121. package/src/behaviours/schema.ts +58 -0
  122. package/src/behaviours/spec.ts +223 -0
  123. package/src/buffered-events.ts +64 -0
  124. package/src/color/contrast.ts +31 -0
  125. package/src/color/index.ts +88 -0
  126. package/src/color/management.ts +210 -0
  127. package/src/color/normalize.ts +7 -0
  128. package/src/color/okhcl.ts +201 -0
  129. package/src/comments/document.ts +51 -0
  130. package/src/comments/list.ts +52 -0
  131. package/src/comments/merge.ts +63 -0
  132. package/src/comments/threads.ts +156 -0
  133. package/src/components/exposure.ts +61 -0
  134. package/src/components/properties.ts +18 -15
  135. package/src/components/variants.ts +53 -0
  136. package/src/constants.ts +2 -0
  137. package/src/coordinate.ts +100 -43
  138. package/src/copy.ts +17 -6
  139. package/src/css/grid.ts +70 -0
  140. package/src/css/index.ts +9 -0
  141. package/src/css/layout.ts +53 -0
  142. package/src/css/shadows.ts +68 -0
  143. package/src/css/values.ts +42 -0
  144. package/src/export-format.ts +12 -0
  145. package/src/fields/geometry.ts +11 -0
  146. package/src/fields/text.ts +35 -0
  147. package/src/gradient.ts +166 -0
  148. package/src/group-bounds.ts +131 -0
  149. package/src/guides.ts +39 -0
  150. package/src/hit-test.ts +262 -46
  151. package/src/icons/glyph.ts +128 -0
  152. package/src/icons/model.ts +54 -0
  153. package/src/icons/schema.ts +18 -0
  154. package/src/index.ts +347 -57
  155. package/src/instance-overrides.ts +27 -0
  156. package/src/instances/content-size.ts +58 -0
  157. package/src/instances/copies.ts +239 -0
  158. package/src/instances/cycles.ts +73 -0
  159. package/src/instances/fields.ts +143 -0
  160. package/src/instances/main-component.ts +19 -0
  161. package/src/instances/placement.ts +29 -0
  162. package/src/instances/source-walk.ts +41 -0
  163. package/src/instances/sync.ts +600 -0
  164. package/src/instances/vector-geometry.ts +81 -0
  165. package/src/instances.ts +125 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +41 -12
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/shared-styles.ts +5 -2
  187. package/src/slots/authoring.ts +101 -0
  188. package/src/slots/content.ts +124 -0
  189. package/src/slots/frames.ts +160 -0
  190. package/src/slots/limits.ts +49 -0
  191. package/src/text/direction.ts +55 -0
  192. package/src/text/index.ts +3 -0
  193. package/src/text/lists.ts +138 -0
  194. package/src/text/paragraphs.ts +241 -0
  195. package/src/{text-picture.ts → text/picture.ts} +21 -29
  196. package/src/text/references.ts +50 -0
  197. package/src/transfer/apply.ts +84 -0
  198. package/src/transfer/history.ts +49 -0
  199. package/src/transfer/identity.ts +16 -0
  200. package/src/transfer/index.ts +6 -0
  201. package/src/transfer/nodes.ts +120 -0
  202. package/src/transfer/plan.ts +130 -0
  203. package/src/transfer/references.ts +9 -0
  204. package/src/transfer/remove.ts +39 -0
  205. package/src/transfer/validation.ts +59 -0
  206. package/src/transfer/variables.ts +82 -0
  207. package/src/types.ts +257 -13
  208. package/src/undo.ts +54 -2
  209. package/src/variables/bindings.ts +224 -0
  210. package/src/variables/fields.ts +43 -0
  211. package/src/variables/token.ts +14 -0
  212. package/src/variables/units.ts +15 -0
  213. package/src/variables.ts +118 -69
  214. package/src/variant-properties.ts +50 -0
  215. package/dist/chunks/components/properties.js.map +0 -1
  216. package/dist/chunks/export-scale.js +0 -19
  217. package/dist/chunks/export-scale.js.map +0 -1
  218. package/dist/coordinate.d.ts.map +0 -1
  219. package/dist/coordinate2.d.ts +0 -2
  220. package/dist/guides2.d.ts +0 -11
  221. package/dist/guides2.d.ts.map +0 -1
  222. package/dist/hit-test.d.ts.map +0 -1
  223. package/dist/layout-guides.d.ts +0 -2
  224. package/dist/layout-guides.js +0 -2
  225. package/dist/layout-guides2.d.ts +0 -16
  226. package/dist/layout-guides2.d.ts.map +0 -1
  227. package/dist/node-defaults.d.ts.map +0 -1
  228. package/dist/preview2.d.ts +0 -12
  229. package/dist/preview2.d.ts.map +0 -1
  230. package/dist/resize.js.map +0 -1
  231. package/dist/variables.d.ts.map +0 -1
  232. package/dist/vector-network2.d.ts +0 -32
  233. package/dist/vector-network2.d.ts.map +0 -1
  234. package/src/instance-overrides.test.ts +0 -67
@@ -0,0 +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 /** `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}\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,SAA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behaviourContract } from "./kinds.js";
3
+ import { omitBy } from "es-toolkit/object";
4
+ import * as v from "valibot";
5
+ //#region src/behaviours/spec.ts
6
+ /**
7
+ * A behaviour as scripts, tools, and JSX write it: component properties and slots by name, not
8
+ * by id. Values are boolean or text values by their contract id; numbers are a slider's or
9
+ * number field's own range.
10
+ */
11
+ const behaviourSpecSchema = v.object({
12
+ kind: v.picklist(BEHAVIOUR_KINDS),
13
+ values: v.optional(v.record(v.string(), v.union([v.string(), v.object({
14
+ property: v.string(),
15
+ on: v.optional(v.string()),
16
+ off: v.optional(v.string())
17
+ })]))),
18
+ numbers: v.optional(v.record(v.string(), v.object({
19
+ min: v.optional(v.number()),
20
+ max: v.optional(v.number()),
21
+ step: v.optional(v.number()),
22
+ default: v.optional(v.number())
23
+ }))),
24
+ parts: v.optional(v.record(v.string(), v.string())),
25
+ states: v.optional(v.union([v.string(), v.object({
26
+ property: v.string(),
27
+ ...interactionStateValues
28
+ })]))
29
+ });
30
+ /** Variant values that usually mean on, compared case-insensitively. */
31
+ const ON_NAMES = [
32
+ "on",
33
+ "true",
34
+ "yes",
35
+ "checked",
36
+ "pressed",
37
+ "open",
38
+ "selected",
39
+ "active"
40
+ ];
41
+ const OFF_NAMES = [
42
+ "off",
43
+ "false",
44
+ "no",
45
+ "unchecked",
46
+ "closed",
47
+ "default",
48
+ "inactive"
49
+ ];
50
+ function named(names, options) {
51
+ return options.find((option) => names.includes(option.trim().toLowerCase()));
52
+ }
53
+ /**
54
+ * The variant values that likely mean on and off: names such as On, True, or Checked first,
55
+ * then the values in order.
56
+ */
57
+ function guessOnOff(options, explicit = {}) {
58
+ const on = explicit.on ?? named(ON_NAMES, options) ?? options[0];
59
+ return {
60
+ on,
61
+ off: explicit.off ?? named(OFF_NAMES, options) ?? options.find((option) => option !== on)
62
+ };
63
+ }
64
+ function findProperty(properties, name, types, what) {
65
+ const found = properties.find((item) => item.name === name && types.includes(item.type));
66
+ if (found) return found;
67
+ const available = properties.filter((item) => types.includes(item.type)).map((item) => item.name);
68
+ throw new Error(`${what} needs a ${types.join(" or ")} property named "${name}"; the component has ${available.length ? available.map((item) => `"${item}"`).join(", ") : "none"}`);
69
+ }
70
+ function listed(items) {
71
+ return items.map((item) => `"${item.id}"`).join(", ");
72
+ }
73
+ /** Bind a boolean or text value to the property named in its binding. */
74
+ function resolveValue(behaviour, properties, valueId, binding) {
75
+ const bindable = behaviourContract(behaviour.kind).values.filter((item) => item.type === "boolean" || item.type === "text");
76
+ const value = bindable.find((item) => item.id === valueId);
77
+ if (!value) throw new Error(`A ${behaviour.kind} has no boolean or text value "${valueId}"; it has ${listed(bindable)}`);
78
+ const name = typeof binding === "string" ? binding : binding.property;
79
+ if (value.type === "text") {
80
+ behaviour.texts[valueId] = { propertyId: findProperty(properties, name, ["TEXT"], valueId).id };
81
+ return;
82
+ }
83
+ const definition = findProperty(properties, name, ["VARIANT", "BOOLEAN"], valueId);
84
+ if (definition.type === "BOOLEAN") {
85
+ behaviour.booleans[valueId] = { propertyId: definition.id };
86
+ return;
87
+ }
88
+ const options = definition.variantOptions ?? [];
89
+ const { on, off } = guessOnOff(options, typeof binding === "string" ? {} : binding);
90
+ for (const choice of [on, off]) if (choice !== void 0 && !options.includes(choice)) throw new Error(`"${definition.name}" has no value "${choice}"; it has ${options.join(", ")}`);
91
+ behaviour.booleans[valueId] = {
92
+ propertyId: definition.id,
93
+ on,
94
+ off
95
+ };
96
+ }
97
+ function resolveStates(behaviour, properties, states) {
98
+ const definition = findProperty(properties, typeof states === "string" ? states : states.property, ["VARIANT"], "states");
99
+ const guessed = guessInteractionStates(definition.id, definition.variantOptions ?? []);
100
+ if (typeof states === "string") {
101
+ behaviour.states = guessed;
102
+ return;
103
+ }
104
+ const { property: _property, ...values } = states;
105
+ behaviour.states = {
106
+ ...guessed,
107
+ ...stripUndefined(values)
108
+ };
109
+ }
110
+ /**
111
+ * The stored behaviour for a spec, with names resolved to the owner's property and slot ids. A
112
+ * name the component lacks, a value the kind does not have, or a variant value the property
113
+ * does not offer fails with a message naming what exists.
114
+ */
115
+ function behaviourFromSpec(graph, owner, spec) {
116
+ const contract = behaviourContract(spec.kind);
117
+ const properties = behaviourProperties(graph, owner);
118
+ const behaviour = emptyBehaviour(spec.kind);
119
+ for (const [valueId, binding] of Object.entries(spec.values ?? {})) resolveValue(behaviour, properties, valueId, binding);
120
+ const numbers = contract.values.filter((item) => item.type === "number");
121
+ for (const [valueId, settings] of Object.entries(spec.numbers ?? {})) {
122
+ if (!numbers.some((item) => item.id === valueId)) throw new Error(`A ${spec.kind} has no number value "${valueId}"; it has ${listed(numbers)}`);
123
+ const range = {
124
+ ...behaviour.numbers[valueId],
125
+ ...stripUndefined(settings)
126
+ };
127
+ if (!isNumberRange(range)) throw new Error(`"${valueId}" needs max above min and a positive step`);
128
+ behaviour.numbers[valueId] = range;
129
+ }
130
+ for (const [partId, slotName] of Object.entries(spec.parts ?? {})) {
131
+ if (!contract.parts.some((item) => item.id === partId)) throw new Error(`A ${spec.kind} has no part "${partId}"; it has ${listed(contract.parts)}`);
132
+ const id = findProperty(properties, slotName, ["SLOT"], partId).id;
133
+ const taken = Object.entries(behaviour.parts).find(([, slot]) => slot === id)?.[0];
134
+ if (taken) throw new Error(`"${slotName}" is already the ${taken}; a slot draws one part`);
135
+ behaviour.parts[partId] = id;
136
+ }
137
+ if (spec.states !== void 0) resolveStates(behaviour, properties, spec.states);
138
+ return behaviour;
139
+ }
140
+ function stripUndefined(record) {
141
+ return omitBy(record, (value) => value === void 0);
142
+ }
143
+ /** The spec a stored behaviour reads as, with ids back to names; unresolved bindings are left out. */
144
+ function behaviourToSpec(graph, owner, behaviour) {
145
+ const properties = behaviourProperties(graph, owner);
146
+ const nameOf = (id) => properties.find((item) => item.id === id)?.name;
147
+ const values = {};
148
+ for (const [valueId, binding] of Object.entries(behaviour.booleans)) {
149
+ const name = nameOf(binding.propertyId);
150
+ if (name) values[valueId] = binding.on || binding.off ? {
151
+ property: name,
152
+ on: binding.on,
153
+ off: binding.off
154
+ } : name;
155
+ }
156
+ for (const valueId of Object.keys(behaviour.texts)) {
157
+ const name = nameOf(textBinding(behaviour, valueId));
158
+ if (name) values[valueId] = name;
159
+ }
160
+ const parts = Object.fromEntries(Object.entries(behaviour.parts).flatMap(([partId, id]) => {
161
+ const name = nameOf(id);
162
+ return name ? [[partId, name]] : [];
163
+ }));
164
+ const statesName = nameOf(behaviour.states?.propertyId);
165
+ const spec = { kind: behaviour.kind };
166
+ if (Object.keys(values).length) spec.values = values;
167
+ if (Object.keys(behaviour.numbers).length) spec.numbers = structuredClone(behaviour.numbers);
168
+ if (Object.keys(parts).length) spec.parts = parts;
169
+ if (behaviour.states && statesName) spec.states = {
170
+ ...stripUndefined({
171
+ ...behaviour.states,
172
+ propertyId: void 0
173
+ }),
174
+ property: statesName
175
+ };
176
+ return spec;
177
+ }
178
+ //#endregion
179
+ export { behaviourFromSpec, behaviourSpecSchema, behaviourToSpec, guessOnOff };
180
+
181
+ //# sourceMappingURL=spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spec.js","names":[],"sources":["../../../src/behaviours/spec.ts"],"sourcesContent":["import { omitBy } from 'es-toolkit/object'\nimport * as v from 'valibot'\n\nimport type { SceneGraph } from '../index'\nimport type { ComponentPropertyDefinition, SceneNode } from '../types'\nimport { BEHAVIOUR_KINDS, behaviourContract, type BehaviourKind } from './kinds'\nimport {\n behaviourProperties,\n emptyBehaviour,\n guessInteractionStates,\n textBinding,\n type Behaviour,\n type BehaviourNumberSettings\n} from './model'\nimport { interactionStateValues, isNumberRange } from './schema'\n\n/**\n * A behaviour as scripts, tools, and JSX write it: component properties and slots by name, not\n * by id. Values are boolean or text values by their contract id; numbers are a slider's or\n * number field's own range.\n */\nexport const behaviourSpecSchema = v.object({\n kind: v.picklist(BEHAVIOUR_KINDS),\n values: v.optional(\n v.record(\n v.string(),\n v.union([\n v.string(),\n v.object({ property: v.string(), on: v.optional(v.string()), off: v.optional(v.string()) })\n ])\n )\n ),\n numbers: v.optional(\n v.record(\n v.string(),\n v.object({\n min: v.optional(v.number()),\n max: v.optional(v.number()),\n step: v.optional(v.number()),\n default: v.optional(v.number())\n })\n )\n ),\n parts: v.optional(v.record(v.string(), v.string())),\n states: v.optional(\n v.union([v.string(), v.object({ property: v.string(), ...interactionStateValues })])\n )\n})\n\nexport type BehaviourSpec = v.InferOutput<typeof behaviourSpecSchema>\n\n/** Variant values that usually mean on, compared case-insensitively. */\nconst ON_NAMES = ['on', 'true', 'yes', 'checked', 'pressed', 'open', 'selected', 'active']\nconst OFF_NAMES = ['off', 'false', 'no', 'unchecked', 'closed', 'default', 'inactive']\n\nfunction named(names: readonly string[], options: readonly string[]): string | undefined {\n return options.find((option) => names.includes(option.trim().toLowerCase()))\n}\n\n/**\n * The variant values that likely mean on and off: names such as On, True, or Checked first,\n * then the values in order.\n */\nexport function guessOnOff(\n options: readonly string[],\n explicit: { on?: string; off?: string } = {}\n): { on?: string; off?: string } {\n const on = explicit.on ?? named(ON_NAMES, options) ?? options[0]\n const off = explicit.off ?? named(OFF_NAMES, options) ?? options.find((option) => option !== on)\n return { on, off }\n}\n\nfunction findProperty(\n properties: readonly ComponentPropertyDefinition[],\n name: string,\n types: readonly ComponentPropertyDefinition['type'][],\n what: string\n): ComponentPropertyDefinition {\n const found = properties.find((item) => item.name === name && types.includes(item.type))\n if (found) return found\n const available = properties.filter((item) => types.includes(item.type)).map((item) => item.name)\n throw new Error(\n `${what} needs a ${types.join(' or ')} property named \"${name}\"; the component has ${\n available.length ? available.map((item) => `\"${item}\"`).join(', ') : 'none'\n }`\n )\n}\n\ntype ValueBinding = NonNullable<BehaviourSpec['values']>[string]\ntype StatesSpec = NonNullable<BehaviourSpec['states']>\n\nfunction listed(items: readonly { id: string }[]): string {\n return items.map((item) => `\"${item.id}\"`).join(', ')\n}\n\n/** Bind a boolean or text value to the property named in its binding. */\nfunction resolveValue(\n behaviour: Behaviour,\n properties: readonly ComponentPropertyDefinition[],\n valueId: string,\n binding: ValueBinding\n): void {\n const contract = behaviourContract(behaviour.kind)\n const bindable = contract.values.filter((item) => item.type === 'boolean' || item.type === 'text')\n const value = bindable.find((item) => item.id === valueId)\n if (!value)\n throw new Error(\n `A ${behaviour.kind} has no boolean or text value \"${valueId}\"; it has ${listed(bindable)}`\n )\n const name = typeof binding === 'string' ? binding : binding.property\n if (value.type === 'text') {\n behaviour.texts[valueId] = { propertyId: findProperty(properties, name, ['TEXT'], valueId).id }\n return\n }\n const definition = findProperty(properties, name, ['VARIANT', 'BOOLEAN'], valueId)\n if (definition.type === 'BOOLEAN') {\n behaviour.booleans[valueId] = { propertyId: definition.id }\n return\n }\n const options = definition.variantOptions ?? []\n const explicit: { on?: string; off?: string } = typeof binding === 'string' ? {} : binding\n const { on, off } = guessOnOff(options, explicit)\n for (const choice of [on, off])\n if (choice !== undefined && !options.includes(choice))\n throw new Error(`\"${definition.name}\" has no value \"${choice}\"; it has ${options.join(', ')}`)\n behaviour.booleans[valueId] = { propertyId: definition.id, on, off }\n}\n\nfunction resolveStates(\n behaviour: Behaviour,\n properties: readonly ComponentPropertyDefinition[],\n states: StatesSpec\n): void {\n const name = typeof states === 'string' ? states : states.property\n const definition = findProperty(properties, name, ['VARIANT'], 'states')\n const guessed = guessInteractionStates(definition.id, definition.variantOptions ?? [])\n if (typeof states === 'string') {\n behaviour.states = guessed\n return\n }\n const { property: _property, ...values } = states\n behaviour.states = { ...guessed, ...stripUndefined(values) }\n}\n\n/**\n * The stored behaviour for a spec, with names resolved to the owner's property and slot ids. A\n * name the component lacks, a value the kind does not have, or a variant value the property\n * does not offer fails with a message naming what exists.\n */\nexport function behaviourFromSpec(\n graph: SceneGraph,\n owner: SceneNode,\n spec: BehaviourSpec\n): Behaviour {\n const contract = behaviourContract(spec.kind)\n const properties = behaviourProperties(graph, owner)\n const behaviour = emptyBehaviour(spec.kind)\n for (const [valueId, binding] of Object.entries(spec.values ?? {}))\n resolveValue(behaviour, properties, valueId, binding)\n const numbers = contract.values.filter((item) => item.type === 'number')\n for (const [valueId, settings] of Object.entries(spec.numbers ?? {})) {\n if (!numbers.some((item) => item.id === valueId))\n throw new Error(`A ${spec.kind} has no number value \"${valueId}\"; it has ${listed(numbers)}`)\n const range = { ...behaviour.numbers[valueId], ...stripUndefined(settings) }\n if (!isNumberRange(range))\n throw new Error(`\"${valueId}\" needs max above min and a positive step`)\n behaviour.numbers[valueId] = range\n }\n for (const [partId, slotName] of Object.entries(spec.parts ?? {})) {\n if (!contract.parts.some((item) => item.id === partId))\n throw new Error(`A ${spec.kind} has no part \"${partId}\"; it has ${listed(contract.parts)}`)\n const id = findProperty(properties, slotName, ['SLOT'], partId).id\n const taken = Object.entries(behaviour.parts).find(([, slot]) => slot === id)?.[0]\n if (taken) throw new Error(`\"${slotName}\" is already the ${taken}; a slot draws one part`)\n behaviour.parts[partId] = id\n }\n if (spec.states !== undefined) resolveStates(behaviour, properties, spec.states)\n return behaviour\n}\n\nfunction stripUndefined<T extends Record<string, unknown>>(record: T): Partial<T> {\n return omitBy(record, (value) => value === undefined)\n}\n\n/** The spec a stored behaviour reads as, with ids back to names; unresolved bindings are left out. */\nexport function behaviourToSpec(\n graph: SceneGraph,\n owner: SceneNode,\n behaviour: Behaviour\n): BehaviourSpec {\n const properties = behaviourProperties(graph, owner)\n const nameOf = (id: string | undefined) => properties.find((item) => item.id === id)?.name\n const values: NonNullable<BehaviourSpec['values']> = {}\n for (const [valueId, binding] of Object.entries(behaviour.booleans)) {\n const name = nameOf(binding.propertyId)\n if (name)\n values[valueId] =\n binding.on || binding.off ? { property: name, on: binding.on, off: binding.off } : name\n }\n for (const valueId of Object.keys(behaviour.texts)) {\n const name = nameOf(textBinding(behaviour, valueId))\n if (name) values[valueId] = name\n }\n const parts = Object.fromEntries(\n Object.entries(behaviour.parts).flatMap(([partId, id]) => {\n const name = nameOf(id)\n return name ? [[partId, name]] : []\n })\n )\n const statesName = nameOf(behaviour.states?.propertyId)\n const spec: BehaviourSpec = { kind: behaviour.kind }\n if (Object.keys(values).length) spec.values = values\n if (Object.keys(behaviour.numbers).length) spec.numbers = structuredClone(behaviour.numbers)\n if (Object.keys(parts).length) spec.parts = parts\n if (behaviour.states && statesName)\n spec.states = {\n ...stripUndefined({ ...behaviour.states, propertyId: undefined }),\n property: statesName\n }\n return spec\n}\n\nexport type { BehaviourKind, BehaviourNumberSettings }\n"],"mappings":";;;;;;;;;;AAqBA,MAAa,sBAAsB,EAAE,OAAO;CAC1C,MAAM,EAAE,SAAS,eAAe;CAChC,QAAQ,EAAE,SACR,EAAE,OACA,EAAE,OAAO,GACT,EAAE,MAAM,CACN,EAAE,OAAO,GACT,EAAE,OAAO;EAAE,UAAU,EAAE,OAAO;EAAG,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC;EAAG,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC;CAAE,CAAC,CAC5F,CAAC,CACH,CACF;CACA,SAAS,EAAE,SACT,EAAE,OACA,EAAE,OAAO,GACT,EAAE,OAAO;EACP,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC;EAC1B,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC;EAC1B,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC;EAC3B,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,CAAC,CACH,CACF;CACA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC;CAClD,QAAQ,EAAE,SACR,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO;EAAE,UAAU,EAAE,OAAO;EAAG,GAAG;CAAuB,CAAC,CAAC,CAAC,CACrF;AACF,CAAC;;AAKD,MAAM,WAAW;CAAC;CAAM;CAAQ;CAAO;CAAW;CAAW;CAAQ;CAAY;AAAQ;AACzF,MAAM,YAAY;CAAC;CAAO;CAAS;CAAM;CAAa;CAAU;CAAW;AAAU;AAErF,SAAS,MAAM,OAA0B,SAAgD;CACvF,OAAO,QAAQ,MAAM,WAAW,M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AAS,KAAK,OAAO,EAAE,CAAC,EAAE;CACtF,MAAM,SAA+C,CAAC;CACtD,KAAK,MAAM,CAAC,SAAS,YAAY,OAAO,QAAQ,UAAU,QAAQ,GAAG;EACnE,MAAM,OAAO,OAAO,QAAQ,UAAU;EACtC,IAAI,MACF,OAAO,WACL,QAAQ,MAAM,QAAQ,MAAM;GAAE,UAAU;GAAM,IAAI,QAAQ;GAAI,KAAK,QAAQ;EAAI,IAAI;CACzF;CACA,KAAK,MAAM,WAAW,OAAO,KAAK,UAAU,KAAK,GAAG;EAClD,MAAM,OAAO,OAAO,YAAY,WAAW,OAAO,CAAC;EACnD,IAAI,MAAM,OAAO,WAAW;CAC9B;CACA,MAAM,QAAQ,OAAO,YACnB,OAAO,QAAQ,UAAU,KAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,QAAQ;EACxD,MAAM,OAAO,OAAO,EAAE;EACtB,OAAO,OAAO,CAAC,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC;CACpC,CAAC,CACH;CACA,MAAM,aAAa,OAAO,UAAU,QAAQ,UAAU;CACtD,MAAM,OAAsB,EAAE,MAAM,UAAU,KAAK;CACnD,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,KAAK,SAAS;CAC9C,IAAI,OAAO,KAAK,UAAU,OAAO,CAAC,CAAC,QAAQ,KAAK,UAAU,gBAAgB,UAAU,OAAO;CAC3F,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,KAAK,QAAQ;CAC5C,IAAI,UAAU,UAAU,YACtB,KAAK,SAAS;EACZ,GAAG,eAAe;GAAE,GAAG,UAAU;GAAQ,YAAY,KAAA;EAAU,CAAC;EAChE,UAAU;CACZ;CACF,OAAO;AACT"}
@@ -0,0 +1,57 @@
1
+ import { createNanoEvents } from "nanoevents";
2
+ //#region src/buffered-events.ts
3
+ var CommittedGraphEventError = class extends AggregateError {
4
+ committed = true;
5
+ constructor(errors) {
6
+ super(errors, "Committed graph event delivery failed");
7
+ this.name = "CommittedGraphEventError";
8
+ }
9
+ };
10
+ /** Stable emitter identity with synchronous, nestable event buffering. */
11
+ var BufferedSceneEmitter = class {
12
+ delegate = createNanoEvents();
13
+ buffers = [];
14
+ get events() {
15
+ return this.delegate.events;
16
+ }
17
+ set events(events) {
18
+ this.delegate.events = events;
19
+ }
20
+ on(event, listener) {
21
+ return this.delegate.on(event, listener);
22
+ }
23
+ emit(event, ...args) {
24
+ const buffer = this.buffers.at(-1);
25
+ if (buffer) buffer.push(() => this.delegate.emit(event, ...args));
26
+ else this.delegate.emit(event, ...args);
27
+ }
28
+ /** Buffers events, not mutations. Callers own rollback if the action throws. */
29
+ batch(action) {
30
+ const pending = [];
31
+ this.buffers.push(pending);
32
+ let result;
33
+ try {
34
+ result = action();
35
+ } catch (error) {
36
+ this.buffers.pop();
37
+ throw error;
38
+ }
39
+ this.buffers.pop();
40
+ const outer = this.buffers.at(-1);
41
+ if (outer) outer.push(...pending);
42
+ else {
43
+ const errors = [];
44
+ for (const publish of pending) try {
45
+ publish();
46
+ } catch (error) {
47
+ errors.push(error);
48
+ }
49
+ if (errors.length) throw new CommittedGraphEventError(errors);
50
+ }
51
+ return result;
52
+ }
53
+ };
54
+ //#endregion
55
+ export { BufferedSceneEmitter, CommittedGraphEventError };
56
+
57
+ //# sourceMappingURL=buffered-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buffered-events.js","names":[],"sources":["../../src/buffered-events.ts"],"sourcesContent":["import { createNanoEvents, type Emitter } from 'nanoevents'\n\nimport type { SceneGraphEvents } from './types'\n\nexport class CommittedGraphEventError extends AggregateError {\n readonly committed = true\n\n constructor(errors: readonly unknown[]) {\n super(errors, 'Committed graph event delivery failed')\n this.name = 'CommittedGraphEventError'\n }\n}\n\n/** Stable emitter identity with synchronous, nestable event buffering. */\nexport class BufferedSceneEmitter implements Emitter<SceneGraphEvents> {\n private readonly delegate = createNanoEvents<SceneGraphEvents>()\n private readonly buffers: Array<Array<() => void>> = []\n\n get events(): Emitter<SceneGraphEvents>['events'] {\n return this.delegate.events\n }\n\n set events(events: Emitter<SceneGraphEvents>['events']) {\n this.delegate.events = events\n }\n\n on<K extends keyof SceneGraphEvents>(event: K, listener: SceneGraphEvents[K]) {\n return this.delegate.on(event, listener)\n }\n\n emit<K extends keyof SceneGraphEvents>(event: K, ...args: Parameters<SceneGraphEvents[K]>): void {\n const buffer = this.buffers.at(-1)\n if (buffer) buffer.push(() => this.delegate.emit(event, ...args))\n else this.delegate.emit(event, ...args)\n }\n\n /** Buffers events, not mutations. Callers own rollback if the action throws. */\n batch<T>(action: () => T): T {\n const pending: Array<() => void> = []\n this.buffers.push(pending)\n let result: T\n try {\n result = action()\n } catch (error) {\n this.buffers.pop()\n throw error\n }\n this.buffers.pop()\n const outer = this.buffers.at(-1)\n if (outer) outer.push(...pending)\n else {\n const errors: unknown[] = []\n for (const publish of pending) {\n try {\n publish()\n } catch (error) {\n errors.push(error)\n }\n }\n if (errors.length) throw new CommittedGraphEventError(errors)\n }\n return result\n }\n}\n"],"mappings":";;AAIA,IAAa,2BAAb,cAA8C,eAAe;CAC3D,YAAqB;CAErB,YAAY,QAA4B;EACtC,MAAM,QAAQ,uCAAuC;EACrD,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,uBAAb,MAAuE;CACrE,WAA4B,iBAAmC;CAC/D,UAAqD,CAAC;CAEtD,IAAI,SAA8C;EAChD,OAAO,KAAK,SAAS;CACvB;CAEA,IAAI,OAAO,QAA6C;EACtD,KAAK,SAAS,SAAS;CACzB;CAEA,GAAqC,OAAU,UAA+B;EAC5E,OAAO,KAAK,SAAS,GAAG,OAAO,QAAQ;CACzC;CAEA,KAAuC,OAAU,GAAG,MAA6C;EAC/F,MAAM,SAAS,KAAK,QAAQ,GAAG,EAAE;EACjC,IAAI,QAAQ,OAAO,WAAW,KAAK,SAAS,KAAK,OAAO,GAAG,IAAI,CAAC;OAC3D,KAAK,SAAS,KAAK,OAAO,GAAG,IAAI;CACxC;;CAGA,MAAS,QAAoB;EAC3B,MAAM,UAA6B,CAAC;EACpC,KAAK,QAAQ,KAAK,OAAO;EACzB,IAAI;EACJ,IAAI;GACF,SAAS,OAAO;EAClB,SAAS,OAAO;GACd,KAAK,QAAQ,IAAI;GACjB,MAAM;EACR;EACA,KAAK,QAAQ,IAAI;EACjB,MAAM,QAAQ,KAAK,QAAQ,GAAG,EAAE;EAChC,IAAI,OAAO,MAAM,KAAK,GAAG,OAAO;OAC3B;GACH,MAAM,SAAoB,CAAC;GAC3B,KAAK,MAAM,WAAW,SACpB,IAAI;IACF,QAAQ;GACV,SAAS,OAAO;IACd,OAAO,KAAK,KAAK;GACnB;GAEF,IAAI,OAAO,QAAQ,MAAM,IAAI,yBAAyB,MAAM;EAC9D;EACA,OAAO;CACT;AACF"}
@@ -0,0 +1,57 @@
1
+ import { wcagContrast } from "culori";
2
+ //#region src/constants.ts
3
+ const BLACK = {
4
+ r: 0,
5
+ g: 0,
6
+ b: 0,
7
+ a: 1
8
+ };
9
+ const WHITE = {
10
+ r: 1,
11
+ g: 1,
12
+ b: 1,
13
+ a: 1
14
+ };
15
+ const TRANSPARENT = {
16
+ r: 0,
17
+ g: 0,
18
+ b: 0,
19
+ a: 0
20
+ };
21
+ const DEFAULT_FONT_FAMILY = "Inter";
22
+ const DEFAULT_STROKE_MITER_LIMIT = 4;
23
+ const DEFAULT_STROKE_WEIGHT = 1;
24
+ //#endregion
25
+ //#region src/color/contrast.ts
26
+ /** Opaque color seen when `foreground` at `alpha` is drawn over an opaque `background`. */
27
+ function compositeOver(foreground, background, alpha = foreground.a) {
28
+ const mix = (top, bottom) => top * alpha + bottom * (1 - alpha);
29
+ return {
30
+ r: mix(foreground.r, background.r),
31
+ g: mix(foreground.g, background.g),
32
+ b: mix(foreground.b, background.b),
33
+ a: 1
34
+ };
35
+ }
36
+ /** WCAG 2 contrast ratio of two colors, from 1 to 21; alpha is ignored, so composite first. */
37
+ function contrastRatio(a, b) {
38
+ return wcagContrast({
39
+ mode: "rgb",
40
+ r: a.r,
41
+ g: a.g,
42
+ b: a.b
43
+ }, {
44
+ mode: "rgb",
45
+ r: b.r,
46
+ g: b.g,
47
+ b: b.b
48
+ });
49
+ }
50
+ /** Black or white, whichever reads better on an opaque `background`. */
51
+ function readableForeground(background) {
52
+ return contrastRatio(background, BLACK) >= contrastRatio(background, WHITE) ? BLACK : WHITE;
53
+ }
54
+ //#endregion
55
+ export { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT, DEFAULT_STROKE_WEIGHT, TRANSPARENT, WHITE, compositeOver, contrastRatio, readableForeground };
56
+
57
+ //# sourceMappingURL=contrast.js.map
@@ -0,0 +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"}