@pixerate/editor 0.26.1 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -3
- package/dist/agent/index.cjs +56 -6
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +6 -4
- package/dist/agent/index.d.ts +6 -4
- package/dist/agent/index.js +51 -1
- package/dist/agent/index.js.map +1 -1
- package/dist/animation/index.cjs +62 -0
- package/dist/animation/index.cjs.map +1 -0
- package/dist/animation/index.d.cts +296 -0
- package/dist/animation/index.d.ts +296 -0
- package/dist/animation/index.js +62 -0
- package/dist/animation/index.js.map +1 -0
- package/dist/{builtins-Chj6zv_O.d.ts → builtins-haN82vjT.d.ts} +33 -3
- package/dist/{builtins-CdPcLwwF.d.cts → builtins-nMXh9sT3.d.cts} +33 -3
- package/dist/canvas/index.cjs +535 -737
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.d.cts +74 -291
- package/dist/canvas/index.d.ts +74 -291
- package/dist/canvas/index.js +417 -619
- package/dist/canvas/index.js.map +1 -1
- package/dist/{chunk-X7HXL2SB.js → chunk-3RPOW4CS.js} +342 -16
- package/dist/chunk-3RPOW4CS.js.map +1 -0
- package/dist/{chunk-UBCFIABU.js → chunk-5H2OPMXZ.js} +183 -6
- package/dist/chunk-5H2OPMXZ.js.map +1 -0
- package/dist/chunk-A6PHCAGX.cjs +87 -0
- package/dist/chunk-A6PHCAGX.cjs.map +1 -0
- package/dist/{chunk-HRMEDT2L.js → chunk-D6AVOTSD.js} +6 -85
- package/dist/chunk-D6AVOTSD.js.map +1 -0
- package/dist/chunk-HXDMZQTD.cjs +497 -0
- package/dist/chunk-HXDMZQTD.cjs.map +1 -0
- package/dist/chunk-IB3ZHQAX.js +497 -0
- package/dist/chunk-IB3ZHQAX.js.map +1 -0
- package/dist/{chunk-4BVP64JJ.cjs → chunk-K2UYKJ6M.cjs} +24 -103
- package/dist/chunk-K2UYKJ6M.cjs.map +1 -0
- package/dist/{chunk-HDYMLS3X.cjs → chunk-MC2LQN5S.cjs} +196 -19
- package/dist/chunk-MC2LQN5S.cjs.map +1 -0
- package/dist/{chunk-XQFHLT53.js → chunk-MXZJ4PKN.js} +24 -10
- package/dist/chunk-MXZJ4PKN.js.map +1 -0
- package/dist/{chunk-LN2POBHT.cjs → chunk-OYEFRO3D.cjs} +28 -14
- package/dist/chunk-OYEFRO3D.cjs.map +1 -0
- package/dist/chunk-PWJARCI4.js +637 -0
- package/dist/chunk-PWJARCI4.js.map +1 -0
- package/dist/chunk-TGD52FEZ.js +87 -0
- package/dist/chunk-TGD52FEZ.js.map +1 -0
- package/dist/chunk-TTYCN6ZH.cjs +637 -0
- package/dist/chunk-TTYCN6ZH.cjs.map +1 -0
- package/dist/{chunk-NQF32I6Z.cjs → chunk-U7VGDSNY.cjs} +463 -137
- package/dist/chunk-U7VGDSNY.cjs.map +1 -0
- package/dist/commands/index.cjs +30 -410
- package/dist/commands/index.cjs.map +1 -1
- package/dist/commands/index.d.cts +1 -1
- package/dist/commands/index.d.ts +1 -1
- package/dist/commands/index.js +17 -397
- package/dist/commands/index.js.map +1 -1
- package/dist/{controller-CxXGOEmy.d.ts → controller-w6eRTjF8.d.cts} +67 -2
- package/dist/{controller-CxXGOEmy.d.cts → controller-w6eRTjF8.d.ts} +67 -2
- package/dist/extensions/index.cjs +25 -7
- package/dist/extensions/index.cjs.map +1 -1
- package/dist/extensions/index.d.cts +1 -1
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +32 -14
- package/dist/generation/index.cjs +3 -3
- package/dist/generation/index.cjs.map +1 -1
- package/dist/generation/index.js +3 -3
- package/dist/{index-jcJwmBYt.d.cts → index-C6gaQRH0.d.cts} +53 -4
- package/dist/{index-B273Zllk.d.ts → index-DXAv_R08.d.ts} +53 -4
- package/dist/index.cjs +57 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +132 -94
- package/dist/index.js.map +1 -1
- package/dist/spreadsheet/index.cjs +23 -3
- package/dist/spreadsheet/index.cjs.map +1 -1
- package/dist/spreadsheet/index.d.cts +76 -3
- package/dist/spreadsheet/index.d.ts +76 -3
- package/dist/spreadsheet/index.js +28 -8
- package/dist/tokens/index.cjs +4 -2
- package/dist/tokens/index.cjs.map +1 -1
- package/dist/tokens/index.js +6 -4
- package/package.json +6 -1
- package/dist/chunk-4BVP64JJ.cjs.map +0 -1
- package/dist/chunk-HDYMLS3X.cjs.map +0 -1
- package/dist/chunk-HRMEDT2L.js.map +0 -1
- package/dist/chunk-LN2POBHT.cjs.map +0 -1
- package/dist/chunk-NQF32I6Z.cjs.map +0 -1
- package/dist/chunk-UBCFIABU.js.map +0 -1
- package/dist/chunk-X7HXL2SB.js.map +0 -1
- package/dist/chunk-XQFHLT53.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-4BVP64JJ.cjs","../src/tokens/types.ts","../src/tokens/color.ts","../src/tokens/model.ts","../src/tokens/store.ts","../src/tokens/css.ts","../src/tokens/w3c.ts"],"names":["g","w3cType"],"mappings":"AAAA;ACaO,IAAM,YAAA,EAAoC,CAAC,OAAA,EAAS,QAAA,EAAU,QAAA,EAAU,SAAS,CAAA;AA8FjF,IAAM,WAAA,EAAN,MAAA,QAAyB,MAAM;AAAA,EAC5B;AAAA,EACT,WAAA,CAAY,IAAA,EAAsB,OAAA,EAAiB;AAClD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,KAAA,EAAO,YAAA;AACZ,IAAA,IAAA,CAAK,KAAA,EAAO,IAAA;AAAA,EACb;AACD,CAAA;AAEO,SAAS,YAAA,CAAa,KAAA,EAAqC;AACjE,EAAA,OAAO,OAAO,MAAA,IAAU,SAAA,GAAY,MAAA,IAAU,KAAA,GAAQ,OAAQ,KAAA,CAAqB,MAAA,IAAU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AAA;AACJ,IAAA;AACF,IAAA;AACQ,IAAA;AACL,IAAA;AACnB,MAAA;AACI,QAAA;AACQ,MAAA;AACQ,QAAA;AACxB,MAAA;AACD,IAAA;AACD,EAAA;AAG+B,EAAA;AACT,IAAA;AACI,IAAA;AACJ,IAAA;AACN,IAAA;AAEa,MAAA;AACA,MAAA;AAEzB,MAAA;AAEuB,MAAA;AAC1B,IAAA;AACe,IAAA;AACC,MAAA;AACf,MAAA;AACD,IAAA;AACgB,IAAA;AACF,IAAA;AACH,IAAA;AACY,MAAA;AACtB,MAAA;AACD,IAAA;AAC2B,IAAA;AAC5B,EAAA;AAE6B,EAAA;AAC9B;ANuyBiC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-4BVP64JJ.cjs","sourcesContent":[null,"// Portions ported from figcraft/crates/doc/src/styles.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n\n/**\n * Design tokens (Figma-style \"variables\"): collections hold modes (e.g. Light / Dark) and\n * typed variables with one value per mode. A value is a literal or an alias to another\n * variable of the same type, possibly in another collection.\n *\n * The state is plain, immutable, JSON-serialisable data. Every operation returns a new state.\n */\n\n/** A variable's type. */\nexport type TokenType = 'color' | 'number' | 'string' | 'boolean';\n\nexport const TOKEN_TYPES: readonly TokenType[] = ['color', 'number', 'string', 'boolean'];\n\n/** A resolved value: colours are normalised hex strings (`#rrggbb` or `#rrggbbaa`). */\nexport type TokenLiteral = string | number | boolean;\n\n/** A reference to another variable (by id). */\nexport interface TokenAlias {\n\talias: string;\n}\n\n/** What a variable holds in one mode. */\nexport type TokenValue = TokenLiteral | TokenAlias;\n\nexport interface TokenMode {\n\tid: string;\n\tname: string;\n}\n\nexport interface TokenCollection {\n\tid: string;\n\tname: string;\n\t/** At least one mode. The first one is the default mode. */\n\tmodes: readonly TokenMode[];\n}\n\n/**\n * Which properties pickers offer a variable for (figcraft / Figma scope ids). Scopes only\n * filter pickers: binding out of scope still works.\n */\nexport type TokenScope =\n\t| 'ALL_SCOPES'\n\t| 'ALL_FILLS'\n\t| 'FRAME_FILL'\n\t| 'SHAPE_FILL'\n\t| 'TEXT_FILL'\n\t| 'STROKE_COLOR'\n\t| 'EFFECT_COLOR'\n\t| 'CORNER_RADIUS'\n\t| 'WIDTH_HEIGHT'\n\t| 'GAP'\n\t| 'OPACITY'\n\t| 'STROKE_FLOAT'\n\t| 'EFFECT_FLOAT'\n\t| 'FONT_WEIGHT'\n\t| 'FONT_SIZE'\n\t| 'LINE_HEIGHT'\n\t| 'LETTER_SPACING'\n\t| 'PARAGRAPH_SPACING'\n\t| 'PARAGRAPH_INDENT'\n\t| 'TEXT_CONTENT'\n\t| 'FONT_FAMILY'\n\t| 'FONT_STYLE';\n\nexport interface TokenVariable {\n\tid: string;\n\t/** Unique within its collection. `/` separates groups (`color/bg`). */\n\tname: string;\n\tcollectionId: string;\n\ttype: TokenType;\n\t/** Value per mode id of the collection. */\n\tvaluesByMode: Readonly<Record<string, TokenValue>>;\n\tdescription?: string;\n\t/** Pickers offer the variable for these scopes; `undefined` = every supported property. */\n\tscopes?: readonly TokenScope[];\n\t/** Unit for number variables in CSS / W3C export (`px`, `rem`, `ms`, …). */\n\tunit?: string;\n}\n\nexport interface TokenState {\n\tcollections: readonly TokenCollection[];\n\tvariables: readonly TokenVariable[];\n}\n\n/**\n * Chosen mode per collection: `{ [collectionId]: modeId }`. Collections not listed (or with an\n * unknown mode) use their default (first) mode.\n */\nexport type TokenModeContext = Readonly<Record<string, string>>;\n\nexport type TokenErrorCode =\n\t| 'not-found'\n\t| 'invalid-name'\n\t| 'duplicate-name'\n\t| 'name-conflict'\n\t| 'invalid-type'\n\t| 'invalid-value'\n\t| 'type-mismatch'\n\t| 'alias-missing'\n\t| 'alias-cycle'\n\t| 'last-mode'\n\t| 'unknown-scope'\n\t| 'invalid-input';\n\n/** Thrown by token operations that are refused; `code` says why. */\nexport class TokenError extends Error {\n\treadonly code: TokenErrorCode;\n\tconstructor(code: TokenErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'TokenError';\n\t\tthis.code = code;\n\t}\n}\n\nexport function isTokenAlias(value: unknown): value is TokenAlias {\n\treturn typeof value === 'object' && value !== null && typeof (value as TokenAlias).alias === 'string';\n}\n\nexport const EMPTY_TOKEN_STATE: TokenState = Object.freeze({ collections: Object.freeze([]), variables: Object.freeze([]) }) as TokenState;\n","/**\n * Colour parsing for colour tokens. Colours are stored as lowercase hex: `#rrggbb`, or\n * `#rrggbbaa` when not opaque. Accepted input: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`,\n * `rgb()` / `rgba()` (numbers or percentages, comma or space separated, `/ alpha`),\n * `transparent`, `black`, `white`, `{ r, g, b, a? }` with channels in 0–1 (Figma JSON) and\n * W3C colour objects (`{ colorSpace: 'srgb', components: [r, g, b], alpha?, hex? }`).\n */\n\nconst HEX = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;\n// Anchored with one character-class run: linear time.\nconst RGB = /^rgba?\\(([^()]*)\\)$/i;\n\nconst clamp01 = (v: number) => Math.min(1, Math.max(0, v));\nconst byte = (v: number) => Math.round(clamp01(v) * 255);\nconst hex2 = (n: number) => n.toString(16).padStart(2, '0');\n\n/** `#rrggbb` / `#rrggbbaa` from 0–1 channels. */\nexport function rgbaToHex(r: number, g: number, b: number, a = 1): string {\n\tconst head = `#${hex2(byte(r))}${hex2(byte(g))}${hex2(byte(b))}`;\n\tconst alpha = byte(a);\n\treturn alpha === 255 ? head : head + hex2(alpha);\n}\n\n/** 0–1 channels of a normalised hex colour. */\nexport function hexToRgba(hex: string): { r: number; g: number; b: number; a: number } | null {\n\tconst normal = normalizeTokenColor(hex);\n\tif (normal === null) return null;\n\tconst n = (i: number) => parseInt(normal.slice(i, i + 2), 16) / 255;\n\treturn { r: n(1), g: n(3), b: n(5), a: normal.length === 9 ? n(7) : 1 };\n}\n\nfunction channel(part: string, scale: number): number | null {\n\tconst pct = part.endsWith('%');\n\tconst n = Number(pct ? part.slice(0, -1) : part);\n\tif (!Number.isFinite(n)) return null;\n\treturn pct ? n / 100 : n / scale;\n}\n\n/** The colour as normalised hex, or `null` when it is not a colour this module reads. */\nexport function normalizeTokenColor(input: unknown): string | null {\n\tif (typeof input === 'string') {\n\t\tconst text = input.trim();\n\t\tif (text.length > 200) return null;\n\t\tconst lower = text.toLowerCase();\n\t\tif (lower === 'transparent') return '#00000000';\n\t\tif (lower === 'black') return '#000000';\n\t\tif (lower === 'white') return '#ffffff';\n\t\tconst hex = HEX.exec(text);\n\t\tif (hex) {\n\t\t\tlet digits = hex[1].toLowerCase();\n\t\t\tif (digits.length <= 4) digits = [...digits].map((c) => c + c).join('');\n\t\t\tif (digits.length === 8 && digits.endsWith('ff')) digits = digits.slice(0, 6);\n\t\t\treturn `#${digits}`;\n\t\t}\n\t\tconst rgb = RGB.exec(text);\n\t\tif (rgb) {\n\t\t\tconst [colour, alphaPart] = rgb[1].split('/');\n\t\t\tconst parts = colour.split(/[\\s,]+/).filter(Boolean);\n\t\t\tlet alpha: string | undefined = alphaPart?.trim();\n\t\t\tif (parts.length === 4 && alpha === undefined) alpha = parts.pop();\n\t\t\tif (parts.length !== 3) return null;\n\t\t\tconst channels = parts.map((p) => channel(p, 255));\n\t\t\tconst a = alpha === undefined || alpha === '' ? 1 : channel(alpha, 1);\n\t\t\tif (channels.some((c) => c === null) || a === null) return null;\n\t\t\treturn rgbaToHex(channels[0]!, channels[1]!, channels[2]!, a);\n\t\t}\n\t\treturn null;\n\t}\n\tif (typeof input === 'object' && input !== null) {\n\t\tconst obj = input as Record<string, unknown>;\n\t\tif (Array.isArray(obj.components)) {\n\t\t\tconst space = obj.colorSpace;\n\t\t\tif (space === undefined || space === 'srgb') {\n\t\t\t\tconst [r, g, b] = obj.components as unknown[];\n\t\t\t\tconst a = obj.alpha === undefined ? 1 : obj.alpha;\n\t\t\t\tif ([r, g, b, a].every((v) => typeof v === 'number' && Number.isFinite(v))) {\n\t\t\t\t\treturn rgbaToHex(r as number, g as number, b as number, a as number);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof obj.hex === 'string') {\n\t\t\t\tconst base = normalizeTokenColor(obj.hex);\n\t\t\t\tif (base === null) return null;\n\t\t\t\tconst a = typeof obj.alpha === 'number' ? obj.alpha : 1;\n\t\t\t\tconst c = hexToRgba(base)!;\n\t\t\t\treturn rgbaToHex(c.r, c.g, c.b, a);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\tconst { r, g, b } = obj;\n\t\tconst a = obj.a === undefined ? 1 : obj.a;\n\t\tif ([r, g, b, a].every((v) => typeof v === 'number' && Number.isFinite(v))) {\n\t\t\treturn rgbaToHex(r as number, g as number, b as number, a as number);\n\t\t}\n\t}\n\treturn null;\n}\n","// Portions ported from figcraft/crates/doc/src/styles.rs and figcraft/crates/engine/src/cmd/variables.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { normalizeTokenColor } from './color.js';\nimport {\n\tTokenError,\n\tisTokenAlias,\n\ttype TokenCollection,\n\ttype TokenLiteral,\n\ttype TokenMode,\n\ttype TokenModeContext,\n\ttype TokenScope,\n\ttype TokenState,\n\ttype TokenType,\n\ttype TokenValue,\n\ttype TokenVariable\n} from './types.js';\n\n// ---------------------------------------------------------------------------------------------\n// Lookups\n\ninterface TokenIndex {\n\tcollections: Map<string, TokenCollection>;\n\tvariables: Map<string, TokenVariable>;\n}\n\nconst indexes = new WeakMap<TokenState, TokenIndex>();\n\nfunction indexOf(state: TokenState): TokenIndex {\n\tlet index = indexes.get(state);\n\tif (!index) {\n\t\tindex = {\n\t\t\tcollections: new Map(state.collections.map((c) => [c.id, c])),\n\t\t\tvariables: new Map(state.variables.map((v) => [v.id, v]))\n\t\t};\n\t\tindexes.set(state, index);\n\t}\n\treturn index;\n}\n\nexport function getTokenCollection(state: TokenState, id: string): TokenCollection | undefined {\n\treturn indexOf(state).collections.get(id);\n}\n\nexport function getTokenVariable(state: TokenState, id: string): TokenVariable | undefined {\n\treturn indexOf(state).variables.get(id);\n}\n\n/** The collection with this name. */\nexport function findTokenCollection(state: TokenState, name: string): TokenCollection | undefined {\n\treturn state.collections.find((c) => c.name === name);\n}\n\n/** The variable named `name` (in `collectionId` when given, else the first match). */\nexport function findTokenVariable(state: TokenState, name: string, collectionId?: string): TokenVariable | undefined {\n\treturn state.variables.find((v) => v.name === name && (collectionId === undefined || v.collectionId === collectionId));\n}\n\n/** The variables of a collection, in order. */\nexport function getCollectionVariables(state: TokenState, collectionId: string): TokenVariable[] {\n\treturn state.variables.filter((v) => v.collectionId === collectionId);\n}\n\n/** The collection's default (first) mode. */\nexport function getDefaultMode(collection: TokenCollection): TokenMode {\n\treturn collection.modes[0];\n}\n\n/** The mode with id `key`, else the one named `key`. */\nexport function findTokenMode(collection: TokenCollection, key: string): TokenMode | undefined {\n\treturn collection.modes.find((m) => m.id === key) ?? collection.modes.find((m) => m.name === key);\n}\n\n/** The mode `collection` is in under `modes` (its chosen mode if valid, else the default). */\nexport function getCurrentMode(collection: TokenCollection, modes: TokenModeContext | undefined): TokenMode {\n\tconst chosen = modes?.[collection.id];\n\treturn (chosen !== undefined && collection.modes.find((m) => m.id === chosen)) || collection.modes[0];\n}\n\n// ---------------------------------------------------------------------------------------------\n// Values\n\n/** A new variable's value per type: black, 0, empty, true (figcraft's pinned defaults). */\nexport function defaultTokenValue(type: TokenType): TokenLiteral {\n\tswitch (type) {\n\t\tcase 'color':\n\t\t\treturn '#000000';\n\t\tcase 'number':\n\t\t\treturn 0;\n\t\tcase 'string':\n\t\t\treturn '';\n\t\tcase 'boolean':\n\t\t\treturn true;\n\t}\n}\n\n/** The literal as `type`, or `null` when it does not fit (colours are normalised). */\nexport function coerceTokenLiteral(type: TokenType, value: unknown): TokenLiteral | null {\n\tswitch (type) {\n\t\tcase 'color':\n\t\t\treturn normalizeTokenColor(value);\n\t\tcase 'number': {\n\t\t\tif (typeof value === 'number') return Number.isFinite(value) ? value : null;\n\t\t\tif (typeof value === 'string' && value.trim() !== '') {\n\t\t\t\tconst n = Number(value);\n\t\t\t\treturn Number.isFinite(n) ? n : null;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\tcase 'string':\n\t\t\treturn typeof value === 'string' ? value : null;\n\t\tcase 'boolean':\n\t\t\tif (typeof value === 'boolean') return value;\n\t\t\tif (value === 'true') return true;\n\t\t\tif (value === 'false') return false;\n\t\t\treturn null;\n\t}\n}\n\n/** The type of a literal value (strings that are colours count as strings). */\nexport function literalTokenType(value: TokenLiteral): TokenType {\n\treturn typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'string';\n}\n\n/** A short text for a value: hex, number, string, boolean, or `→ name` for an alias. */\nexport function formatTokenValue(state: TokenState, value: TokenValue | undefined): string {\n\tif (value === undefined) return '';\n\tif (isTokenAlias(value)) return `→ ${getTokenVariable(state, value.alias)?.name ?? value.alias}`;\n\treturn String(value);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Resolution\n\nexport type TokenResolutionErrorCode = 'missing' | 'cycle' | 'no-value' | 'type-mismatch';\n\nexport type TokenResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tvalue: TokenLiteral;\n\t\t\ttype: TokenType;\n\t\t\t/** The variable whose literal was used (the end of the alias chain). */\n\t\t\tvariable: TokenVariable;\n\t\t\t/** Mode of `variable`'s collection that supplied the value. */\n\t\t\tmodeId: string;\n\t\t\t/** Variable ids visited, starting with the requested one. */\n\t\t\tchain: string[];\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\tcode: TokenResolutionErrorCode;\n\t\t\tmessage: string;\n\t\t\tchain: string[];\n\t };\n\n/** The name of a variable for messages. */\nfunction label(state: TokenState, id: string): string {\n\tconst v = getTokenVariable(state, id);\n\treturn v ? `\\`${v.name}\\`` : `\\`${id}\\``;\n}\n\n/**\n * Resolves variable `id` under `modes` (collection id → mode id; the default mode otherwise),\n * following aliases. Each variable along the chain is read in its own collection's mode.\n * Cycles, missing variables and type changes along the chain are reported, never thrown.\n */\nexport function resolveToken(state: TokenState, id: string, modes?: TokenModeContext): TokenResolution {\n\tconst chain: string[] = [];\n\tconst seen = new Set<string>();\n\tlet current = id;\n\tlet type: TokenType | undefined;\n\tfor (;;) {\n\t\tif (seen.has(current)) {\n\t\t\tchain.push(current);\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: 'cycle',\n\t\t\t\tmessage: `Alias cycle: ${chain.map((c) => label(state, c)).join(' → ')}`,\n\t\t\t\tchain\n\t\t\t};\n\t\t}\n\t\tseen.add(current);\n\t\tchain.push(current);\n\t\tconst variable = getTokenVariable(state, current);\n\t\tif (!variable) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: 'missing',\n\t\t\t\tmessage:\n\t\t\t\t\tchain.length === 1\n\t\t\t\t\t\t? `No variable ${label(state, current)}`\n\t\t\t\t\t\t: `${label(state, chain[chain.length - 2])} aliases a missing variable ${label(state, current)}`,\n\t\t\t\tchain\n\t\t\t};\n\t\t}\n\t\tif (type !== undefined && variable.type !== type) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: 'type-mismatch',\n\t\t\t\tmessage: `${label(state, chain[chain.length - 2])} (${type}) aliases ${label(state, current)} (${variable.type})`,\n\t\t\t\tchain\n\t\t\t};\n\t\t}\n\t\ttype = variable.type;\n\t\tconst collection = getTokenCollection(state, variable.collectionId);\n\t\tconst mode = collection ? getCurrentMode(collection, modes) : undefined;\n\t\tlet modeId = mode?.id;\n\t\tlet value = modeId !== undefined ? variable.valuesByMode[modeId] : undefined;\n\t\tif (value === undefined) {\n\t\t\t// figcraft: a missing per-mode value falls back to the default mode, then any value.\n\t\t\tconst fallback = collection?.modes[0]?.id;\n\t\t\tif (fallback !== undefined && variable.valuesByMode[fallback] !== undefined) {\n\t\t\t\tmodeId = fallback;\n\t\t\t\tvalue = variable.valuesByMode[fallback];\n\t\t\t} else {\n\t\t\t\tconst first = Object.keys(variable.valuesByMode)[0];\n\t\t\t\tif (first !== undefined) {\n\t\t\t\t\tmodeId = first;\n\t\t\t\t\tvalue = variable.valuesByMode[first];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (value === undefined || modeId === undefined) {\n\t\t\treturn { ok: false, code: 'no-value', message: `${label(state, current)} has no value`, chain };\n\t\t}\n\t\tif (isTokenAlias(value)) {\n\t\t\tcurrent = value.alias;\n\t\t\tcontinue;\n\t\t}\n\t\treturn { ok: true, value, type: variable.type, variable, modeId, chain };\n\t}\n}\n\n/** The resolved literal, or `undefined` when it does not resolve. */\nexport function resolveTokenValue(state: TokenState, id: string, modes?: TokenModeContext): TokenLiteral | undefined {\n\tconst result = resolveToken(state, id, modes);\n\treturn result.ok ? result.value : undefined;\n}\n\n/** The value of `variableId` in mode `modeId` of its own collection (other collections in their default mode). */\nexport function resolveTokenInMode(state: TokenState, variableId: string, modeId: string): TokenLiteral | undefined {\n\tconst variable = getTokenVariable(state, variableId);\n\tif (!variable) return undefined;\n\treturn resolveTokenValue(state, variableId, { [variable.collectionId]: modeId });\n}\n\n/**\n * Why `variable` cannot alias `targetId`, or `null` when it can: the target must exist, have\n * the same type, and not lead back to `variable` through any alias in any mode.\n */\nexport function checkTokenAlias(state: TokenState, variable: Pick<TokenVariable, 'id' | 'type' | 'name'>, targetId: string): TokenError | null {\n\tconst target = getTokenVariable(state, targetId);\n\tif (!target) return new TokenError('alias-missing', `No variable \\`${targetId}\\` to alias`);\n\tif (target.type !== variable.type) {\n\t\treturn new TokenError('type-mismatch', `Can't alias a ${variable.type} variable to a ${target.type} one (\\`${target.name}\\`)`);\n\t}\n\t// Depth-first search over alias edges in every mode, remembering the path for the message.\n\tconst parent = new Map<string, string | null>([[target.id, null]]);\n\tconst stack = [target.id];\n\twhile (stack.length > 0) {\n\t\tconst current = stack.pop()!;\n\t\tif (current === variable.id) {\n\t\t\tconst path: string[] = [];\n\t\t\tfor (let at: string | null | undefined = current; at != null; at = parent.get(at)) path.push(at);\n\t\t\tconst names = [variable.id, ...path.reverse()].map((id) => (id === variable.id ? `\\`${variable.name}\\`` : label(state, id)));\n\t\t\treturn new TokenError('alias-cycle', `The alias would create a cycle: ${names.join(' → ')}`);\n\t\t}\n\t\tconst v = getTokenVariable(state, current);\n\t\tif (!v) continue;\n\t\tfor (const value of Object.values(v.valuesByMode)) {\n\t\t\tif (isTokenAlias(value) && !parent.has(value.alias)) {\n\t\t\t\tparent.set(value.alias, current);\n\t\t\t\tstack.push(value.alias);\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Scopes\n\nexport const TOKEN_SCOPES_BY_TYPE: Readonly<Record<TokenType, readonly TokenScope[]>> = {\n\tnumber: [\n\t\t'CORNER_RADIUS',\n\t\t'WIDTH_HEIGHT',\n\t\t'GAP',\n\t\t'OPACITY',\n\t\t'STROKE_FLOAT',\n\t\t'EFFECT_FLOAT',\n\t\t'FONT_WEIGHT',\n\t\t'FONT_SIZE',\n\t\t'LINE_HEIGHT',\n\t\t'LETTER_SPACING',\n\t\t'PARAGRAPH_SPACING',\n\t\t'PARAGRAPH_INDENT',\n\t\t'TEXT_CONTENT'\n\t],\n\tcolor: ['FRAME_FILL', 'SHAPE_FILL', 'TEXT_FILL', 'STROKE_COLOR', 'EFFECT_COLOR'],\n\tstring: ['TEXT_CONTENT', 'FONT_FAMILY', 'FONT_STYLE'],\n\tboolean: []\n};\n\n/** Whether `scope` is a scope a variable of `type` can be limited to. */\nexport function isTokenScopeKnown(type: TokenType, scope: string): scope is TokenScope {\n\treturn scope === 'ALL_SCOPES' || (scope === 'ALL_FILLS' && type === 'color') || (TOKEN_SCOPES_BY_TYPE[type] as readonly string[]).includes(scope);\n}\n\n/**\n * Canonical scope list: known ids only, no repeats, `undefined` (no limit) when every\n * supported property is named. Unknown ids throw `unknown-scope`.\n */\nexport function normalizeTokenScopes(type: TokenType, scopes: readonly string[] | null | undefined): TokenScope[] | undefined {\n\tif (scopes == null) return undefined;\n\tconst list: TokenScope[] = [];\n\tfor (const scope of scopes) {\n\t\tif (!isTokenScopeKnown(type, scope)) throw new TokenError('unknown-scope', `Unknown ${type} scope \\`${scope}\\``);\n\t\tif (!list.includes(scope)) list.push(scope);\n\t}\n\tconst allowed = TOKEN_SCOPES_BY_TYPE[type];\n\tconst all = list.includes('ALL_SCOPES') || (allowed.length > 0 && allowed.every((s) => list.includes(s)));\n\treturn all ? undefined : list;\n}\n\n/** Whether pickers offer `variable` for a property of `scope` (no scope: any). */\nexport function isTokenInScope(variable: Pick<TokenVariable, 'scopes'>, scope: TokenScope | undefined): boolean {\n\tif (!variable.scopes || scope === undefined) return true;\n\treturn variable.scopes.some((s) => s === scope || s === 'ALL_SCOPES' || (s === 'ALL_FILLS' && scope.endsWith('_FILL')));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Names\n\nconst BAD_NAME_CHARS = /[{}.]/;\n\n/** Trims each `/`-separated group; throws `invalid-name` when empty or not exportable. */\nexport function normalizeTokenName(name: unknown, what = 'Variable'): string {\n\tif (typeof name !== 'string') throw new TokenError('invalid-name', `${what} name must be a string`);\n\tconst segments = name.split('/').map((s) => s.trim());\n\tif (name.length > 500 || segments.some((s) => s === '')) {\n\t\tthrow new TokenError('invalid-name', `${what} name \\`${name}\\` has an empty group`);\n\t}\n\tfor (const segment of segments) {\n\t\tif (BAD_NAME_CHARS.test(segment) || segment.startsWith('$')) {\n\t\t\tthrow new TokenError('invalid-name', `${what} name \\`${name}\\` can't contain \\`{\\`, \\`}\\` or \\`.\\`, or start a group with \\`$\\``);\n\t\t}\n\t}\n\treturn segments.join('/');\n}\n\nfunction normalizeModeName(name: unknown): string {\n\tif (typeof name !== 'string' || name.trim() === '') throw new TokenError('invalid-name', 'Mode name can\\'t be empty');\n\treturn name.trim().slice(0, 200);\n}\n\nfunction checkVariableName(state: TokenState, collectionId: string, name: string, exceptId?: string): void {\n\tfor (const other of state.variables) {\n\t\tif (other.collectionId !== collectionId || other.id === exceptId) continue;\n\t\tif (other.name === name) throw new TokenError('duplicate-name', `A variable named \\`${name}\\` already exists in this collection`);\n\t\t// A token can't also be a group (W3C design tokens): `color` and `color/bg` clash.\n\t\tif (other.name.startsWith(name + '/') || name.startsWith(other.name + '/')) {\n\t\t\tthrow new TokenError('name-conflict', `\\`${name}\\` clashes with \\`${other.name}\\`: a name can't be both a variable and a group`);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------------------------\n// Operations (pure: each returns a new state, or throws a TokenError)\n\nexport type TokenIdFactory = (kind: 'collection' | 'mode' | 'variable') => string;\n\nlet fallbackCounter = 0;\n/** Default id factory: `crypto.randomUUID`, with a counter fallback. */\nexport const defaultTokenId: TokenIdFactory = (kind) => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return `${kind}-${crypto.randomUUID()}`;\n\tfallbackCounter += 1;\n\treturn `${kind}-${Date.now().toString(36)}-${fallbackCounter}`;\n};\n\nfunction requireCollection(state: TokenState, id: string): TokenCollection {\n\tconst c = getTokenCollection(state, id);\n\tif (!c) throw new TokenError('not-found', `No collection \\`${id}\\``);\n\treturn c;\n}\n\nfunction requireVariable(state: TokenState, id: string): TokenVariable {\n\tconst v = getTokenVariable(state, id);\n\tif (!v) throw new TokenError('not-found', `No variable \\`${id}\\``);\n\treturn v;\n}\n\nfunction requireMode(collection: TokenCollection, key: string): TokenMode {\n\tconst m = findTokenMode(collection, key);\n\tif (!m) throw new TokenError('not-found', `No mode \\`${key}\\` in \\`${collection.name}\\``);\n\treturn m;\n}\n\nfunction replaceCollection(state: TokenState, next: TokenCollection): TokenState {\n\treturn { ...state, collections: state.collections.map((c) => (c.id === next.id ? next : c)) };\n}\n\nfunction replaceVariable(state: TokenState, next: TokenVariable): TokenState {\n\treturn { ...state, variables: state.variables.map((v) => (v.id === next.id ? next : v)) };\n}\n\nexport interface CreateTokenCollectionInput {\n\tname: string;\n\t/** Mode names (default `['Default']`). */\n\tmodes?: readonly string[];\n}\n\nexport function createTokenCollection(\n\tstate: TokenState,\n\tinput: CreateTokenCollectionInput,\n\tcreateId: TokenIdFactory = defaultTokenId\n): { state: TokenState; collection: TokenCollection } {\n\tconst name = normalizeTokenName(input.name, 'Collection');\n\tif (state.collections.some((c) => c.name === name)) {\n\t\tthrow new TokenError('duplicate-name', `A collection named \\`${name}\\` already exists`);\n\t}\n\tconst modeNames = input.modes && input.modes.length > 0 ? input.modes.map(normalizeModeName) : ['Default'];\n\tconst collection: TokenCollection = {\n\t\tid: createId('collection'),\n\t\tname,\n\t\tmodes: modeNames.map((n) => ({ id: createId('mode'), name: n }))\n\t};\n\treturn { state: { ...state, collections: [...state.collections, collection] }, collection };\n}\n\nexport function renameTokenCollection(state: TokenState, id: string, name: string): TokenState {\n\tconst collection = requireCollection(state, id);\n\tconst next = normalizeTokenName(name, 'Collection');\n\tif (state.collections.some((c) => c.id !== id && c.name === next)) {\n\t\tthrow new TokenError('duplicate-name', `A collection named \\`${next}\\` already exists`);\n\t}\n\treturn replaceCollection(state, { ...collection, name: next });\n}\n\n/**\n * Deletes variables `ids`. Variables aliasing one of them take its values (per mode: the deleted\n * variable resolved in that mode when it is in the same collection, else in its default mode).\n */\nexport function deleteTokenVariables(state: TokenState, ids: Iterable<string>): { state: TokenState; deleted: string[] } {\n\tconst gone = new Set<string>();\n\tfor (const id of ids) if (getTokenVariable(state, id)) gone.add(id);\n\tif (gone.size === 0) return { state, deleted: [] };\n\tconst variables: TokenVariable[] = [];\n\tfor (const v of state.variables) {\n\t\tif (gone.has(v.id)) continue;\n\t\tlet values: Record<string, TokenValue> | null = null;\n\t\tfor (const [modeId, value] of Object.entries(v.valuesByMode)) {\n\t\t\tif (!isTokenAlias(value) || !gone.has(value.alias)) continue;\n\t\t\tconst target = getTokenVariable(state, value.alias)!;\n\t\t\tconst resolved = resolveTokenValue(state, target.id, { [target.collectionId]: modeId, [v.collectionId]: modeId });\n\t\t\tvalues ??= { ...v.valuesByMode };\n\t\t\tvalues[modeId] = resolved ?? defaultTokenValue(v.type);\n\t\t}\n\t\tvariables.push(values ? { ...v, valuesByMode: values } : v);\n\t}\n\treturn { state: { ...state, variables }, deleted: [...gone] };\n}\n\n/** Deletes a collection and its variables (aliases into it are detached to their values). */\nexport function deleteTokenCollection(state: TokenState, id: string): { state: TokenState; deleted: string[] } {\n\trequireCollection(state, id);\n\tconst result = deleteTokenVariables(\n\t\tstate,\n\t\tstate.variables.filter((v) => v.collectionId === id).map((v) => v.id)\n\t);\n\treturn { state: { ...result.state, collections: result.state.collections.filter((c) => c.id !== id) }, deleted: result.deleted };\n}\n\n/**\n * Adds a mode. Variables start with the values of mode `from` (default: the default mode).\n */\nexport function addTokenMode(\n\tstate: TokenState,\n\tcollectionId: string,\n\tname: string,\n\toptions: { from?: string } = {},\n\tcreateId: TokenIdFactory = defaultTokenId\n): { state: TokenState; mode: TokenMode } {\n\tconst collection = requireCollection(state, collectionId);\n\tconst modeName = normalizeModeName(name);\n\tif (collection.modes.some((m) => m.name === modeName)) {\n\t\tthrow new TokenError('duplicate-name', `\\`${collection.name}\\` already has a mode named \\`${modeName}\\``);\n\t}\n\tconst source = options.from !== undefined ? requireMode(collection, options.from) : collection.modes[0];\n\tconst mode: TokenMode = { id: createId('mode'), name: modeName };\n\tlet next = replaceCollection(state, { ...collection, modes: [...collection.modes, mode] });\n\tnext = {\n\t\t...next,\n\t\tvariables: next.variables.map((v) => {\n\t\t\tif (v.collectionId !== collectionId) return v;\n\t\t\tconst value = v.valuesByMode[source.id] ?? defaultTokenValue(v.type);\n\t\t\treturn { ...v, valuesByMode: { ...v.valuesByMode, [mode.id]: value } };\n\t\t})\n\t};\n\treturn { state: next, mode };\n}\n\nexport function renameTokenMode(state: TokenState, collectionId: string, modeId: string, name: string): TokenState {\n\tconst collection = requireCollection(state, collectionId);\n\tconst mode = requireMode(collection, modeId);\n\tconst modeName = normalizeModeName(name);\n\tif (collection.modes.some((m) => m.id !== mode.id && m.name === modeName)) {\n\t\tthrow new TokenError('duplicate-name', `\\`${collection.name}\\` already has a mode named \\`${modeName}\\``);\n\t}\n\treturn replaceCollection(state, { ...collection, modes: collection.modes.map((m) => (m.id === mode.id ? { ...m, name: modeName } : m)) });\n}\n\n/** Removes a mode and its values; a collection keeps at least one mode. */\nexport function removeTokenMode(state: TokenState, collectionId: string, modeId: string): TokenState {\n\tconst collection = requireCollection(state, collectionId);\n\tconst mode = requireMode(collection, modeId);\n\tif (collection.modes.length < 2) throw new TokenError('last-mode', 'A collection keeps at least one mode');\n\tconst next = replaceCollection(state, { ...collection, modes: collection.modes.filter((m) => m.id !== mode.id) });\n\treturn {\n\t\t...next,\n\t\tvariables: next.variables.map((v) => {\n\t\t\tif (v.collectionId !== collectionId || !(mode.id in v.valuesByMode)) return v;\n\t\t\tconst values = { ...v.valuesByMode };\n\t\t\tdelete values[mode.id];\n\t\t\treturn { ...v, valuesByMode: values };\n\t\t})\n\t};\n}\n\n/** Moves a mode to index `to` (clamped). Index 0 makes it the default mode. */\nexport function moveTokenMode(state: TokenState, collectionId: string, modeId: string, to: number): TokenState {\n\tconst collection = requireCollection(state, collectionId);\n\tconst mode = requireMode(collection, modeId);\n\tconst modes = collection.modes.filter((m) => m.id !== mode.id);\n\tconst at = Math.min(Math.max(Number.isFinite(to) ? Math.trunc(to) : 0, 0), modes.length);\n\tmodes.splice(at, 0, mode);\n\treturn replaceCollection(state, { ...collection, modes });\n}\n\nexport interface CreateTokenVariableInput {\n\tcollectionId: string;\n\tname: string;\n\ttype: TokenType;\n\t/** Value for every mode (literal or `{ alias }`). Default: the type's default. */\n\tvalue?: unknown;\n\t/** Values by mode id or name (win over `value`). */\n\tvalues?: Readonly<Record<string, unknown>>;\n\tdescription?: string;\n\tscopes?: readonly string[];\n\tunit?: string;\n}\n\n/** A value for `variable`: a normalised literal or a checked alias. Throws when refused. */\nexport function prepareTokenValue(state: TokenState, variable: Pick<TokenVariable, 'id' | 'type' | 'name'>, value: unknown): TokenValue {\n\tif (isTokenAlias(value)) {\n\t\tconst error = checkTokenAlias(state, variable, value.alias);\n\t\tif (error) throw error;\n\t\treturn { alias: value.alias };\n\t}\n\tconst literal = coerceTokenLiteral(variable.type, value);\n\tif (literal === null) {\n\t\tthrow new TokenError('invalid-value', `\\`${String(value)}\\` is not a ${variable.type} value for \\`${variable.name}\\``);\n\t}\n\treturn literal;\n}\n\nfunction normalizeUnit(unit: unknown): string | undefined {\n\tif (unit === undefined || unit === null || unit === '') return undefined;\n\tif (typeof unit !== 'string' || !/^[a-z%]{1,8}$/i.test(unit)) throw new TokenError('invalid-value', `Unknown unit \\`${String(unit)}\\``);\n\treturn unit.toLowerCase();\n}\n\nexport function createTokenVariable(\n\tstate: TokenState,\n\tinput: CreateTokenVariableInput,\n\tcreateId: TokenIdFactory = defaultTokenId\n): { state: TokenState; variable: TokenVariable } {\n\tconst collection = requireCollection(state, input.collectionId);\n\tif (!(['color', 'number', 'string', 'boolean'] as unknown[]).includes(input.type)) {\n\t\tthrow new TokenError('invalid-type', `Unknown variable type \\`${String(input.type)}\\``);\n\t}\n\tconst name = normalizeTokenName(input.name);\n\tcheckVariableName(state, collection.id, name);\n\tconst id = createId('variable');\n\tconst stub = { id, type: input.type, name };\n\tconst base = input.value === undefined ? defaultTokenValue(input.type) : prepareTokenValue(state, stub, input.value);\n\tconst valuesByMode: Record<string, TokenValue> = {};\n\tfor (const mode of collection.modes) valuesByMode[mode.id] = base;\n\tif (input.values) {\n\t\tfor (const [key, raw] of Object.entries(input.values)) {\n\t\t\tconst mode = requireMode(collection, key);\n\t\t\tvaluesByMode[mode.id] = prepareTokenValue(state, stub, raw);\n\t\t}\n\t}\n\tconst variable: TokenVariable = {\n\t\tid,\n\t\tname,\n\t\tcollectionId: collection.id,\n\t\ttype: input.type,\n\t\tvaluesByMode,\n\t\t...(input.description ? { description: String(input.description) } : {}),\n\t\t...(input.scopes !== undefined ? { scopes: normalizeTokenScopes(input.type, input.scopes) } : {}),\n\t};\n\tif (variable.scopes === undefined) delete variable.scopes;\n\tconst unit = normalizeUnit(input.unit);\n\tif (unit) variable.unit = unit;\n\treturn { state: { ...state, variables: [...state.variables, variable] }, variable };\n}\n\n/**\n * Sets a variable's value in one mode (id or name; default: the default mode) to a literal or\n * `{ alias: variableId }`. Aliases must keep the type and not create a cycle.\n */\nexport function setTokenValue(state: TokenState, variableId: string, value: unknown, modeId?: string): TokenState {\n\tconst variable = requireVariable(state, variableId);\n\tconst collection = requireCollection(state, variable.collectionId);\n\tconst mode = modeId === undefined ? collection.modes[0] : requireMode(collection, modeId);\n\tconst prepared = prepareTokenValue(state, variable, value);\n\tconst current = variable.valuesByMode[mode.id];\n\tif (current === prepared || (isTokenAlias(current) && isTokenAlias(prepared) && current.alias === prepared.alias)) return state;\n\treturn replaceVariable(state, { ...variable, valuesByMode: { ...variable.valuesByMode, [mode.id]: prepared } });\n}\n\nexport function renameTokenVariable(state: TokenState, variableId: string, name: string): TokenState {\n\tconst variable = requireVariable(state, variableId);\n\tconst next = normalizeTokenName(name);\n\tif (next === variable.name) return state;\n\tcheckVariableName(state, variable.collectionId, next, variable.id);\n\treturn replaceVariable(state, { ...variable, name: next });\n}\n\nexport interface UpdateTokenVariableInput {\n\tdescription?: string;\n\t/** `null` clears the limit (every property). */\n\tscopes?: readonly string[] | null;\n\t/** `null` clears the unit. */\n\tunit?: string | null;\n}\n\nexport function updateTokenVariable(state: TokenState, variableId: string, input: UpdateTokenVariableInput): TokenState {\n\tconst variable = requireVariable(state, variableId);\n\tconst next: TokenVariable = { ...variable };\n\tif (input.description !== undefined) {\n\t\tif (input.description) next.description = String(input.description);\n\t\telse delete next.description;\n\t}\n\tif (input.scopes !== undefined) {\n\t\tconst scopes = normalizeTokenScopes(variable.type, input.scopes);\n\t\tif (scopes) next.scopes = scopes;\n\t\telse delete next.scopes;\n\t}\n\tif (input.unit !== undefined) {\n\t\tconst unit = normalizeUnit(input.unit);\n\t\tif (unit) next.unit = unit;\n\t\telse delete next.unit;\n\t}\n\treturn replaceVariable(state, next);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Validation of untrusted state\n\nexport interface TokenStateIssue {\n\tmessage: string;\n\tcollectionId?: string;\n\tvariableId?: string;\n}\n\n/**\n * Reads untrusted data (e.g. a saved `TokenState`) and keeps what is valid: junk collections,\n * modes and variables are dropped, bad values replaced by the type's default and alias cycles\n * broken, each with an issue.\n */\nexport function parseTokenState(input: unknown): { state: TokenState; issues: TokenStateIssue[] } {\n\tconst issues: TokenStateIssue[] = [];\n\tlet raw = input;\n\tif (typeof raw === 'string') {\n\t\ttry {\n\t\t\traw = JSON.parse(raw);\n\t\t} catch {\n\t\t\treturn { state: { collections: [], variables: [] }, issues: [{ message: 'Not JSON' }] };\n\t\t}\n\t}\n\tconst obj = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>;\n\tconst collections: TokenCollection[] = [];\n\tconst ids = new Set<string>();\n\tfor (const c of Array.isArray(obj.collections) ? obj.collections : []) {\n\t\tconst item = c as Partial<TokenCollection> | null;\n\t\tconst modes = Array.isArray(item?.modes)\n\t\t\t? (item!.modes as unknown[]).filter(\n\t\t\t\t\t(m): m is TokenMode => typeof m === 'object' && m !== null && typeof (m as TokenMode).id === 'string' && typeof (m as TokenMode).name === 'string'\n\t\t\t\t)\n\t\t\t: [];\n\t\tif (!item || typeof item.id !== 'string' || typeof item.name !== 'string' || modes.length === 0 || ids.has(item.id)) {\n\t\t\tissues.push({ message: 'Dropped an invalid collection' });\n\t\t\tcontinue;\n\t\t}\n\t\tids.add(item.id);\n\t\tcollections.push({ id: item.id, name: item.name, modes: modes.map((m) => ({ id: m.id, name: m.name })) });\n\t}\n\tconst byId = new Map(collections.map((c) => [c.id, c]));\n\tconst variables: TokenVariable[] = [];\n\tconst varIds = new Set<string>();\n\tfor (const v of Array.isArray(obj.variables) ? obj.variables : []) {\n\t\tconst item = v as Partial<TokenVariable> | null;\n\t\tconst collection = item && typeof item.collectionId === 'string' ? byId.get(item.collectionId) : undefined;\n\t\tif (\n\t\t\t!item ||\n\t\t\ttypeof item.id !== 'string' ||\n\t\t\ttypeof item.name !== 'string' ||\n\t\t\t!collection ||\n\t\t\t!(['color', 'number', 'string', 'boolean'] as unknown[]).includes(item.type) ||\n\t\t\tvarIds.has(item.id)\n\t\t) {\n\t\t\tissues.push({ message: 'Dropped an invalid variable', variableId: typeof item?.id === 'string' ? item.id : undefined });\n\t\t\tcontinue;\n\t\t}\n\t\tvarIds.add(item.id);\n\t\tconst type = item.type as TokenType;\n\t\tconst values: Record<string, TokenValue> = {};\n\t\tconst rawValues = (typeof item.valuesByMode === 'object' && item.valuesByMode !== null ? item.valuesByMode : {}) as Record<string, unknown>;\n\t\tfor (const mode of collection.modes) {\n\t\t\tconst value = rawValues[mode.id];\n\t\t\tif (isTokenAlias(value)) values[mode.id] = { alias: value.alias };\n\t\t\telse {\n\t\t\t\tconst literal = coerceTokenLiteral(type, value);\n\t\t\t\tif (literal === null) issues.push({ message: `\\`${item.name}\\` had no valid value in \\`${mode.name}\\``, variableId: item.id });\n\t\t\t\tvalues[mode.id] = literal ?? defaultTokenValue(type);\n\t\t\t}\n\t\t}\n\t\tconst variable: TokenVariable = { id: item.id, name: item.name, collectionId: collection.id, type, valuesByMode: values };\n\t\tif (typeof item.description === 'string' && item.description) variable.description = item.description;\n\t\tif (Array.isArray(item.scopes)) {\n\t\t\ttry {\n\t\t\t\tconst scopes = normalizeTokenScopes(type, item.scopes as string[]);\n\t\t\t\tif (scopes) variable.scopes = scopes;\n\t\t\t} catch {\n\t\t\t\tissues.push({ message: `Dropped unknown scopes of \\`${item.name}\\``, variableId: item.id });\n\t\t\t}\n\t\t}\n\t\tif (typeof item.unit === 'string' && /^[a-z%]{1,8}$/i.test(item.unit)) variable.unit = item.unit.toLowerCase();\n\t\tvariables.push(variable);\n\t}\n\tlet state: TokenState = { collections, variables };\n\t// Aliases: drop missing / mistyped targets and break cycles.\n\tconst fixed = state.variables.map((variable) => {\n\t\tlet values: Record<string, TokenValue> | null = null;\n\t\tfor (const [modeId, value] of Object.entries(variable.valuesByMode)) {\n\t\t\tif (!isTokenAlias(value)) continue;\n\t\t\tconst target = state.variables.find((t) => t.id === value.alias);\n\t\t\tif (!target || target.type !== variable.type) {\n\t\t\t\tvalues ??= { ...variable.valuesByMode };\n\t\t\t\tvalues[modeId] = defaultTokenValue(variable.type);\n\t\t\t\tissues.push({ message: `\\`${variable.name}\\` aliased a missing or mistyped variable`, variableId: variable.id });\n\t\t\t}\n\t\t}\n\t\treturn values ? { ...variable, valuesByMode: values } : variable;\n\t});\n\tstate = { collections, variables: fixed };\n\t// Cycle breaking: rebuild alias by alias, keeping only those that do not close a loop.\n\tconst literalOnly = fixed.map((variable) => {\n\t\tconst values: Record<string, TokenValue> = {};\n\t\tfor (const [modeId, value] of Object.entries(variable.valuesByMode)) values[modeId] = isTokenAlias(value) ? defaultTokenValue(variable.type) : value;\n\t\treturn { ...variable, valuesByMode: values };\n\t});\n\tlet rebuilt: TokenState = { collections, variables: literalOnly };\n\tfor (const variable of fixed) {\n\t\tfor (const [modeId, value] of Object.entries(variable.valuesByMode)) {\n\t\t\tif (!isTokenAlias(value)) continue;\n\t\t\tconst error = checkTokenAlias(rebuilt, variable, value.alias);\n\t\t\tif (error) {\n\t\t\t\tissues.push({ message: `\\`${variable.name}\\`: ${error.message}`, variableId: variable.id });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst current = getTokenVariable(rebuilt, variable.id)!;\n\t\t\trebuilt = replaceVariable(rebuilt, { ...current, valuesByMode: { ...current.valuesByMode, [modeId]: { alias: value.alias } } });\n\t\t}\n\t}\n\treturn { state: rebuilt, issues };\n}\n","import {\n\taddTokenMode,\n\tcreateTokenCollection,\n\tcreateTokenVariable,\n\tdefaultTokenId,\n\tdeleteTokenCollection,\n\tdeleteTokenVariables,\n\tmoveTokenMode,\n\tparseTokenState,\n\tremoveTokenMode,\n\trenameTokenCollection,\n\trenameTokenMode,\n\trenameTokenVariable,\n\tresolveToken,\n\tresolveTokenValue,\n\tsetTokenValue,\n\tupdateTokenVariable,\n\ttype CreateTokenCollectionInput,\n\ttype CreateTokenVariableInput,\n\ttype TokenIdFactory,\n\ttype TokenResolution,\n\ttype UpdateTokenVariableInput\n} from './model.js';\nimport type { TokenCollection, TokenLiteral, TokenMode, TokenModeContext, TokenState, TokenVariable } from './types.js';\nimport { EMPTY_TOKEN_STATE } from './types.js';\n\n/** Why the state changed. */\nexport type TokenChangeSource = 'edit' | 'undo' | 'redo' | 'replace';\n\nexport interface TokenChangeEvent {\n\tsource: TokenChangeSource;\n\t/** Operation name (`setValue`, `deleteVariables`, a `transact` label, …). */\n\treason: string;\n\tstate: TokenState;\n\tprevious: TokenState;\n\t/**\n\t * Variables this edit deleted (also via `deleteCollection`). Detach canvas bindings to them\n\t * with `detachTokenBindings(nodes, event.previous, event.deletedVariableIds)`.\n\t */\n\tdeletedVariableIds: readonly string[];\n}\n\nexport type TokenChangeListener = (event: TokenChangeEvent) => void;\n\nexport interface TokenStoreOptions {\n\tinitialState?: TokenState;\n\tcreateId?: TokenIdFactory;\n\t/** Undo steps kept (default 100). */\n\thistoryLimit?: number;\n}\n\ninterface Pending {\n\treason: string;\n\tprevious: TokenState;\n\tdeleted: string[];\n}\n\n/**\n * Undoable design-token store. Every edit is one undo step (group several with `transact`)\n * and notifies subscribers once. `getState()` returns an immutable snapshot whose reference\n * only changes on edits, so it works with `useSyncExternalStore` and Svelte stores.\n * Refused edits throw a `TokenError` and change nothing.\n */\nexport class TokenStore {\n\tprivate state: TokenState;\n\tprivate undoStack: { state: TokenState; reason: string }[] = [];\n\tprivate redoStack: { state: TokenState; reason: string }[] = [];\n\tprivate listeners = new Set<TokenChangeListener>();\n\tprivate pending: Pending | null = null;\n\tprivate depth = 0;\n\tprivate readonly createId: TokenIdFactory;\n\tprivate readonly historyLimit: number;\n\n\tconstructor(options: TokenStoreOptions = {}) {\n\t\tthis.state = options.initialState ?? EMPTY_TOKEN_STATE;\n\t\tthis.createId = options.createId ?? defaultTokenId;\n\t\tthis.historyLimit = Math.max(0, options.historyLimit ?? 100);\n\t}\n\n\tgetState = (): TokenState => this.state;\n\n\tsubscribe = (listener: TokenChangeListener): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\tget collections(): readonly TokenCollection[] {\n\t\treturn this.state.collections;\n\t}\n\n\tget variables(): readonly TokenVariable[] {\n\t\treturn this.state.variables;\n\t}\n\n\tcanUndo(): boolean {\n\t\treturn this.undoStack.length > 0;\n\t}\n\n\tcanRedo(): boolean {\n\t\treturn this.redoStack.length > 0;\n\t}\n\n\t/** Resolves a variable under `modes` (see `resolveToken`). */\n\tresolve(id: string, modes?: TokenModeContext): TokenResolution {\n\t\treturn resolveToken(this.state, id, modes);\n\t}\n\n\tresolveValue(id: string, modes?: TokenModeContext): TokenLiteral | undefined {\n\t\treturn resolveTokenValue(this.state, id, modes);\n\t}\n\n\t/**\n\t * Runs `fn` as one undo step with one change event. If `fn` throws, every change it made is\n\t * rolled back and the error rethrown.\n\t */\n\ttransact<T>(reason: string, fn: (store: this) => T): T {\n\t\tconst outer = this.depth === 0;\n\t\tif (outer) this.pending = { reason, previous: this.state, deleted: [] };\n\t\tthis.depth += 1;\n\t\ttry {\n\t\t\tconst result = fn(this);\n\t\t\tthis.depth -= 1;\n\t\t\tif (outer) this.flush();\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tthis.depth -= 1;\n\t\t\tif (outer) {\n\t\t\t\tthis.state = this.pending!.previous;\n\t\t\t\tthis.pending = null;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate apply(reason: string, next: TokenState, deleted: readonly string[] = []): void {\n\t\tif (next === this.state) return;\n\t\tif (this.depth > 0) {\n\t\t\tthis.state = next;\n\t\t\tthis.pending!.deleted.push(...deleted);\n\t\t\treturn;\n\t\t}\n\t\tthis.pending = { reason, previous: this.state, deleted: [...deleted] };\n\t\tthis.state = next;\n\t\tthis.flush();\n\t}\n\n\tprivate flush(): void {\n\t\tconst pending = this.pending!;\n\t\tthis.pending = null;\n\t\tif (pending.previous === this.state) return;\n\t\tthis.undoStack.push({ state: pending.previous, reason: pending.reason });\n\t\tif (this.undoStack.length > this.historyLimit) this.undoStack.splice(0, this.undoStack.length - this.historyLimit);\n\t\tthis.redoStack = [];\n\t\tthis.emit({ source: 'edit', reason: pending.reason, state: this.state, previous: pending.previous, deletedVariableIds: pending.deleted });\n\t}\n\n\tprivate emit(event: TokenChangeEvent): void {\n\t\tfor (const listener of [...this.listeners]) listener(event);\n\t}\n\n\tundo(): boolean {\n\t\tconst entry = this.undoStack.pop();\n\t\tif (!entry) return false;\n\t\tconst previous = this.state;\n\t\tthis.redoStack.push({ state: previous, reason: entry.reason });\n\t\tthis.state = entry.state;\n\t\tthis.emit({ source: 'undo', reason: entry.reason, state: this.state, previous, deletedVariableIds: [] });\n\t\treturn true;\n\t}\n\n\tredo(): boolean {\n\t\tconst entry = this.redoStack.pop();\n\t\tif (!entry) return false;\n\t\tconst previous = this.state;\n\t\tthis.undoStack.push({ state: previous, reason: entry.reason });\n\t\tthis.state = entry.state;\n\t\tthis.emit({ source: 'redo', reason: entry.reason, state: this.state, previous, deletedVariableIds: [] });\n\t\treturn true;\n\t}\n\n\t/**\n\t * Replaces the whole state (e.g. after loading a file). Untrusted data should go through\n\t * `parseTokenState` first. With `record: true` it is an undo step; otherwise history is cleared.\n\t */\n\treplaceState(state: TokenState, options: { record?: boolean; reason?: string } = {}): void {\n\t\tif (options.record) {\n\t\t\tthis.apply(options.reason ?? 'replace', state);\n\t\t\treturn;\n\t\t}\n\t\tconst previous = this.state;\n\t\tthis.state = state;\n\t\tthis.undoStack = [];\n\t\tthis.redoStack = [];\n\t\tthis.emit({ source: 'replace', reason: options.reason ?? 'replace', state, previous, deletedVariableIds: [] });\n\t}\n\n\t/** Loads untrusted JSON (or an object) as the new state; returns the issues found. */\n\tload(input: unknown): ReturnType<typeof parseTokenState>['issues'] {\n\t\tconst { state, issues } = parseTokenState(input);\n\t\tthis.replaceState(state, { reason: 'load' });\n\t\treturn issues;\n\t}\n\n\t/** The state as JSON. */\n\ttoJSON(): TokenState {\n\t\treturn this.state;\n\t}\n\n\t// --- Collections and modes -----------------------------------------------------------------\n\n\tcreateCollection(name: string, modes?: readonly string[]): TokenCollection {\n\t\tconst input: CreateTokenCollectionInput = { name, modes };\n\t\tconst result = createTokenCollection(this.state, input, this.createId);\n\t\tthis.apply('createCollection', result.state);\n\t\treturn result.collection;\n\t}\n\n\trenameCollection(id: string, name: string): void {\n\t\tthis.apply('renameCollection', renameTokenCollection(this.state, id, name));\n\t}\n\n\tdeleteCollection(id: string): string[] {\n\t\tconst result = deleteTokenCollection(this.state, id);\n\t\tthis.apply('deleteCollection', result.state, result.deleted);\n\t\treturn result.deleted;\n\t}\n\n\taddMode(collectionId: string, name: string, options: { from?: string } = {}): TokenMode {\n\t\tconst result = addTokenMode(this.state, collectionId, name, options, this.createId);\n\t\tthis.apply('addMode', result.state);\n\t\treturn result.mode;\n\t}\n\n\trenameMode(collectionId: string, modeId: string, name: string): void {\n\t\tthis.apply('renameMode', renameTokenMode(this.state, collectionId, modeId, name));\n\t}\n\n\tremoveMode(collectionId: string, modeId: string): void {\n\t\tthis.apply('removeMode', removeTokenMode(this.state, collectionId, modeId));\n\t}\n\n\tmoveMode(collectionId: string, modeId: string, to: number): void {\n\t\tthis.apply('moveMode', moveTokenMode(this.state, collectionId, modeId, to));\n\t}\n\n\t/** Makes a mode the default by moving it first. */\n\tsetDefaultMode(collectionId: string, modeId: string): void {\n\t\tthis.apply('setDefaultMode', moveTokenMode(this.state, collectionId, modeId, 0));\n\t}\n\n\t// --- Variables -----------------------------------------------------------------------------\n\n\tcreateVariable(input: CreateTokenVariableInput): TokenVariable {\n\t\tconst result = createTokenVariable(this.state, input, this.createId);\n\t\tthis.apply('createVariable', result.state);\n\t\treturn result.variable;\n\t}\n\n\t/** Sets a literal or `{ alias }` in one mode (id or name; default: the default mode). */\n\tsetValue(variableId: string, value: unknown, modeId?: string): void {\n\t\tthis.apply('setValue', setTokenValue(this.state, variableId, value, modeId));\n\t}\n\n\trenameVariable(variableId: string, name: string): void {\n\t\tthis.apply('renameVariable', renameTokenVariable(this.state, variableId, name));\n\t}\n\n\tupdateVariable(variableId: string, input: UpdateTokenVariableInput): void {\n\t\tthis.apply('updateVariable', updateTokenVariable(this.state, variableId, input));\n\t}\n\n\t/** Deletes variables; aliases to them take their values. Returns the ids deleted. */\n\tdeleteVariables(ids: string | Iterable<string>): string[] {\n\t\tconst result = deleteTokenVariables(this.state, typeof ids === 'string' ? [ids] : ids);\n\t\tthis.apply('deleteVariables', result.state, result.deleted);\n\t\treturn result.deleted;\n\t}\n\n\t/** Applies a pure state transform (e.g. `importW3CTokens`) as one undo step. */\n\tupdate(reason: string, fn: (state: TokenState) => TokenState): void {\n\t\tthis.apply(reason, fn(this.state));\n\t}\n}\n\nexport function createTokenStore(options: TokenStoreOptions = {}): TokenStore {\n\treturn new TokenStore(options);\n}\n","// Portions ported from figcraft/crates/engine/src/variables_io_tests.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { getCurrentMode, getTokenCollection, getTokenVariable, resolveToken } from './model.js';\nimport { isTokenAlias, type TokenCollection, type TokenLiteral, type TokenMode, type TokenModeContext, type TokenState, type TokenVariable } from './types.js';\n\nexport interface TokenCssOptions {\n\t/** Collections to export (ids; default all). */\n\tcollections?: readonly string[];\n\t/** Prefix after `--` (e.g. `ds-` → `--ds-color-bg`). */\n\tprefix?: string;\n\t/** Also prefix each variable with its collection name (avoids clashes between collections). */\n\tcollectionPrefix?: boolean;\n\t/** Root selector (default `:root`). */\n\tselector?: string;\n\t/** Attribute that selects a mode (default `data-mode`), or one per collection. */\n\tattribute?: string | ((collection: TokenCollection) => string);\n\t/** Attribute value for a mode (default: the mode name as a lowercase slug, e.g. `dark`). */\n\tmodeValue?: (mode: TokenMode, collection: TokenCollection) => string;\n\t/**\n\t * Also emit `[data-mode=\"…\"]` rules that match any element (not just the root), so a subtree\n\t * can switch mode. Default `false`.\n\t */\n\tnested?: boolean;\n\t/** Formats numbers (default: the number with the variable's `unit`, if any). */\n\tformatNumber?: (value: number, variable: TokenVariable) => string;\n}\n\n/** Lowercase slug of a name: groups and spaces become `-` (`Color/Bg Muted` → `color-bg-muted`). */\nexport function tokenSlug(name: string): string {\n\tlet out = '';\n\tlet dash = false;\n\tfor (const ch of name.toLowerCase()) {\n\t\tif ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch === '_') {\n\t\t\tif (dash && out) out += '-';\n\t\t\tout += ch;\n\t\t\tdash = false;\n\t\t} else dash = true;\n\t}\n\treturn out || 'token';\n}\n\n/** The CSS custom property for a variable (e.g. `--color-bg`). */\nexport function getTokenCssName(state: TokenState, variable: TokenVariable, options: Pick<TokenCssOptions, 'prefix' | 'collectionPrefix'> = {}): string {\n\tconst collection = getTokenCollection(state, variable.collectionId);\n\tconst head = options.collectionPrefix && collection ? `${tokenSlug(collection.name)}-` : '';\n\tconst prefix = options.prefix ? `${tokenSlug(options.prefix)}-` : '';\n\treturn `--${prefix}${head}${tokenSlug(variable.name)}`;\n}\n\n/** A CSS string literal with `\"`, `\\`, newlines and `<` escaped. */\nexport function cssString(value: string): string {\n\tlet out = '\"';\n\tfor (const ch of value) {\n\t\tif (ch === '\"' || ch === '\\\\') out += '\\\\' + ch;\n\t\telse if (ch === '\\n') out += '\\\\a ';\n\t\telse if (ch === '\\r') out += '\\\\d ';\n\t\telse if (ch === '<') out += '\\\\3c ';\n\t\telse out += ch;\n\t}\n\treturn out + '\"';\n}\n\n/** A literal as CSS. */\nexport function formatTokenCssValue(value: TokenLiteral, variable: TokenVariable, options: Pick<TokenCssOptions, 'formatNumber'> = {}): string {\n\tswitch (variable.type) {\n\t\tcase 'color':\n\t\t\treturn String(value);\n\t\tcase 'number':\n\t\t\treturn options.formatNumber ? options.formatNumber(value as number, variable) : `${value}${variable.unit ?? ''}`;\n\t\tcase 'string':\n\t\t\treturn cssString(String(value));\n\t\tcase 'boolean':\n\t\t\treturn value ? 'true' : 'false';\n\t}\n}\n\nconst defaultModeValue = (mode: TokenMode) => tokenSlug(mode.name);\n\nfunction attributeFor(options: TokenCssOptions, collection: TokenCollection): string {\n\tconst attr = typeof options.attribute === 'function' ? options.attribute(collection) : options.attribute ?? 'data-mode';\n\treturn tokenSlug(attr);\n}\n\n/**\n * Flat CSS custom properties per mode: each collection's default mode on `:root`, its other\n * modes on `:root[data-mode=\"dark\"]`. Aliases to exported variables become `var(--target)`, so\n * switching the attribute re-themes everything; aliases to other variables are resolved.\n */\nexport function exportTokensCss(state: TokenState, options: TokenCssOptions = {}): string {\n\tconst selector = options.selector ?? ':root';\n\tconst wanted = options.collections ? new Set(options.collections) : null;\n\tconst collections = state.collections.filter((c) => !wanted || wanted.has(c.id));\n\tconst exported = new Set(state.variables.filter((v) => collections.some((c) => c.id === v.collectionId)).map((v) => v.id));\n\tconst modeValue = options.modeValue ?? defaultModeValue;\n\n\tconst declaration = (variable: TokenVariable, collection: TokenCollection, mode: TokenMode): string | null => {\n\t\tconst value = variable.valuesByMode[mode.id];\n\t\tif (isTokenAlias(value) && exported.has(value.alias)) {\n\t\t\tconst target = getTokenVariable(state, value.alias)!;\n\t\t\treturn ` ${getTokenCssName(state, variable, options)}: var(${getTokenCssName(state, target, options)});`;\n\t\t}\n\t\tconst resolved = resolveToken(state, variable.id, { [collection.id]: mode.id });\n\t\tif (!resolved.ok) return null;\n\t\treturn ` ${getTokenCssName(state, variable, options)}: ${formatTokenCssValue(resolved.value, variable, options)};`;\n\t};\n\n\tconst blocks: string[] = [];\n\tconst rootLines: string[] = [];\n\tfor (const collection of collections) {\n\t\tconst vars = state.variables.filter((v) => v.collectionId === collection.id);\n\t\tfor (const v of vars) {\n\t\t\tconst line = declaration(v, collection, collection.modes[0]);\n\t\t\tif (line) rootLines.push(line);\n\t\t}\n\t}\n\tconst rootSelectors = [selector];\n\tif (options.nested) {\n\t\tfor (const collection of collections) {\n\t\t\trootSelectors.push(`[${attributeFor(options, collection)}=\"${tokenSlug(modeValue(collection.modes[0], collection))}\"]`);\n\t\t}\n\t}\n\tblocks.push(`${[...new Set(rootSelectors)].join(', ')} {\\n${rootLines.join('\\n')}${rootLines.length ? '\\n' : ''}}`);\n\tfor (const collection of collections) {\n\t\tconst vars = state.variables.filter((v) => v.collectionId === collection.id);\n\t\tconst attr = attributeFor(options, collection);\n\t\tfor (const mode of collection.modes.slice(1)) {\n\t\t\tconst lines = vars.map((v) => declaration(v, collection, mode)).filter((l): l is string => l !== null);\n\t\t\tconst value = tokenSlug(modeValue(mode, collection));\n\t\t\tconst selectors = [`${selector}[${attr}=\"${value}\"]`];\n\t\t\tif (options.nested) selectors.push(`[${attr}=\"${value}\"]`);\n\t\t\tblocks.push(`${selectors.join(', ')} {\\n${lines.join('\\n')}${lines.length ? '\\n' : ''}}`);\n\t\t}\n\t}\n\treturn blocks.join('\\n\\n') + '\\n';\n}\n\n/**\n * Resolved CSS custom properties for one mode context, e.g. for an element's inline style:\n * `{ '--color-bg': '#ffffff', … }`. Aliases are resolved (no `var()`).\n */\nexport function getTokenCssVariables(\n\tstate: TokenState,\n\tmodes?: TokenModeContext,\n\toptions: Omit<TokenCssOptions, 'selector' | 'attribute' | 'modeValue' | 'nested'> = {}\n): Record<string, string> {\n\tconst wanted = options.collections ? new Set(options.collections) : null;\n\tconst out: Record<string, string> = {};\n\tfor (const variable of state.variables) {\n\t\tif (wanted && !wanted.has(variable.collectionId)) continue;\n\t\tconst collection = getTokenCollection(state, variable.collectionId);\n\t\tif (!collection) continue;\n\t\tconst resolved = resolveToken(state, variable.id, { ...modes, [collection.id]: getCurrentMode(collection, modes).id });\n\t\tif (resolved.ok) out[getTokenCssName(state, variable, options)] = formatTokenCssValue(resolved.value, variable, options);\n\t}\n\treturn out;\n}\n","// Portions ported from figcraft/crates/engine/src/variables_io_tests.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { hexToRgba, normalizeTokenColor } from './color.js';\nimport {\n\taddTokenMode,\n\tcheckTokenAlias,\n\tcoerceTokenLiteral,\n\tcreateTokenCollection,\n\tcreateTokenVariable,\n\tdefaultTokenId,\n\tfindTokenCollection,\n\tfindTokenMode,\n\tfindTokenVariable,\n\tgetTokenCollection,\n\tgetTokenVariable,\n\tnormalizeTokenName,\n\tsetTokenValue,\n\tupdateTokenVariable,\n\ttype TokenIdFactory\n} from './model.js';\nimport {\n\tTokenError,\n\tisTokenAlias,\n\ttype TokenCollection,\n\ttype TokenLiteral,\n\ttype TokenModeContext,\n\ttype TokenState,\n\ttype TokenType,\n\ttype TokenValue,\n\ttype TokenVariable\n} from './types.js';\n\n/**\n * W3C Design Tokens (DTCG) JSON. Each collection is a top-level group named after it; variable\n * names' `/` groups become nested groups; aliases are `{Collection.group.token}` references.\n * `$value` holds the default mode (or the modes passed in). Modes, ids and scopes ride along in\n * `$extensions[\"com.pixerate.tokens\"]`, so an export round-trips; tools that ignore extensions\n * still read the default mode. Strings and booleans use `$type: \"string\"` / `\"boolean\"`\n * (outside the spec, as Tokens Studio and Style Dictionary do).\n */\nexport const W3C_TOKENS_EXTENSION = 'com.pixerate.tokens';\n\nexport interface W3CTokensExportOptions {\n\t/** Collections to export (ids; default all). */\n\tcollections?: readonly string[];\n\t/** Modes that supply `$value` (default: each collection's default mode). */\n\tmodes?: TokenModeContext;\n\t/** Include `$extensions` with ids, every mode's value and scopes (default `true`). */\n\textensions?: boolean;\n\t/** Colours as `#hex` strings (default) or W3C colour objects. */\n\tcolorFormat?: 'hex' | 'object';\n}\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json };\n\nfunction path(name: string): string[] {\n\treturn name.split('/');\n}\n\nfunction reference(state: TokenState, variable: TokenVariable): string {\n\tconst collection = getTokenCollection(state, variable.collectionId);\n\treturn `{${[collection?.name ?? variable.collectionId, ...path(variable.name)].join('.')}}`;\n}\n\nfunction w3cType(variable: TokenVariable): string {\n\tif (variable.type === 'number') {\n\t\tif (variable.unit === 'ms' || variable.unit === 's') return 'duration';\n\t\tif (variable.unit) return 'dimension';\n\t}\n\treturn variable.type;\n}\n\nfunction w3cLiteral(variable: TokenVariable, value: TokenLiteral, colorFormat: 'hex' | 'object'): Json {\n\tif (variable.type === 'color' && colorFormat === 'object') {\n\t\tconst c = hexToRgba(String(value));\n\t\tif (c) {\n\t\t\tconst round = (n: number) => Math.round(n * 10000) / 10000;\n\t\t\treturn { colorSpace: 'srgb', components: [round(c.r), round(c.g), round(c.b)], alpha: round(c.a), hex: String(value).slice(0, 7) };\n\t\t}\n\t}\n\tif (variable.type === 'number' && variable.unit) return { value: value as number, unit: variable.unit };\n\treturn value;\n}\n\nfunction w3cValue(state: TokenState, variable: TokenVariable, value: TokenValue | undefined, colorFormat: 'hex' | 'object'): Json {\n\tif (value === undefined) return null;\n\tif (isTokenAlias(value)) {\n\t\tconst target = getTokenVariable(state, value.alias);\n\t\treturn target ? reference(state, target) : null;\n\t}\n\treturn w3cLiteral(variable, value, colorFormat);\n}\n\n/** The tokens as a W3C Design Tokens object (see {@link W3C_TOKENS_EXTENSION}). */\nexport function exportW3CTokens(state: TokenState, options: W3CTokensExportOptions = {}): Record<string, Json> {\n\tconst withExtensions = options.extensions !== false;\n\tconst colorFormat = options.colorFormat ?? 'hex';\n\tconst wanted = options.collections ? new Set(options.collections) : null;\n\tconst root: Record<string, Json> = {};\n\tfor (const collection of state.collections) {\n\t\tif (wanted && !wanted.has(collection.id)) continue;\n\t\tconst group: Record<string, Json> = {};\n\t\tif (withExtensions) {\n\t\t\tgroup.$extensions = {\n\t\t\t\t[W3C_TOKENS_EXTENSION]: { id: collection.id, modes: collection.modes.map((m) => ({ id: m.id, name: m.name })) }\n\t\t\t};\n\t\t}\n\t\tconst chosen = options.modes?.[collection.id];\n\t\tconst mode = (chosen !== undefined && collection.modes.find((m) => m.id === chosen)) || collection.modes[0];\n\t\tfor (const variable of state.variables) {\n\t\t\tif (variable.collectionId !== collection.id) continue;\n\t\t\tconst token: Record<string, Json> = {\n\t\t\t\t$type: w3cType(variable),\n\t\t\t\t$value: w3cValue(state, variable, variable.valuesByMode[mode.id], colorFormat)\n\t\t\t};\n\t\t\tif (variable.description) token.$description = variable.description;\n\t\t\tif (withExtensions) {\n\t\t\t\tconst modes: Record<string, Json> = {};\n\t\t\t\tfor (const m of collection.modes) modes[m.name] = w3cValue(state, variable, variable.valuesByMode[m.id], colorFormat);\n\t\t\t\tconst ext: Record<string, Json> = { id: variable.id, modes };\n\t\t\t\tif (variable.scopes) ext.scopes = [...variable.scopes];\n\t\t\t\tif (variable.unit) ext.unit = variable.unit;\n\t\t\t\ttoken.$extensions = { [W3C_TOKENS_EXTENSION]: ext };\n\t\t\t}\n\t\t\tlet at = group;\n\t\t\tconst segments = path(variable.name);\n\t\t\tfor (const segment of segments.slice(0, -1)) {\n\t\t\t\tconst next = at[segment];\n\t\t\t\tif (typeof next !== 'object' || next === null || Array.isArray(next) || '$value' in next) at[segment] = {};\n\t\t\t\tat = at[segment] as Record<string, Json>;\n\t\t\t}\n\t\t\tat[segments[segments.length - 1]] = token;\n\t\t}\n\t\troot[collection.name] = group;\n\t}\n\treturn root;\n}\n\n/** {@link exportW3CTokens} as indented JSON text. */\nexport function exportW3CTokensJson(state: TokenState, options: W3CTokensExportOptions = {}): string {\n\treturn JSON.stringify(exportW3CTokens(state, options), null, 2);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Import\n\nexport interface W3CTokensImportOptions {\n\t/**\n\t * Collection for tokens outside a marked collection group (a plain W3C file). Default\n\t * `\"Tokens\"`; an existing collection with that name is updated.\n\t */\n\tcollection?: string;\n\t/** Mode that plain `$value`s go to (name; created when missing). Default: the default mode. */\n\tmode?: string;\n\tcreateId?: TokenIdFactory;\n}\n\nexport interface W3CTokensImportReport {\n\tcollectionsAdded: number;\n\tmodesAdded: number;\n\tvariablesAdded: number;\n\t/** Existing variables (matched by collection and name) that were updated in place. */\n\tvariablesUpdated: number;\n\t/** Entries skipped or values not taken, with the reason. */\n\twarnings: string[];\n}\n\ninterface RawToken {\n\tcollection: string;\n\tpath: string[];\n\ttype: string | undefined;\n\tvalue: unknown;\n\tdescription: unknown;\n\text: Record<string, unknown> | undefined;\n}\n\nconst MAX_DEPTH = 32;\nconst REF = /^\\{([^{}]+)\\}$/;\nconst MEASURE = /^(-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)\\s*([a-z%]*)$/i;\nconst FONT_WEIGHTS: Record<string, number> = {\n\tthin: 100,\n\thairline: 100,\n\t'extra-light': 200,\n\t'ultra-light': 200,\n\tlight: 300,\n\tnormal: 400,\n\tregular: 400,\n\tbook: 400,\n\tmedium: 500,\n\t'semi-bold': 600,\n\t'demi-bold': 600,\n\tbold: 700,\n\t'extra-bold': 800,\n\t'ultra-bold': 800,\n\tblack: 900,\n\theavy: 900,\n\t'extra-black': 950,\n\t'ultra-black': 950\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nfunction extensionOf(node: Record<string, unknown>): Record<string, unknown> | undefined {\n\tconst ext = node.$extensions;\n\tif (!isObject(ext)) return undefined;\n\tconst ours = ext[W3C_TOKENS_EXTENSION];\n\treturn isObject(ours) ? ours : undefined;\n}\n\nfunction aliasRef(value: unknown): string | null {\n\tif (typeof value !== 'string' || value.length > 1000) return null;\n\tconst match = REF.exec(value.trim());\n\treturn match ? match[1].trim() : null;\n}\n\n/** W3C type → our type, or `null` for types we don't take (composites). */\nfunction mapType(type: string): TokenType | null {\n\tswitch (type) {\n\t\tcase 'color':\n\t\t\treturn 'color';\n\t\tcase 'number':\n\t\tcase 'dimension':\n\t\tcase 'duration':\n\t\tcase 'fontWeight':\n\t\t\treturn 'number';\n\t\tcase 'string':\n\t\tcase 'text':\n\t\tcase 'fontFamily':\n\t\tcase 'fontStyle':\n\t\t\treturn 'string';\n\t\tcase 'boolean':\n\t\t\treturn 'boolean';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction inferType(value: unknown): string | undefined {\n\tif (typeof value === 'boolean') return 'boolean';\n\tif (typeof value === 'number') return 'number';\n\tif (typeof value === 'string') {\n\t\tconst text = value.trim();\n\t\tif ((text.startsWith('#') || /^rgba?\\(/i.test(text)) && normalizeTokenColor(text)) return 'color';\n\t\tif (MEASURE.test(text) && /[a-z%]$/i.test(text)) return 'dimension';\n\t\treturn 'string';\n\t}\n\tif (isObject(value) && Array.isArray(value.components)) return 'color';\n\tif (isObject(value) && typeof value.value === 'number' && typeof value.unit === 'string') return 'dimension';\n\treturn undefined;\n}\n\n/** A literal and (for numbers) unit from a W3C value of `w3cType`, or `null`. */\nfunction readLiteral(w3cType: string, type: TokenType, value: unknown): { value: TokenLiteral; unit?: string } | null {\n\tif (type === 'number') {\n\t\tif (w3cType === 'fontWeight' && typeof value === 'string') {\n\t\t\tconst weight = FONT_WEIGHTS[value.trim().toLowerCase()];\n\t\t\treturn weight === undefined ? null : { value: weight };\n\t\t}\n\t\tif (isObject(value) && typeof value.value === 'number' && Number.isFinite(value.value)) {\n\t\t\tconst unit = typeof value.unit === 'string' && /^[a-z%]{1,8}$/i.test(value.unit) ? value.unit.toLowerCase() : undefined;\n\t\t\treturn { value: value.value, unit };\n\t\t}\n\t\tif (typeof value === 'string' && value.length <= 100) {\n\t\t\tconst match = MEASURE.exec(value.trim());\n\t\t\tif (!match) return null;\n\t\t\tconst n = Number(match[1]);\n\t\t\tif (!Number.isFinite(n)) return null;\n\t\t\tconst unit = match[2] ? match[2].toLowerCase() : undefined;\n\t\t\treturn { value: n, unit: unit && unit.length <= 8 ? unit : undefined };\n\t\t}\n\t\tconst n = coerceTokenLiteral('number', value);\n\t\treturn n === null ? null : { value: n };\n\t}\n\tif (type === 'string' && w3cType === 'fontFamily' && Array.isArray(value)) {\n\t\treturn value.every((v) => typeof v === 'string') ? { value: value.join(', ') } : null;\n\t}\n\tconst literal = coerceTokenLiteral(type, value);\n\treturn literal === null ? null : { value: literal };\n}\n\nfunction collectTokens(\n\tgroup: Record<string, unknown>,\n\tcollection: string,\n\tprefix: string[],\n\tinheritedType: string | undefined,\n\tout: RawToken[],\n\twarnings: string[],\n\tdepth: number\n): void {\n\tif (depth > MAX_DEPTH) {\n\t\twarnings.push(`\\`${prefix.join('.')}\\` is nested too deeply; skipped`);\n\t\treturn;\n\t}\n\tconst groupType = typeof group.$type === 'string' ? group.$type : inheritedType;\n\tfor (const [key, child] of Object.entries(group)) {\n\t\tif (key.startsWith('$')) continue;\n\t\tconst at = [...prefix, key];\n\t\tif (!isObject(child)) {\n\t\t\twarnings.push(`\\`${at.join('.')}\\` is not a token or group; skipped`);\n\t\t\tcontinue;\n\t\t}\n\t\tif ('$value' in child) {\n\t\t\tout.push({\n\t\t\t\tcollection,\n\t\t\t\tpath: at,\n\t\t\t\ttype: typeof child.$type === 'string' ? child.$type : groupType,\n\t\t\t\tvalue: child.$value,\n\t\t\t\tdescription: child.$description,\n\t\t\t\text: extensionOf(child)\n\t\t\t});\n\t\t} else collectTokens(child, collection, at, groupType, out, warnings, depth + 1);\n\t}\n}\n\n/**\n * Merges a W3C Design Tokens document (object or JSON text) into `state`. Collections, modes\n * and variables are matched by name and updated in place (ids, and so canvas bindings, are\n * kept); new ones take the ids in the file's extensions when free. Junk entries, type clashes,\n * unresolved references and alias cycles are skipped with a warning. Throws `invalid-input`\n * only when the input is not a JSON object.\n */\nexport function importW3CTokens(\n\tstate: TokenState,\n\tinput: unknown,\n\toptions: W3CTokensImportOptions = {}\n): { state: TokenState; report: W3CTokensImportReport } {\n\tlet doc = input;\n\tif (typeof doc === 'string') {\n\t\ttry {\n\t\t\tdoc = JSON.parse(doc);\n\t\t} catch {\n\t\t\tthrow new TokenError('invalid-input', 'Not JSON');\n\t\t}\n\t}\n\tif (!isObject(doc)) throw new TokenError('invalid-input', 'Expected a design tokens object');\n\tconst createId = options.createId ?? defaultTokenId;\n\tconst report: W3CTokensImportReport = { collectionsAdded: 0, modesAdded: 0, variablesAdded: 0, variablesUpdated: 0, warnings: [] };\n\tconst warn = (message: string) => {\n\t\tif (report.warnings.length < 500) report.warnings.push(message);\n\t};\n\n\t// Which top-level groups are collections.\n\tconst marked = Object.entries(doc).filter(([key, value]) => !key.startsWith('$') && isObject(value) && !('$value' in value) && Array.isArray(extensionOf(value)?.modes));\n\tconst plainName = options.collection ?? 'Tokens';\n\tconst sources: { name: string; group: Record<string, unknown>; modes?: unknown[]; id?: unknown; plain: boolean }[] = [];\n\tif (marked.length > 0) {\n\t\tfor (const [key, value] of marked) {\n\t\t\tconst ext = extensionOf(value as Record<string, unknown>)!;\n\t\t\tsources.push({ name: key, group: value as Record<string, unknown>, modes: ext.modes as unknown[], id: ext.id, plain: false });\n\t\t}\n\t\tconst rest: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(doc)) if (!marked.some(([k]) => k === key)) rest[key] = value;\n\t\tif (Object.keys(rest).some((k) => !k.startsWith('$'))) sources.push({ name: plainName, group: rest, plain: true });\n\t} else sources.push({ name: plainName, group: doc, plain: true });\n\n\tconst usedIds = new Set<string>([...state.collections.map((c) => c.id), ...state.variables.map((v) => v.id)]);\n\tfor (const c of state.collections) for (const m of c.modes) usedIds.add(m.id);\n\tconst idFrom = (candidate: unknown, kind: 'collection' | 'mode' | 'variable'): TokenIdFactory => (k) => {\n\t\tif (k === kind && typeof candidate === 'string' && candidate.length > 0 && candidate.length <= 200 && !usedIds.has(candidate)) {\n\t\t\tusedIds.add(candidate);\n\t\t\treturn candidate;\n\t\t}\n\t\tconst id = createId(k);\n\t\tusedIds.add(id);\n\t\treturn id;\n\t};\n\n\tlet next = state;\n\tconst tokens: RawToken[] = [];\n\tconst collectionIds = new Map<string, string>();\n\tconst plainMode = new Map<string, string>();\n\n\tconst ensureMode = (collectionId: string, name: string, id?: unknown): string | null => {\n\t\tconst collection = getTokenCollection(next, collectionId)!;\n\t\tconst existing = findTokenMode(collection, name);\n\t\tif (existing) return existing.id;\n\t\ttry {\n\t\t\tconst result = addTokenMode(next, collectionId, name, {}, idFrom(id, 'mode'));\n\t\t\tnext = result.state;\n\t\t\treport.modesAdded += 1;\n\t\t\treturn result.mode.id;\n\t\t} catch (error) {\n\t\t\twarn(`Mode \\`${name}\\`: ${(error as Error).message}`);\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tfor (const source of sources) {\n\t\tlet collection: TokenCollection | undefined = findTokenCollection(next, source.name);\n\t\tif (!collection) {\n\t\t\tconst declared = (source.modes ?? []).filter(isObject);\n\t\t\tconst names = declared.map((m) => m.name).filter((n): n is string => typeof n === 'string' && n.trim() !== '');\n\t\t\tif (source.plain && options.mode) names.splice(0, names.length, options.mode);\n\t\t\ttry {\n\t\t\t\tconst ids = [source.id, ...declared.map((m) => m.id)];\n\t\t\t\tlet i = 0;\n\t\t\t\tconst factory: TokenIdFactory = (kind) => idFrom(kind === 'collection' ? ids[0] : ids[++i], kind)(kind);\n\t\t\t\tconst result = createTokenCollection(next, { name: source.name, modes: names.length ? names : undefined }, factory);\n\t\t\t\tnext = result.state;\n\t\t\t\tcollection = result.collection;\n\t\t\t\treport.collectionsAdded += 1;\n\t\t\t} catch (error) {\n\t\t\t\twarn(`Collection \\`${source.name}\\`: ${(error as Error).message}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const m of (source.modes ?? []).filter(isObject)) {\n\t\t\t\tif (typeof m.name === 'string' && m.name.trim()) ensureMode(collection.id, m.name, m.id);\n\t\t\t}\n\t\t}\n\t\tcollectionIds.set(source.name, collection.id);\n\t\tconst modeId = options.mode && source.plain ? ensureMode(collection.id, options.mode) : getTokenCollection(next, collection.id)!.modes[0].id;\n\t\tif (modeId) plainMode.set(source.name, modeId);\n\t\tcollectTokens(source.group, source.name, [], undefined, tokens, report.warnings, 0);\n\t}\n\n\t// Paths for references: `Collection.a.b` and (within a collection) `a.b`.\n\tconst byFullPath = new Map<string, RawToken>();\n\tfor (const token of tokens) byFullPath.set([token.collection, ...token.path].join('.'), token);\n\tconst findRaw = (ref: string, from: RawToken): RawToken | undefined =>\n\t\tbyFullPath.get(ref) ?? byFullPath.get(`${from.collection}.${ref}`);\n\n\t// Types of untyped aliases follow their targets.\n\tconst typeOf = (token: RawToken): string | undefined => {\n\t\tlet current: RawToken | undefined = token;\n\t\tfor (let i = 0; i < MAX_DEPTH && current; i++) {\n\t\t\tif (current.type) return current.type;\n\t\t\tconst ref = aliasRef(current.value);\n\t\t\tif (ref === null) return inferType(current.value);\n\t\t\tcurrent = findRaw(ref, current);\n\t\t}\n\t\treturn undefined;\n\t};\n\n\tconst pending: { variable: TokenVariable; modeId: string; ref: string; token: RawToken }[] = [];\n\tconst variableFor = new Map<RawToken, string>();\n\tfor (const token of tokens) {\n\t\tconst label = [token.collection, ...token.path].join('.');\n\t\tconst collectionId = collectionIds.get(token.collection);\n\t\tif (!collectionId) continue;\n\t\tconst w3cType = typeOf(token);\n\t\tconst type = w3cType ? mapType(w3cType) : null;\n\t\tif (!w3cType || !type) {\n\t\t\twarn(`\\`${label}\\` has an unsupported type \\`${w3cType ?? 'unknown'}\\`; skipped`);\n\t\t\tcontinue;\n\t\t}\n\t\tlet name: string;\n\t\ttry {\n\t\t\tname = normalizeTokenName(token.path.join('/'));\n\t\t} catch (error) {\n\t\t\twarn(`\\`${label}\\`: ${(error as Error).message}`);\n\t\t\tcontinue;\n\t\t}\n\t\tlet variable = findTokenVariable(next, name, collectionId);\n\t\tif (variable && variable.type !== type) {\n\t\t\twarn(`\\`${name}\\` is a ${variable.type} variable; the ${type} token \\`${label}\\` was skipped`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!variable) {\n\t\t\ttry {\n\t\t\t\tconst result = createTokenVariable(next, { collectionId, name, type }, idFrom(token.ext?.id, 'variable'));\n\t\t\t\tnext = result.state;\n\t\t\t\tvariable = result.variable;\n\t\t\t\treport.variablesAdded += 1;\n\t\t\t} catch (error) {\n\t\t\t\twarn(`\\`${label}\\`: ${(error as Error).message}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else report.variablesUpdated += 1;\n\t\tvariableFor.set(token, variable.id);\n\n\t\t// Values: per mode from our extension, else `$value` into the plain mode.\n\t\tconst values: [string, unknown][] = [];\n\t\tconst extModes = token.ext?.modes;\n\t\tif (isObject(extModes)) {\n\t\t\tfor (const [modeName, value] of Object.entries(extModes)) {\n\t\t\t\tconst modeId = ensureMode(collectionId, modeName);\n\t\t\t\tif (modeId) values.push([modeId, value]);\n\t\t\t}\n\t\t} else {\n\t\t\tconst modeId = plainMode.get(token.collection);\n\t\t\tif (modeId) values.push([modeId, token.value]);\n\t\t}\n\t\tlet unit: string | undefined;\n\t\tfor (const [modeId, raw] of values) {\n\t\t\tconst ref = aliasRef(raw);\n\t\t\tif (ref !== null) {\n\t\t\t\tpending.push({ variable, modeId, ref, token });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst literal = readLiteral(w3cType, type, raw);\n\t\t\tif (!literal) {\n\t\t\t\twarn(`\\`${label}\\` has an invalid ${w3cType} value; kept the previous value`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (literal.unit) unit = literal.unit;\n\t\t\tnext = setTokenValue(next, variable.id, literal.value, modeId);\n\t\t}\n\t\tconst update: { description?: string; scopes?: string[]; unit?: string } = {};\n\t\tif (typeof token.description === 'string') update.description = token.description;\n\t\tconst extUnit = token.ext?.unit;\n\t\tif (typeof extUnit === 'string') unit = extUnit;\n\t\tif (unit && unit !== variable.unit) update.unit = unit;\n\t\tif (Array.isArray(token.ext?.scopes)) update.scopes = (token.ext!.scopes as unknown[]).filter((s): s is string => typeof s === 'string');\n\t\tif (Object.keys(update).length > 0) {\n\t\t\ttry {\n\t\t\t\tnext = updateTokenVariable(next, variable.id, update);\n\t\t\t} catch (error) {\n\t\t\t\twarn(`\\`${label}\\`: ${(error as Error).message}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Aliases, once every variable exists.\n\tfor (const { variable, modeId, ref, token } of pending) {\n\t\tconst label = [token.collection, ...token.path].join('.');\n\t\tconst raw = findRaw(ref, token);\n\t\tlet targetId = raw ? variableFor.get(raw) : undefined;\n\t\tif (!targetId) {\n\t\t\t// A variable already in the state: `Collection.a.b` or `a.b` in this collection.\n\t\t\tconst dot = ref.indexOf('.');\n\t\t\tconst inCollection = dot > 0 ? findTokenCollection(next, ref.slice(0, dot)) : undefined;\n\t\t\tconst found =\n\t\t\t\t(inCollection && findTokenVariable(next, ref.slice(dot + 1).split('.').join('/'), inCollection.id)) ||\n\t\t\t\tfindTokenVariable(next, ref.split('.').join('/'), variable.collectionId);\n\t\t\ttargetId = found ? found.id : undefined;\n\t\t}\n\t\tif (!targetId) {\n\t\t\twarn(`\\`${label}\\` refers to \\`{${ref}}\\`, which doesn't exist; kept the previous value`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = getTokenVariable(next, variable.id)!;\n\t\tconst error = checkTokenAlias(next, current, targetId);\n\t\tif (error) {\n\t\t\twarn(`\\`${label}\\`: ${error.message}`);\n\t\t\tcontinue;\n\t\t}\n\t\tnext = setTokenValue(next, variable.id, { alias: targetId }, modeId);\n\t}\n\n\treturn { state: next, report };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-HDYMLS3X.cjs","../src/extensions/table/extension.ts","../src/extensions/table/actions.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA,oCAAqD;AACrD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;AACH,MAAA;AAC1C,IAAA;AACM,EAAA;AAC0B,IAAA;AAClC,EAAA;AACF;AAE4D;AAcoB;AACxC,EAAA;AACH,EAAA;AACR,EAAA;AAEN,EAAA;AACc,IAAA;AACJ,IAAA;AACR,IAAA;AACV,IAAA;AACL,IAAA;AACoC,IAAA;AAC5C,EAAA;AACqB,EAAA;AACc,oBAAA;AACL,oBAAA;AACD,oBAAA;AACE,oBAAA;AAC/B,EAAA;AAEO,EAAA;AACc,IAAA;AACI,MAAA;AACc,QAAA;AACJ,QAAA;AACR,QAAA;AACR,UAAA;AACL,UAAA;AACR,QAAA;AACF,MAAA;AACO,MAAA;AACT,IAAA;AACoB,IAAA;AACa,MAAA;AACtB,QAAA;AACwB,QAAA;AAEL,QAAA;AACD,QAAA;AACE,QAAA;AAC7B,MAAA;AACsB,MAAA;AACT,MAAA;AACc,QAAA;AACG,QAAA;AAC9B,MAAA;AACF,IAAA;AACU,IAAA;AACD,MAAA;AACS,MAAA;AAClB,IAAA;AACF,EAAA;AACF;AF1BmD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-HDYMLS3X.cjs","sourcesContent":[null,"import { getHTMLFromFragment, type Extensions } from \"@tiptap/core\";\nimport { Fragment, type Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport * as _Table from \"@tiptap/extension-table\";\nimport * as _TableRow from \"@tiptap/extension-table-row\";\nimport * as _TableHeader from \"@tiptap/extension-table-header\";\nimport * as _TableCell from \"@tiptap/extension-table-cell\";\n\nconst resolveExt = (mod: any, name: string) =>\n mod?.[name] || mod?.default?.[name] || mod?.default?.default || mod?.default || mod;\n\nconst BaseTable = resolveExt(_Table, \"Table\");\nconst BaseTableRow = resolveExt(_TableRow, \"TableRow\");\nconst BaseTableHeader = resolveExt(_TableHeader, \"TableHeader\");\nconst BaseTableCell = resolveExt(_TableCell, \"TableCell\");\n\n/** Horizontal alignment of a table cell (`align` attribute). */\nexport type TableCellAlignment = \"left\" | \"center\" | \"right\" | \"justify\";\n\nconst ALIGNMENTS = new Set<TableCellAlignment>([\"left\", \"center\", \"right\", \"justify\"]);\n\n/** Returns a valid cell alignment, or `null`. */\nexport function normalizeTableCellAlignment(value: unknown): TableCellAlignment | null {\n const v = typeof value === \"string\" ? value.trim().toLowerCase() : \"\";\n return ALIGNMENTS.has(v as TableCellAlignment) ? (v as TableCellAlignment) : null;\n}\n\n/**\n * Color values allowed as a cell background: hex, `rgb()/rgba()/hsl()/hsla()`\n * with numeric arguments, or a CSS color keyword. Anything else (e.g.\n * `url(...)`, `expression(...)`, `;`) is rejected because the value ends up in\n * a `style` attribute.\n */\nconst COLOR_REGEX =\n /^(?:#[0-9a-f]{3,8}|(?:rgb|rgba|hsl|hsla)\\(\\s*[-0-9.%\\s,/deg]+\\)|[a-z]{3,20})$/i;\n\n/** Returns a safe CSS color for a cell background, or `null`. */\nexport function normalizeTableCellColor(value: unknown): string | null {\n const v = typeof value === \"string\" ? value.trim() : \"\";\n if (!v || v.length > 64 || !COLOR_REGEX.test(v)) return null;\n if (/^(?:inherit|initial|unset|revert|transparent)$/i.test(v)) return null;\n return v;\n}\n\n/** Cell attributes added on top of TipTap's `colspan` / `rowspan` / `colwidth`. */\nconst cellAttributes = () => ({\n align: {\n default: null,\n parseHTML: (element: HTMLElement) =>\n normalizeTableCellAlignment(element.style?.textAlign || element.getAttribute(\"align\")),\n renderHTML: (attrs: Record<string, any>) => {\n const align = normalizeTableCellAlignment(attrs.align);\n return align ? { style: `text-align: ${align}` } : {};\n },\n },\n backgroundColor: {\n default: null,\n parseHTML: (element: HTMLElement) =>\n normalizeTableCellColor(\n element.getAttribute(\"data-background-color\") ||\n element.style?.backgroundColor ||\n element.getAttribute(\"bgcolor\"),\n ),\n renderHTML: (attrs: Record<string, any>) => {\n const color = normalizeTableCellColor(attrs.backgroundColor);\n return color ? { style: `background-color: ${color}`, \"data-background-color\": color } : {};\n },\n },\n});\n\n// ---------------------------------------------------------------------------\n// Markdown (tiptap-markdown)\n// ---------------------------------------------------------------------------\n\nconst children = (node: ProsemirrorNode) => {\n const list: ProsemirrorNode[] = [];\n node.forEach((child) => list.push(child));\n return list;\n};\n\nconst hasSpan = (cell: ProsemirrorNode) => (cell.attrs.colspan ?? 1) > 1 || (cell.attrs.rowspan ?? 1) > 1;\n\n/**\n * Whether a table can be written as a GFM pipe table: the first row is all\n * header cells, the other rows have none, no cell spans rows or columns, and\n * every cell holds a single paragraph.\n */\nexport function isGfmTable(node: ProsemirrorNode): boolean {\n const rows = children(node);\n if (rows.length === 0) return false;\n const width = rows[0].childCount;\n return rows.every(\n (row, r) =>\n row.childCount === width &&\n children(row).every(\n (cell) =>\n (r === 0 ? cell.type.name === \"tableHeader\" : cell.type.name === \"tableCell\") &&\n !hasSpan(cell) &&\n cell.childCount === 1 &&\n cell.firstChild!.type.name === \"paragraph\",\n ),\n );\n}\n\nconst DELIMITERS: Record<string, string> = { left: \":---\", center: \":---:\", right: \"---:\" };\n\n/**\n * tiptap-markdown serializer for tables: GFM pipe tables (with column\n * alignment from the header cells and `|` escaped) when `isGfmTable`, HTML\n * otherwise (spans, header columns, multi-paragraph cells).\n */\nfunction serializeTableMarkdown(state: any, node: ProsemirrorNode) {\n if (!isGfmTable(node)) {\n const html = getHTMLFromFragment(Fragment.from(node), node.type.schema);\n // An HTML block must start on its own line and contain no blank lines.\n state.write(html.replace(/\\n{2,}/g, \"\\n\"));\n state.closeBlock(node);\n return;\n }\n const previous = state.inTable;\n state.inTable = true;\n children(node).forEach((row, r) => {\n if (r) state.ensureNewLine();\n state.write(\"| \");\n children(row).forEach((cell, c) => {\n if (c) state.write(\" | \");\n const paragraph = cell.firstChild!;\n // Render in place (mid-line, so no block prefix is added), then escape\n // the cell's pipes and line breaks, which would end the cell or row.\n const start = state.out.length;\n if (paragraph.childCount) state.renderInline(paragraph);\n const text: string = state.out.slice(start);\n state.out = state.out.slice(0, start) + text.replace(/\\n/g, \" \").replace(/\\|/g, \"\\\\|\");\n });\n state.write(\" |\");\n if (r === 0) {\n const delimiter = children(row).map((cell) => DELIMITERS[cell.attrs.align] ?? \"---\");\n state.ensureNewLine();\n state.write(`| ${delimiter.join(\" | \")} |`);\n }\n });\n state.inTable = previous;\n state.closeBlock(node);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions\n// ---------------------------------------------------------------------------\n\nexport interface RichTextTableOptions {\n /** Drag column borders to resize columns (stored as `colwidth`). Default `true`. */\n resizable: boolean;\n /** Width of the resize handle in pixels. Default 5. */\n handleWidth: number;\n /** Minimum cell width in pixels. Default 25. */\n cellMinWidth: number;\n /** Whether the last column can be resized. Default `true`. */\n lastColumnResizable: boolean;\n /** Allow selecting the whole table as a node (click its border, Esc from a cell selection). Default `true`. */\n allowTableNodeSelection: boolean;\n /** HTML attributes of the `<table>` element. */\n HTMLAttributes: Record<string, any>;\n /** HTML attributes of `<td>` elements. */\n cellHTMLAttributes: Record<string, any>;\n /** HTML attributes of `<th>` elements. */\n headerHTMLAttributes: Record<string, any>;\n /** HTML attributes of `<tr>` elements. */\n rowHTMLAttributes: Record<string, any>;\n}\n\nexport const DEFAULT_TABLE_OPTIONS: RichTextTableOptions = {\n resizable: true,\n handleWidth: 5,\n cellMinWidth: 25,\n lastColumnResizable: true,\n allowTableNodeSelection: true,\n HTMLAttributes: { class: \"pixerate-table\" },\n cellHTMLAttributes: {},\n headerHTMLAttributes: {},\n rowHTMLAttributes: {},\n};\n\n/** TipTap's `Table` with the GFM-aware markdown serializer. */\nexport const Table = BaseTable.extend({\n addStorage() {\n return { markdown: { serialize: serializeTableMarkdown } };\n },\n});\n\nexport const TableRow = BaseTableRow;\n\n/** TipTap's `TableCell` plus `align` and `backgroundColor` attributes. */\nexport const TableCell = BaseTableCell.extend({\n addAttributes() {\n return { ...this.parent?.(), ...cellAttributes() };\n },\n});\n\n/** TipTap's `TableHeader` plus `align` and `backgroundColor` attributes. */\nexport const TableHeader = BaseTableHeader.extend({\n addAttributes() {\n return { ...this.parent?.(), ...cellAttributes() };\n },\n});\n\n/**\n * The table extensions (`table`, `tableRow`, `tableHeader`, `tableCell`)\n * configured for rich documents: resizable columns, header rows, columns and\n * cells, `colspan` / `rowspan` from imported HTML, cell alignment and\n * background, table node selection and GFM markdown. `createRichTextPreset`\n * adds them unless `table: false`.\n */\nexport function createTableExtensions(options: Partial<RichTextTableOptions> = {}): Extensions {\n const o = { ...DEFAULT_TABLE_OPTIONS, ...options };\n return [\n Table.configure({\n resizable: o.resizable,\n handleWidth: o.handleWidth,\n cellMinWidth: o.cellMinWidth,\n lastColumnResizable: o.lastColumnResizable,\n allowTableNodeSelection: o.allowTableNodeSelection,\n HTMLAttributes: o.HTMLAttributes,\n }),\n TableRow.configure({ HTMLAttributes: o.rowHTMLAttributes }),\n TableHeader.configure({ HTMLAttributes: o.headerHTMLAttributes }),\n TableCell.configure({ HTMLAttributes: o.cellHTMLAttributes }),\n ];\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { EditorState } from \"@tiptap/pm/state\";\nimport { CellSelection, isInTable, selectedRect } from \"@tiptap/pm/tables\";\nimport { isTrackChangesEnabled } from \"../track-changes\";\nimport {\n normalizeTableCellAlignment,\n normalizeTableCellColor,\n type TableCellAlignment,\n} from \"./extension\";\n\n/** Table operations shared by the command registry, the toolbars and agent tools. */\nexport type TableAction =\n | \"insertTable\"\n | \"addRowBefore\"\n | \"addRowAfter\"\n | \"deleteRow\"\n | \"addColumnBefore\"\n | \"addColumnAfter\"\n | \"deleteColumn\"\n | \"deleteTable\"\n | \"mergeCells\"\n | \"splitCell\"\n | \"toggleHeaderRow\"\n | \"toggleHeaderColumn\"\n | \"toggleHeaderCell\"\n | \"goToNextCell\"\n | \"goToPreviousCell\"\n | \"setCellAlignment\"\n | \"setCellBackground\";\n\n/** Parameters of `insertTable`, `setCellAlignment` and `setCellBackground`. */\nexport interface TableActionParams {\n /** `insertTable`: number of rows (1–100, default 3). */\n rows?: number;\n /** `insertTable`: number of columns (1–50, default 3). */\n cols?: number;\n /** `insertTable`: make the first row a header row (default `true`). */\n withHeaderRow?: boolean;\n /** `setCellAlignment`: `left`, `center`, `right`, `justify`, or `null` to clear. */\n align?: TableCellAlignment | null;\n /** `setCellBackground`: a CSS color, or `null` to clear. */\n color?: string | null;\n}\n\nexport interface TableActionInfo {\n action: TableAction;\n label: string;\n description: string;\n keywords: readonly string[];\n}\n\n/** Every table action with its label, in toolbar order. */\nexport const TABLE_ACTIONS: readonly TableActionInfo[] = [\n { action: \"insertTable\", label: \"Insert Table\", description: \"Inserts a table (rows, cols, withHeaderRow) at the cursor.\", keywords: [\"table\", \"grid\", \"new\"] },\n { action: \"addRowBefore\", label: \"Insert Row Above\", description: \"Adds a row above the current row.\", keywords: [\"row\", \"add\", \"above\"] },\n { action: \"addRowAfter\", label: \"Insert Row Below\", description: \"Adds a row below the current row.\", keywords: [\"row\", \"add\", \"below\"] },\n { action: \"deleteRow\", label: \"Delete Row\", description: \"Deletes the selected rows.\", keywords: [\"row\", \"remove\"] },\n { action: \"addColumnBefore\", label: \"Insert Column Left\", description: \"Adds a column left of the current column.\", keywords: [\"column\", \"add\", \"left\", \"before\"] },\n { action: \"addColumnAfter\", label: \"Insert Column Right\", description: \"Adds a column right of the current column.\", keywords: [\"column\", \"add\", \"right\", \"after\"] },\n { action: \"deleteColumn\", label: \"Delete Column\", description: \"Deletes the selected columns.\", keywords: [\"column\", \"remove\"] },\n { action: \"deleteTable\", label: \"Delete Table\", description: \"Deletes the table around the cursor.\", keywords: [\"table\", \"remove\"] },\n { action: \"mergeCells\", label: \"Merge Cells\", description: \"Merges the selected cells into one.\", keywords: [\"combine\", \"join\", \"span\"] },\n { action: \"splitCell\", label: \"Split Cell\", description: \"Splits a merged cell back into single cells.\", keywords: [\"unmerge\", \"span\"] },\n { action: \"toggleHeaderRow\", label: \"Toggle Header Row\", description: \"Turns the first row into header cells, or back.\", keywords: [\"header\", \"row\", \"th\"] },\n { action: \"toggleHeaderColumn\", label: \"Toggle Header Column\", description: \"Turns the first column into header cells, or back.\", keywords: [\"header\", \"column\", \"th\"] },\n { action: \"toggleHeaderCell\", label: \"Toggle Header Cell\", description: \"Turns the selected cells into header cells, or back.\", keywords: [\"header\", \"cell\", \"th\"] },\n { action: \"goToNextCell\", label: \"Next Cell\", description: \"Moves the cursor to the next cell.\", keywords: [\"tab\", \"navigate\"] },\n { action: \"goToPreviousCell\", label: \"Previous Cell\", description: \"Moves the cursor to the previous cell.\", keywords: [\"shift tab\", \"navigate\"] },\n { action: \"setCellAlignment\", label: \"Align Cells…\", description: \"Sets the horizontal alignment (align: left | center | right | justify | null) of the selected cells.\", keywords: [\"align\", \"left\", \"center\", \"right\"] },\n { action: \"setCellBackground\", label: \"Cell Background…\", description: \"Sets the background color (color: CSS color or null) of the selected cells.\", keywords: [\"shading\", \"fill\", \"color\"] },\n];\n\n/** A button of the table toolbars (`TableToolbar` in React and Svelte). */\nexport interface TableToolbarItem {\n /** Unique id (also the button's `data-action`). */\n id: string;\n action: TableAction;\n params?: TableActionParams;\n /** Short button text. */\n label: string;\n /** Accessible name and tooltip. */\n title: string;\n /** Items of one group are separated from the next group. */\n group: string;\n /** Toggle buttons: whether the button shows as pressed. */\n active?: (state: TableState) => boolean;\n}\n\n/** The default table toolbar: rows, columns, cells, headers, alignment, delete. */\nexport const DEFAULT_TABLE_TOOLBAR: readonly TableToolbarItem[] = [\n { id: \"addRowBefore\", action: \"addRowBefore\", label: \"+ Row ↑\", title: \"Insert row above\", group: \"rows\" },\n { id: \"addRowAfter\", action: \"addRowAfter\", label: \"+ Row ↓\", title: \"Insert row below\", group: \"rows\" },\n { id: \"deleteRow\", action: \"deleteRow\", label: \"− Row\", title: \"Delete row\", group: \"rows\" },\n { id: \"addColumnBefore\", action: \"addColumnBefore\", label: \"+ Col ←\", title: \"Insert column left\", group: \"columns\" },\n { id: \"addColumnAfter\", action: \"addColumnAfter\", label: \"+ Col →\", title: \"Insert column right\", group: \"columns\" },\n { id: \"deleteColumn\", action: \"deleteColumn\", label: \"− Col\", title: \"Delete column\", group: \"columns\" },\n { id: \"mergeCells\", action: \"mergeCells\", label: \"Merge\", title: \"Merge cells\", group: \"cells\" },\n { id: \"splitCell\", action: \"splitCell\", label: \"Split\", title: \"Split cell\", group: \"cells\" },\n { id: \"toggleHeaderRow\", action: \"toggleHeaderRow\", label: \"Header row\", title: \"Toggle header row\", group: \"headers\", active: (s) => s.headerRow },\n { id: \"toggleHeaderColumn\", action: \"toggleHeaderColumn\", label: \"Header col\", title: \"Toggle header column\", group: \"headers\", active: (s) => s.headerColumn },\n { id: \"toggleHeaderCell\", action: \"toggleHeaderCell\", label: \"Header cell\", title: \"Toggle header cell\", group: \"headers\", active: (s) => s.headerCell },\n { id: \"alignLeft\", action: \"setCellAlignment\", params: { align: \"left\" }, label: \"Left\", title: \"Align cell left\", group: \"align\", active: (s) => s.cellAlignment === \"left\" },\n { id: \"alignCenter\", action: \"setCellAlignment\", params: { align: \"center\" }, label: \"Center\", title: \"Align cell center\", group: \"align\", active: (s) => s.cellAlignment === \"center\" },\n { id: \"alignRight\", action: \"setCellAlignment\", params: { align: \"right\" }, label: \"Right\", title: \"Align cell right\", group: \"align\", active: (s) => s.cellAlignment === \"right\" },\n { id: \"deleteTable\", action: \"deleteTable\", label: \"Delete table\", title: \"Delete table\", group: \"table\" },\n];\n\nexport const MAX_TABLE_ROWS = 100;\nexport const MAX_TABLE_COLUMNS = 50;\n\nconst live = (editor: Editor | null | undefined): editor is Editor => !!editor && !editor.isDestroyed;\n\n/** Whether the editor's schema has the table nodes (`createRichTextPreset({ table })`). */\nexport function isTableEnabled(editor: Editor | null | undefined): boolean {\n return live(editor) && !!editor.schema.nodes.table && !!editor.schema.nodes.tableRow;\n}\n\n/** Whether the selection (cursor, text or cell selection) is inside a table. */\nexport function isSelectionInTable(state: EditorState): boolean {\n if (!state.schema.nodes.table) return false;\n return state.selection instanceof CellSelection || isInTable(state);\n}\n\n/**\n * `shouldShow` for a table bubble menu (TipTap's `BubbleMenuPlugin`): shown\n * while an editable editor's selection is in a table, even a collapsed cursor.\n */\nexport function shouldShowTableBubbleMenu({ editor, state }: { editor: Editor; state: EditorState }): boolean {\n return editor.isEditable && isSelectionInTable(state);\n}\n\nconst isInt = (value: unknown, min: number, max: number) =>\n typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max;\n\nconst can = (editor: Editor, run: (chain: any) => any): boolean => {\n try {\n return !!run(editor.can().chain()).run();\n } catch {\n return false;\n }\n};\n\n/**\n * Whether a table action can run: `true`, or the reason it cannot (e.g.\n * \"Place the cursor in a table first.\").\n */\nexport function getTableActionState(\n editor: Editor | null | undefined,\n action: TableAction,\n params: TableActionParams = {},\n): true | string {\n if (!live(editor)) return \"The editor is not available.\";\n if (!isTableEnabled(editor)) return \"Tables are not enabled in this editor.\";\n if (!editor.isEditable) return \"The editor is read-only.\";\n const state = editor.state;\n const inTable = isSelectionInTable(state);\n\n if (action === \"insertTable\") {\n if (inTable) return \"Tables cannot be nested: move the cursor out of the table first.\";\n if (params.rows !== undefined && !isInt(params.rows, 1, MAX_TABLE_ROWS)) {\n return `Rows must be a whole number from 1 to ${MAX_TABLE_ROWS}.`;\n }\n if (params.cols !== undefined && !isInt(params.cols, 1, MAX_TABLE_COLUMNS)) {\n return `Columns must be a whole number from 1 to ${MAX_TABLE_COLUMNS}.`;\n }\n return can(editor, (c) => c.insertTable({ rows: 1, cols: 1 })) ? true : \"A table cannot be inserted here.\";\n }\n\n if (!inTable) return \"Place the cursor in a table first.\";\n\n switch (action) {\n case \"mergeCells\":\n case \"splitCell\": {\n if (isTrackChangesEnabled(editor)) {\n return `${action === \"mergeCells\" ? \"Merging\" : \"Splitting\"} cells cannot be tracked: turn off Track Changes first.`;\n }\n if (action === \"mergeCells\") {\n return can(editor, (c) => c.mergeCells()) ? true : \"Select two or more adjacent cells to merge.\";\n }\n return can(editor, (c) => c.splitCell()) ? true : \"Only a merged cell can be split.\";\n }\n case \"deleteRow\":\n case \"deleteColumn\": {\n // prosemirror-tables only refuses to delete every row/column when dispatching.\n const rect = selectedRect(state);\n const all = action === \"deleteRow\"\n ? rect.top === 0 && rect.bottom === rect.map.height\n : rect.left === 0 && rect.right === rect.map.width;\n const what = action === \"deleteRow\" ? \"rows\" : \"columns\";\n if (all || !can(editor, (c) => c[action]())) return `These are all the ${what}: delete the table instead.`;\n return true;\n }\n case \"goToNextCell\":\n return can(editor, (c) => c.goToNextCell()) ? true : \"This is the last cell.\";\n case \"goToPreviousCell\":\n return can(editor, (c) => c.goToPreviousCell()) ? true : \"This is the first cell.\";\n case \"setCellAlignment\":\n if (params.align !== undefined && params.align !== null && !normalizeTableCellAlignment(params.align)) {\n return 'Alignment must be \"left\", \"center\", \"right\", \"justify\" or null.';\n }\n if (!editor.schema.nodes.tableCell?.spec.attrs?.align) return \"Cell alignment is not supported by this schema.\";\n return true;\n case \"setCellBackground\":\n if (params.color !== undefined && params.color !== null && !normalizeTableCellColor(params.color)) {\n return \"Color must be a CSS color such as #fde68a, rgb(…) or a color name, or null.\";\n }\n if (!editor.schema.nodes.tableCell?.spec.attrs?.backgroundColor) return \"Cell backgrounds are not supported by this schema.\";\n return true;\n default:\n return can(editor, (c) => c[action]()) ? true : \"This table action is not available here.\";\n }\n}\n\nexport interface RunTableActionOptions {\n /** Focus the editor (toolbars). Default `false`. */\n focus?: boolean;\n}\n\n/**\n * Runs a table action. Returns `false` (and changes nothing) when it cannot\n * run; check `getTableActionState` for the reason.\n */\nexport function runTableAction(\n editor: Editor | null | undefined,\n action: TableAction,\n params: TableActionParams = {},\n options: RunTableActionOptions = {},\n): boolean {\n if (getTableActionState(editor, action, params) !== true) return false;\n const ed = editor as Editor;\n let chain: any = ed.chain();\n if (options.focus) chain = chain.focus();\n switch (action) {\n case \"insertTable\":\n chain = chain.insertTable({\n rows: params.rows ?? 3,\n cols: params.cols ?? 3,\n withHeaderRow: params.withHeaderRow ?? true,\n });\n break;\n case \"setCellAlignment\":\n chain = chain.setCellAttribute(\"align\", normalizeTableCellAlignment(params.align));\n break;\n case \"setCellBackground\":\n chain = chain.setCellAttribute(\"backgroundColor\", normalizeTableCellColor(params.color));\n break;\n default:\n chain = chain[action]();\n }\n return !!chain.run();\n}\n\nexport interface TableActionStatus {\n enabled: boolean;\n /** Why the action cannot run (only when `enabled` is false). */\n reason?: string;\n}\n\n/** The table at the selection and what can be done there. */\nexport interface TableState {\n /** The schema has tables. */\n enabled: boolean;\n /** The selection is inside a table. */\n inTable: boolean;\n /** Cells are selected (a `CellSelection`). */\n cellSelection: boolean;\n /** Size of the table (0 outside a table). */\n rows: number;\n columns: number;\n /** Row and column (0-based) of the selection's first cell, or -1. */\n row: number;\n column: number;\n /** The first row / first column are all header cells. */\n headerRow: boolean;\n headerColumn: boolean;\n /** The cell at the selection is a header cell. */\n headerCell: boolean;\n /** Alignment / background of the cell at the selection. */\n cellAlignment: TableCellAlignment | null;\n cellBackground: string | null;\n /** Enablement of every action (with the default params). */\n actions: Record<TableAction, TableActionStatus>;\n}\n\nconst NO_ACTIONS = Object.fromEntries(\n TABLE_ACTIONS.map(({ action }) => [action, { enabled: false, reason: \"The editor is not available.\" }]),\n) as Record<TableAction, TableActionStatus>;\n\nexport const EMPTY_TABLE_STATE: TableState = Object.freeze({\n enabled: false,\n inTable: false,\n cellSelection: false,\n rows: 0,\n columns: 0,\n row: -1,\n column: -1,\n headerRow: false,\n headerColumn: false,\n headerCell: false,\n cellAlignment: null,\n cellBackground: null,\n actions: NO_ACTIONS,\n}) as TableState;\n\n/** Computes the table state at the editor's selection. */\nexport function getTableState(editor: Editor | null | undefined): TableState {\n if (!live(editor)) return EMPTY_TABLE_STATE;\n const actions = Object.fromEntries(\n TABLE_ACTIONS.map(({ action }) => {\n const result = getTableActionState(editor, action);\n return [action, result === true ? { enabled: true } : { enabled: false, reason: result }];\n }),\n ) as Record<TableAction, TableActionStatus>;\n const state = editor.state;\n const base: TableState = { ...EMPTY_TABLE_STATE, enabled: isTableEnabled(editor), actions };\n if (!base.enabled || !isSelectionInTable(state)) return base;\n try {\n const rect = selectedRect(state);\n const { map, table } = rect;\n const cellAt = (row: number, col: number) => table.nodeAt(map.map[row * map.width + col]);\n const allHeaders = (positions: number[]) =>\n positions.length > 0 && positions.every((pos) => table.nodeAt(pos)?.type.name === \"tableHeader\");\n const firstRow = map.cellsInRect({ left: 0, right: map.width, top: 0, bottom: 1 });\n const firstColumn = map.cellsInRect({ left: 0, right: 1, top: 0, bottom: map.height });\n const cell = cellAt(rect.top, rect.left);\n return {\n ...base,\n inTable: true,\n cellSelection: state.selection instanceof CellSelection,\n rows: map.height,\n columns: map.width,\n row: rect.top,\n column: rect.left,\n headerRow: allHeaders(firstRow),\n headerColumn: allHeaders(firstColumn),\n headerCell: cell?.type.name === \"tableHeader\",\n cellAlignment: normalizeTableCellAlignment(cell?.attrs.align),\n cellBackground: normalizeTableCellColor(cell?.attrs.backgroundColor),\n };\n } catch {\n return { ...base, inTable: true };\n }\n}\n\nconst stateKey = (state: TableState) => JSON.stringify(state);\n\nexport interface TableStore {\n getSnapshot(): TableState;\n subscribe(listener: () => void): () => void;\n destroy(): void;\n}\n\n/**\n * An external store of `getTableState(editor)` for UI bindings (React's\n * `useSyncExternalStore`, Svelte runes). The snapshot object only changes\n * when the state does, and the store listens to the editor only while it\n * has subscribers.\n */\nexport function createTableStore(editor: Editor | null | undefined): TableStore {\n const listeners = new Set<() => void>();\n let snapshot = getTableState(editor);\n let key = stateKey(snapshot);\n\n const update = () => {\n const next = getTableState(editor);\n const nextKey = stateKey(next);\n if (nextKey === key) return;\n snapshot = next;\n key = nextKey;\n listeners.forEach((listener) => listener());\n };\n const detach = () => {\n editor?.off(\"transaction\", update);\n editor?.off(\"update\", update);\n editor?.off(\"focus\", update);\n editor?.off(\"destroy\", update);\n };\n\n return {\n getSnapshot: () => {\n if (!listeners.size) {\n const next = getTableState(editor);\n const nextKey = stateKey(next);\n if (nextKey !== key) {\n snapshot = next;\n key = nextKey;\n }\n }\n return snapshot;\n },\n subscribe(listener) {\n if (!listeners.size && editor) {\n update();\n editor.on(\"transaction\", update);\n // `setEditable` emits `update` without a transaction.\n editor.on(\"update\", update);\n editor.on(\"focus\", update);\n editor.on(\"destroy\", update);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (!listeners.size) detach();\n };\n },\n destroy() {\n detach();\n listeners.clear();\n },\n };\n}\n"]}
|