@pixerate/editor 0.26.0 → 0.27.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.
Files changed (79) hide show
  1. package/README.md +8 -2
  2. package/dist/agent/index.cjs +59 -9
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +6 -4
  5. package/dist/agent/index.d.ts +6 -4
  6. package/dist/agent/index.js +52 -2
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/{builtins-Chj6zv_O.d.ts → builtins-haN82vjT.d.ts} +33 -3
  9. package/dist/{builtins-CdPcLwwF.d.cts → builtins-nMXh9sT3.d.cts} +33 -3
  10. package/dist/canvas/index.cjs +372 -8
  11. package/dist/canvas/index.cjs.map +1 -1
  12. package/dist/canvas/index.d.cts +72 -4
  13. package/dist/canvas/index.d.ts +72 -4
  14. package/dist/canvas/index.js +368 -4
  15. package/dist/canvas/index.js.map +1 -1
  16. package/dist/{chunk-UBCFIABU.js → chunk-5H2OPMXZ.js} +183 -6
  17. package/dist/chunk-5H2OPMXZ.js.map +1 -0
  18. package/dist/{chunk-NFVBT3UZ.cjs → chunk-66IMF6OD.cjs} +108 -25
  19. package/dist/chunk-66IMF6OD.cjs.map +1 -0
  20. package/dist/{chunk-Q2OHWD2A.js → chunk-6IO7WUSU.js} +19 -5
  21. package/dist/chunk-6IO7WUSU.js.map +1 -0
  22. package/dist/{chunk-YOMYSFJU.cjs → chunk-AGR7EVRW.cjs} +49 -35
  23. package/dist/chunk-AGR7EVRW.cjs.map +1 -0
  24. package/dist/{chunk-RRREAOVM.cjs → chunk-HNDSPZ5T.cjs} +4 -4
  25. package/dist/{chunk-RRREAOVM.cjs.map → chunk-HNDSPZ5T.cjs.map} +1 -1
  26. package/dist/chunk-HXDMZQTD.cjs +497 -0
  27. package/dist/chunk-HXDMZQTD.cjs.map +1 -0
  28. package/dist/chunk-IB3ZHQAX.js +497 -0
  29. package/dist/chunk-IB3ZHQAX.js.map +1 -0
  30. package/dist/{chunk-X7HXL2SB.js → chunk-JT7AXQTE.js} +336 -10
  31. package/dist/chunk-JT7AXQTE.js.map +1 -0
  32. package/dist/{chunk-HDYMLS3X.cjs → chunk-MC2LQN5S.cjs} +196 -19
  33. package/dist/chunk-MC2LQN5S.cjs.map +1 -0
  34. package/dist/{chunk-JOIREKL7.js → chunk-UKI64KUD.js} +85 -2
  35. package/dist/chunk-UKI64KUD.js.map +1 -0
  36. package/dist/{chunk-MHEPLBFB.js → chunk-WON34HKM.js} +2 -2
  37. package/dist/{chunk-NQF32I6Z.cjs → chunk-YK5TATOF.cjs} +461 -135
  38. package/dist/chunk-YK5TATOF.cjs.map +1 -0
  39. package/dist/commands/index.cjs +30 -410
  40. package/dist/commands/index.cjs.map +1 -1
  41. package/dist/commands/index.d.cts +1 -1
  42. package/dist/commands/index.d.ts +1 -1
  43. package/dist/commands/index.js +17 -397
  44. package/dist/commands/index.js.map +1 -1
  45. package/dist/{controller-CxXGOEmy.d.cts → controller-w6eRTjF8.d.cts} +67 -2
  46. package/dist/{controller-CxXGOEmy.d.ts → controller-w6eRTjF8.d.ts} +67 -2
  47. package/dist/extensions/index.cjs +23 -5
  48. package/dist/extensions/index.cjs.map +1 -1
  49. package/dist/extensions/index.d.cts +1 -1
  50. package/dist/extensions/index.d.ts +1 -1
  51. package/dist/extensions/index.js +23 -5
  52. package/dist/{index-jcJwmBYt.d.cts → index-C6gaQRH0.d.cts} +53 -4
  53. package/dist/{index-B273Zllk.d.ts → index-DXAv_R08.d.ts} +53 -4
  54. package/dist/index.cjs +66 -26
  55. package/dist/index.cjs.map +1 -1
  56. package/dist/index.d.cts +8 -6
  57. package/dist/index.d.ts +8 -6
  58. package/dist/index.js +46 -6
  59. package/dist/index.js.map +1 -1
  60. package/dist/serializers/index.cjs +5 -3
  61. package/dist/serializers/index.cjs.map +1 -1
  62. package/dist/serializers/index.d.cts +13 -3
  63. package/dist/serializers/index.d.ts +13 -3
  64. package/dist/serializers/index.js +4 -2
  65. package/dist/spreadsheet/index.cjs +22 -2
  66. package/dist/spreadsheet/index.cjs.map +1 -1
  67. package/dist/spreadsheet/index.d.cts +76 -3
  68. package/dist/spreadsheet/index.d.ts +76 -3
  69. package/dist/spreadsheet/index.js +21 -1
  70. package/package.json +1 -1
  71. package/dist/chunk-HDYMLS3X.cjs.map +0 -1
  72. package/dist/chunk-JOIREKL7.js.map +0 -1
  73. package/dist/chunk-NFVBT3UZ.cjs.map +0 -1
  74. package/dist/chunk-NQF32I6Z.cjs.map +0 -1
  75. package/dist/chunk-Q2OHWD2A.js.map +0 -1
  76. package/dist/chunk-UBCFIABU.js.map +0 -1
  77. package/dist/chunk-X7HXL2SB.js.map +0 -1
  78. package/dist/chunk-YOMYSFJU.cjs.map +0 -1
  79. /package/dist/{chunk-MHEPLBFB.js.map → chunk-WON34HKM.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/builtins.ts"],"sourcesContent":["import type { HistoryState } from '../history/types.js';\nimport type { CanvasArrangeAction } from '../canvas/arrangeShortcuts.js';\nimport type { AlignEdge, DistributeAxis, DistributeMode, ZOrderOperation } from '../canvas/arrange.js';\nimport { DEFAULT_ARRANGE_SHORTCUTS } from '../canvas/arrangeShortcuts.js';\nimport type { CommandParamsSchema, CommandSpec } from './registry.js';\nimport { ShortcutMap, type ShortcutBinding } from './shortcuts.js';\nimport type { KeyboardEventLike, Platform } from './chords.js';\n\n// ---------------------------------------------------------------------------\n// History\n// ---------------------------------------------------------------------------\n\n/** Minimal history surface (`HistoryManager` satisfies it). */\nexport interface HistoryCommandTarget {\n\tundo(): boolean | void;\n\tredo(): boolean | void;\n\tgetState(): Pick<HistoryState, 'canUndo' | 'canRedo'> & Partial<Pick<HistoryState, 'undoName' | 'redoName'>>;\n}\n\n/** Default history bindings: `Mod+Z` undo; `Mod+Shift+Z` redo, plus `Mod+Y` off macOS. */\nexport const DEFAULT_HISTORY_SHORTCUTS: readonly ShortcutBinding[] = [\n\t{ command: 'undo', chord: 'Mod+Z' },\n\t{ command: 'redo', chord: 'Mod+Shift+Z' },\n\t{ command: 'redo', chord: 'Mod+Y', platforms: ['windows', 'linux'] }\n];\n\nexport interface HistoryCommandOptions {\n\t/** Id prefix (default `history.`). */\n\tprefix?: string;\n\tgroup?: string;\n\tscope?: string;\n}\n\n/** `history.undo` / `history.redo` commands for a `HistoryManager` (disabled with a reason when empty). */\nexport function createHistoryCommands(history: HistoryCommandTarget, options: HistoryCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'history.';\n\tconst group = options.group ?? 'Edit';\n\tconst shortcutsOf = (command: 'undo' | 'redo') =>\n\t\tDEFAULT_HISTORY_SHORTCUTS.filter((b) => b.command === command).map(({ command: _c, ...rest }) => rest);\n\treturn [\n\t\t{\n\t\t\tid: `${prefix}undo`,\n\t\t\tlabel: 'Undo',\n\t\t\tgroup,\n\t\t\tkeywords: ['revert', 'back'],\n\t\t\tdescription: 'Reverts the last change.',\n\t\t\tshortcut: shortcutsOf('undo'),\n\t\t\t...(options.scope ? { scope: options.scope } : {}),\n\t\t\tenabled: () => (history.getState().canUndo ? true : 'Nothing to undo.'),\n\t\t\trun: () => {\n\t\t\t\thistory.undo();\n\t\t\t\treturn { undone: true, state: history.getState() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tid: `${prefix}redo`,\n\t\t\tlabel: 'Redo',\n\t\t\tgroup,\n\t\t\tkeywords: ['repeat', 'forward'],\n\t\t\tdescription: 'Re-applies the last undone change.',\n\t\t\tshortcut: shortcutsOf('redo'),\n\t\t\t...(options.scope ? { scope: options.scope } : {}),\n\t\t\tenabled: () => (history.getState().canRedo ? true : 'Nothing to redo.'),\n\t\t\trun: () => {\n\t\t\t\thistory.redo();\n\t\t\t\treturn { redone: true, state: history.getState() };\n\t\t\t}\n\t\t}\n\t];\n}\n\nlet historyShortcutMap: ShortcutMap | null = null;\n\n/**\n * Resolves a keydown event to `undo` / `redo` with the default history bindings\n * (`Mod` is ⌘ on macOS and Ctrl elsewhere). Events from text inputs and\n * contenteditable elements are ignored unless `allowInEditable`.\n */\nexport function matchHistoryShortcut(\n\tevent: KeyboardEventLike,\n\toptions: { platform?: Platform; allowInEditable?: boolean } = {}\n): 'undo' | 'redo' | null {\n\thistoryShortcutMap ??= new ShortcutMap(DEFAULT_HISTORY_SHORTCUTS);\n\treturn (historyShortcutMap.resolve(event, options)?.command as 'undo' | 'redo' | undefined) ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Canvas arrange\n// ---------------------------------------------------------------------------\n\n/** Minimal arrange controller surface (`createCanvasArrangeController` satisfies it). */\nexport interface ArrangeCommandTarget {\n\talign(edge: AlignEdge, ids?: Iterable<string>): unknown;\n\tdistribute(axis: DistributeAxis, mode?: DistributeMode, ids?: Iterable<string>): unknown;\n\treorder(operation: ZOrderOperation, ids?: Iterable<string>): unknown;\n\tlock(ids?: Iterable<string>): unknown;\n\tunlock(ids?: Iterable<string>): unknown;\n}\n\nexport interface ArrangeCommandOptions {\n\t/** Id prefix (default `canvas.`). */\n\tprefix?: string;\n\tgroup?: string;\n\t/** Scope of the commands and their shortcuts (default `canvas`). Pass `null` for global. */\n\tscope?: string | null;\n\t/** Current selection, used for enablement (\"Select at least two nodes\"). */\n\tgetSelectedIds?: () => string[];\n\t/** Scene navigation (`nextScene` / `previousScene`); those commands are only added when given. */\n\tscenes?: { next(): unknown; previous(): unknown };\n\t/** Use these bindings instead of `DEFAULT_ARRANGE_SHORTCUTS`. */\n\tbindings?: readonly { action: CanvasArrangeAction; label: string }[];\n}\n\nconst ARRANGE_LABELS: Record<CanvasArrangeAction, string> = {\n\talignLeft: 'Align Left',\n\talignCenter: 'Align Horizontal Centers',\n\talignRight: 'Align Right',\n\talignTop: 'Align Top',\n\talignMiddle: 'Align Vertical Centers',\n\talignBottom: 'Align Bottom',\n\tdistributeHorizontal: 'Distribute Horizontally',\n\tdistributeVertical: 'Distribute Vertically',\n\tlock: 'Lock',\n\tunlock: 'Unlock',\n\tbringForward: 'Bring Forward',\n\tsendBackward: 'Send Backward',\n\tbringToFront: 'Bring to Front',\n\tsendToBack: 'Send to Back',\n\tnextScene: 'Next Scene',\n\tpreviousScene: 'Previous Scene'\n};\n\nconst IDS_PARAMS: CommandParamsSchema = {\n\ttype: 'object',\n\tproperties: {\n\t\tids: {\n\t\t\ttype: 'array',\n\t\t\titems: { type: 'string' },\n\t\t\tdescription: 'Node ids to act on (default: the selection).'\n\t\t}\n\t}\n};\n\n/**\n * Commands for the canvas arrange actions (`canvas.alignLeft`, `canvas.bringToFront`, …)\n * with the default arrange shortcuts. Each accepts `{ ids? }`; enablement checks the\n * named ids, or the selection when none are named.\n */\nexport function createArrangeCommands(controller: ArrangeCommandTarget, options: ArrangeCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'canvas.';\n\tconst group = options.group ?? 'Arrange';\n\tconst scope = options.scope === null ? undefined : options.scope ?? 'canvas';\n\tconst bindings = options.bindings ?? DEFAULT_ARRANGE_SHORTCUTS;\n\tconst count = (params?: { ids?: string[] }) => params?.ids?.length ?? options.getSelectedIds?.().length;\n\tconst needs = (min: number, what: string) => (_: unknown, params?: { ids?: string[] }) => {\n\t\tconst n = count(params);\n\t\tif (n === undefined || n >= min) return true;\n\t\treturn min === 1 ? `Select a ${what} first.` : `Select at least ${min} ${what}s.`;\n\t};\n\n\tconst run: Record<CanvasArrangeAction, (ids?: string[]) => unknown> = {\n\t\talignLeft: (ids) => controller.align('left', ids),\n\t\talignCenter: (ids) => controller.align('center', ids),\n\t\talignRight: (ids) => controller.align('right', ids),\n\t\talignTop: (ids) => controller.align('top', ids),\n\t\talignMiddle: (ids) => controller.align('middle', ids),\n\t\talignBottom: (ids) => controller.align('bottom', ids),\n\t\tdistributeHorizontal: (ids) => controller.distribute('horizontal', 'gaps', ids),\n\t\tdistributeVertical: (ids) => controller.distribute('vertical', 'gaps', ids),\n\t\tlock: (ids) => controller.lock(ids),\n\t\tunlock: (ids) => controller.unlock(ids),\n\t\tbringForward: (ids) => controller.reorder('bringForward', ids),\n\t\tsendBackward: (ids) => controller.reorder('sendBackward', ids),\n\t\tbringToFront: (ids) => controller.reorder('bringToFront', ids),\n\t\tsendToBack: (ids) => controller.reorder('sendToBack', ids),\n\t\tnextScene: () => options.scenes?.next(),\n\t\tpreviousScene: () => options.scenes?.previous()\n\t};\n\n\tconst actions = Object.keys(ARRANGE_LABELS) as CanvasArrangeAction[];\n\treturn actions\n\t\t.filter((action) => options.scenes || (action !== 'nextScene' && action !== 'previousScene'))\n\t\t.map((action): CommandSpec => {\n\t\t\tconst isScene = action === 'nextScene' || action === 'previousScene';\n\t\t\tconst enabled = isScene\n\t\t\t\t? undefined\n\t\t\t\t: action.startsWith('align')\n\t\t\t\t\t? needs(2, 'node')\n\t\t\t\t\t: action.startsWith('distribute')\n\t\t\t\t\t\t? needs(3, 'node')\n\t\t\t\t\t\t: needs(1, 'node');\n\t\t\treturn {\n\t\t\t\tid: `${prefix}${action}`,\n\t\t\t\tlabel: ARRANGE_LABELS[action],\n\t\t\t\tgroup: isScene ? 'Scenes' : group,\n\t\t\t\tkeywords: isScene ? ['scene', 'slide', 'page'] : action.startsWith('align') ? ['align'] : ['arrange', 'layer', 'order'],\n\t\t\t\t...(scope ? { scope } : {}),\n\t\t\t\tshortcut: bindings.filter((b) => b.action === action).map((b) => b.label),\n\t\t\t\t...(isScene ? {} : { params: IDS_PARAMS }),\n\t\t\t\t...(enabled ? { enabled } : {}),\n\t\t\t\trun: (_ctx: unknown, params: { ids?: string[] }) => run[action](params?.ids)\n\t\t\t};\n\t\t});\n}\n\n// ---------------------------------------------------------------------------\n// Canvas shape operations\n// ---------------------------------------------------------------------------\n\n/** Shape operations surface of the arrange controller (`createCanvasArrangeController` satisfies it). */\nexport interface ShapeCommandTarget {\n\tcombineShapes(operation: 'unite' | 'intersect' | 'subtract' | 'exclude' | 'divide', ids?: Iterable<string>): unknown;\n\tcanCombineShapes(ids?: Iterable<string>): boolean;\n\toffsetShapes(distance: number, ids?: Iterable<string>, options?: { join?: 'miter' | 'round' | 'bevel'; miterLimit?: number }): unknown;\n\tcanOffsetShapes(ids?: Iterable<string>): boolean;\n\toutlineStroke(\n\t\tids?: Iterable<string>,\n\t\toptions?: { join?: 'miter' | 'round' | 'bevel'; cap?: 'butt' | 'round' | 'square'; miterLimit?: number }\n\t): unknown;\n\tcanOutlineStroke(ids?: Iterable<string>): boolean;\n}\n\nexport interface ShapeCommandOptions {\n\t/** Id prefix (default `canvas.`). */\n\tprefix?: string;\n\tgroup?: string;\n\t/** Scope (default `canvas`). Pass `null` for global. */\n\tscope?: string | null;\n\t/** Offset distance used when `canvas.offsetPath` is run without one (default 10). */\n\tdefaultOffset?: number;\n}\n\nconst SHAPE_COMMANDS = [\n\t{ op: 'unite', label: 'Unite Shapes', keywords: ['union', 'merge', 'boolean', 'combine'] },\n\t{ op: 'intersect', label: 'Intersect Shapes', keywords: ['intersection', 'boolean', 'combine'] },\n\t{ op: 'subtract', label: 'Subtract Shapes', keywords: ['difference', 'minus front', 'boolean', 'combine'] },\n\t{ op: 'exclude', label: 'Exclude Shapes', keywords: ['xor', 'boolean', 'combine'] },\n\t{ op: 'divide', label: 'Divide Shapes', keywords: ['split', 'pathfinder', 'boolean'] }\n] as const;\n\nconst JOIN_PARAM = { type: 'string', enum: ['miter', 'round', 'bevel'], description: 'Corner style (default miter).' } as const;\n\n/**\n * Palette / context-menu / agent commands for the shape operations: `canvas.unite`,\n * `canvas.intersect`, `canvas.subtract`, `canvas.exclude`, `canvas.divide`,\n * `canvas.offsetPath` (`{ distance, join?, miterLimit?, ids? }`) and `canvas.outlineStroke`\n * (`{ join?, cap?, miterLimit?, ids? }`). Each is one undoable step when the controller has a\n * history; enablement explains why a command cannot run.\n */\nexport function createShapeCommands(controller: ShapeCommandTarget, options: ShapeCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'canvas.';\n\tconst group = options.group ?? 'Shape';\n\tconst scope = options.scope === null ? undefined : options.scope ?? 'canvas';\n\tconst base = { group, ...(scope ? { scope } : {}) };\n\tconst combine = SHAPE_COMMANDS.map(\n\t\t({ op, label, keywords }): CommandSpec => ({\n\t\t\t...base,\n\t\t\tid: `${prefix}${op}`,\n\t\t\tlabel,\n\t\t\tkeywords: [...keywords],\n\t\t\tdescription: `${label.split(' ')[0]}s the selected shapes into a new path (curves are kept).`,\n\t\t\tparams: IDS_PARAMS,\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) =>\n\t\t\t\tcontroller.canCombineShapes(params?.ids) ? true : 'Select at least two unlocked shapes.',\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] }) => controller.combineShapes(op, params?.ids)\n\t\t})\n\t);\n\treturn [\n\t\t...combine,\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}offsetPath`,\n\t\t\tlabel: 'Offset Path…',\n\t\t\tkeywords: ['inset', 'outset', 'grow', 'shrink', 'expand', 'contract'],\n\t\t\tdescription: 'Grows (positive distance) or shrinks (negative) the selected shapes.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tdistance: { type: 'number', description: `Offset in canvas units (default ${options.defaultOffset ?? 10}).` },\n\t\t\t\t\tjoin: JOIN_PARAM,\n\t\t\t\t\tmiterLimit: { type: 'number', description: 'Miter limit (default 4).' },\n\t\t\t\t\tids: IDS_PARAMS.properties!.ids\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) =>\n\t\t\t\tcontroller.canOffsetShapes(params?.ids) ? true : 'Select an unlocked shape.',\n\t\t\trun: (_ctx: unknown, params: { distance?: number; join?: 'miter' | 'round' | 'bevel'; miterLimit?: number; ids?: string[] }) =>\n\t\t\t\tcontroller.offsetShapes(params?.distance ?? options.defaultOffset ?? 10, params?.ids, {\n\t\t\t\t\t...(params?.join ? { join: params.join } : {}),\n\t\t\t\t\t...(params?.miterLimit !== undefined ? { miterLimit: params.miterLimit } : {})\n\t\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}outlineStroke`,\n\t\t\tlabel: 'Outline Stroke',\n\t\t\tkeywords: ['expand stroke', 'stroke to path', 'convert stroke'],\n\t\t\tdescription: 'Converts the strokes of the selected shapes to filled shapes.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tjoin: JOIN_PARAM,\n\t\t\t\t\tcap: { type: 'string', enum: ['butt', 'round', 'square'], description: 'Line cap (default butt).' },\n\t\t\t\t\tmiterLimit: { type: 'number', description: 'Miter limit (default 4).' },\n\t\t\t\t\tids: IDS_PARAMS.properties!.ids\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) =>\n\t\t\t\tcontroller.canOutlineStroke(params?.ids) ? true : 'Select an unlocked shape with a stroke.',\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: { join?: 'miter' | 'round' | 'bevel'; cap?: 'butt' | 'round' | 'square'; miterLimit?: number; ids?: string[] }\n\t\t\t) =>\n\t\t\t\tcontroller.outlineStroke(params?.ids, {\n\t\t\t\t\t...(params?.join ? { join: params.join } : {}),\n\t\t\t\t\t...(params?.cap ? { cap: params.cap } : {}),\n\t\t\t\t\t...(params?.miterLimit !== undefined ? { miterLimit: params.miterLimit } : {})\n\t\t\t\t})\n\t\t}\n\t];\n}\n\n// ---------------------------------------------------------------------------\n// Canvas components and instances\n// ---------------------------------------------------------------------------\n\ntype ComponentActionResult = { ok: true; ids: string[] } | { ok: false; reason: string };\n\n/** Components surface of the components controller (`createCanvasComponentsController` satisfies it). */\nexport interface ComponentCommandTarget {\n\tcreateComponent(ids?: Iterable<string>): ComponentActionResult;\n\tcanCreateComponent(ids?: Iterable<string>): true | string;\n\tcombineAsVariants(ids?: Iterable<string>): ComponentActionResult;\n\tcanCombineAsVariants(ids?: Iterable<string>): true | string;\n\tcreateInstance(componentId: string, options?: { parentId?: string; position?: { x: number; y: number }; properties?: Record<string, boolean | string> }): ComponentActionResult;\n\tcanCreateInstance(componentId?: string, parentId?: string): true | string;\n\tdetachInstance(ids?: Iterable<string>): ComponentActionResult;\n\tcanDetachInstance(ids?: Iterable<string>): true | string;\n\tresetOverrides(id?: string, group?: string): ComponentActionResult;\n\tcanResetOverrides(id?: string): true | string;\n\tpushOverrides(id?: string): ComponentActionResult;\n\tcanPushOverrides(id?: string): true | string;\n\tswapInstance(componentId: string, ids?: Iterable<string>): ComponentActionResult;\n\tcanSwapInstance(componentId?: string, ids?: Iterable<string>): true | string;\n\tsetInstanceProperties(properties: Record<string, unknown>, ids?: Iterable<string>): ComponentActionResult;\n\tcanSetInstanceProperties(ids?: Iterable<string>): true | string;\n\trestoreMainComponent(id?: string): ComponentActionResult;\n\tcanRestoreMainComponent(id?: string): true | string;\n\tgoToMainComponent(id?: string): string | undefined;\n\tcanGoToMainComponent(id?: string): true | string;\n\tlist(): unknown;\n\tinspect(id?: string): unknown;\n\t// Variant editing (optional so older targets keep type-checking; the controller has them all).\n\taddVariant?(\n\t\tsetId?: string,\n\t\toptions?: { from?: string; variant?: Record<string, string>; position?: { x: number; y: number }; defaultValue?: string }\n\t): ComponentActionResult;\n\tcanAddVariant?(setId?: string, options?: { from?: string; variant?: Record<string, string> }): true | string;\n\tremoveVariant?(variantId?: string): ComponentActionResult;\n\tcanRemoveVariant?(variantId?: string): true | string;\n\tsetVariantProperties?(values: Record<string, string>, variantId?: string, options?: { defaultValue?: string }): ComponentActionResult;\n\tcanSetVariantProperties?(values?: Record<string, string>, variantId?: string): true | string;\n\trenameVariantProperty?(name: string, newName: string, setId?: string): ComponentActionResult;\n\tcanRenameVariantProperty?(name?: string, newName?: string, setId?: string): true | string;\n\trenameVariantValue?(property: string, value: string, newValue: string, setId?: string): ComponentActionResult;\n\tcanRenameVariantValue?(property?: string, value?: string, newValue?: string, setId?: string): true | string;\n}\n\n/** The variant-editing part of a `ComponentCommandTarget` (present on the components controller). */\ntype VariantCommandTarget = Required<\n\tPick<\n\t\tComponentCommandTarget,\n\t\t| 'addVariant'\n\t\t| 'canAddVariant'\n\t\t| 'removeVariant'\n\t\t| 'canRemoveVariant'\n\t\t| 'setVariantProperties'\n\t\t| 'canSetVariantProperties'\n\t\t| 'renameVariantProperty'\n\t\t| 'canRenameVariantProperty'\n\t\t| 'renameVariantValue'\n\t\t| 'canRenameVariantValue'\n\t>\n>;\n\n/** Whether a command target can edit variants. */\nexport function hasVariantCommands(controller: ComponentCommandTarget): controller is ComponentCommandTarget & VariantCommandTarget {\n\treturn typeof controller.addVariant === 'function' && typeof controller.removeVariant === 'function';\n}\n\nconst SET_ID_PARAM = { type: 'string', description: 'Component set (or one of its variants) to act on (default: the selection’s set).' } as const;\nconst VARIANT_ID_PARAM = { type: 'string', description: 'Variant to act on (default: the first selected variant).' } as const;\nconst VARIANT_VALUES_PARAM = {\n\ttype: 'object',\n\tdescription: 'Variant property → value, e.g. { \"Size\": \"Medium\" }. New property names are added to every variant.',\n\tadditionalProperties: { type: 'string' }\n} as const;\n\nfunction variantCommands(controller: ComponentCommandTarget & VariantCommandTarget, prefix: string, base: Partial<CommandSpec>): CommandSpec[] {\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addVariant`,\n\t\t\tlabel: 'Add Variant',\n\t\t\tkeywords: ['variant', 'new variant', 'duplicate variant', 'component set'],\n\t\t\tdescription: 'Adds a variant to a component set by duplicating one (default: the selected or default variant) with new property values.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tsetId: SET_ID_PARAM,\n\t\t\t\t\tfrom: { type: 'string', description: 'Variant to duplicate (default: the selected variant, else the default one).' },\n\t\t\t\t\tvariant: VARIANT_VALUES_PARAM,\n\t\t\t\t\tx: { type: 'number', description: 'X in the set’s space (default: next to the source).' },\n\t\t\t\t\ty: { type: 'number', description: 'Y in the set’s space.' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { setId?: string; from?: string; variant?: Record<string, string> }) =>\n\t\t\t\tcontroller.canAddVariant(params?.setId, {\n\t\t\t\t\t...(params?.from !== undefined ? { from: params.from } : {}),\n\t\t\t\t\t...(params?.variant ? { variant: params.variant } : {})\n\t\t\t\t}),\n\t\t\trun: (_ctx: unknown, params?: { setId?: string; from?: string; variant?: Record<string, string>; x?: number; y?: number }) =>\n\t\t\t\toutcome(\n\t\t\t\t\tcontroller.addVariant(params?.setId, {\n\t\t\t\t\t\t...(params?.from !== undefined ? { from: params.from } : {}),\n\t\t\t\t\t\t...(params?.variant ? { variant: params.variant } : {}),\n\t\t\t\t\t\t...(params?.x !== undefined || params?.y !== undefined ? { position: { x: params?.x ?? 0, y: params?.y ?? 0 } } : {})\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t} as CommandSpec,\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeVariant`,\n\t\t\tlabel: 'Remove Variant',\n\t\t\tkeywords: ['delete variant', 'variant'],\n\t\t\tdescription: 'Removes a variant; its instances switch to the closest remaining variant, keeping overrides.',\n\t\t\tparams: { type: 'object', properties: { id: VARIANT_ID_PARAM } },\n\t\t\tenabled: (_ctx: unknown, params?: { id?: string }) => controller.canRemoveVariant(params?.id),\n\t\t\trun: (_ctx: unknown, params?: { id?: string }) => outcome(controller.removeVariant(params?.id))\n\t\t} as CommandSpec,\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setVariantProperties`,\n\t\t\tlabel: 'Edit Variant Properties…',\n\t\t\tkeywords: ['rename variant', 'variant values', 'variant'],\n\t\t\tdescription: 'Sets a variant’s property values (refusing a combination another variant has).',\n\t\t\tparams: { type: 'object', properties: { values: VARIANT_VALUES_PARAM, id: VARIANT_ID_PARAM }, required: ['values'] },\n\t\t\tenabled: (_ctx: unknown, params?: { values?: Record<string, string>; id?: string }) => controller.canSetVariantProperties(params?.values, params?.id),\n\t\t\trun: (_ctx: unknown, params: { values: Record<string, string>; id?: string }) => outcome(controller.setVariantProperties(params.values, params?.id))\n\t\t} as CommandSpec,\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}renameVariantProperty`,\n\t\t\tlabel: 'Rename Variant Property…',\n\t\t\tkeywords: ['rename property', 'variant property'],\n\t\t\tdescription: 'Renames a variant property across a component set.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { name: { type: 'string' }, newName: { type: 'string' }, setId: SET_ID_PARAM },\n\t\t\t\trequired: ['name', 'newName']\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { name?: string; newName?: string; setId?: string }) =>\n\t\t\t\tcontroller.canRenameVariantProperty(params?.name, params?.newName, params?.setId),\n\t\t\trun: (_ctx: unknown, params: { name: string; newName: string; setId?: string }) =>\n\t\t\t\toutcome(controller.renameVariantProperty(params.name, params.newName, params?.setId))\n\t\t} as CommandSpec,\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}renameVariantValue`,\n\t\t\tlabel: 'Rename Variant Value…',\n\t\t\tkeywords: ['rename value', 'variant value'],\n\t\t\tdescription: 'Renames a value of a variant property across a component set.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { property: { type: 'string' }, value: { type: 'string' }, newValue: { type: 'string' }, setId: SET_ID_PARAM },\n\t\t\t\trequired: ['property', 'value', 'newValue']\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { property?: string; value?: string; newValue?: string; setId?: string }) =>\n\t\t\t\tcontroller.canRenameVariantValue(params?.property, params?.value, params?.newValue, params?.setId),\n\t\t\trun: (_ctx: unknown, params: { property: string; value: string; newValue: string; setId?: string }) =>\n\t\t\t\toutcome(controller.renameVariantValue(params.property, params.value, params.newValue, params?.setId))\n\t\t} as CommandSpec\n\t];\n}\n\nexport interface ComponentCommandOptions {\n\t/** Id prefix (default `canvas.`). */\n\tprefix?: string;\n\tgroup?: string;\n\t/** Scope (default `canvas`). Pass `null` for global. */\n\tscope?: string | null;\n}\n\nconst outcome = (result: ComponentActionResult) => {\n\tif (!result.ok) throw new Error(result.reason);\n\treturn { ids: result.ids };\n};\n\nconst ID_PARAM = { type: 'string', description: 'Instance (or layer inside one) to act on (default: the first selected node).' } as const;\n\n/**\n * Palette / context-menu / agent commands for components and instances:\n * `canvas.createComponent`, `canvas.combineAsVariants`, `canvas.createInstance`\n * (`{ componentId, parentId?, x?, y?, properties? }`), `canvas.detachInstance`,\n * `canvas.resetOverrides` (`{ id?, group? }`), `canvas.pushOverrides`, `canvas.goToMainComponent`,\n * `canvas.swapInstance` (`{ componentId, ids? }`), `canvas.setInstanceProperties`\n * (`{ properties, ids? }`: variant and component property values), `canvas.restoreMainComponent`,\n * the variant editors `canvas.addVariant` (`{ setId?, from?, variant?, x?, y? }`),\n * `canvas.removeVariant` (`{ id? }`), `canvas.setVariantProperties` (`{ values, id? }`),\n * `canvas.renameVariantProperty` (`{ name, newName, setId? }`) and `canvas.renameVariantValue`\n * (`{ property, value, newValue, setId? }`) when the target has them, and the read-only `canvas.listComponents` / `canvas.inspectInstance`. Each action is one\n * undoable step when the controller has a history; enablement explains why it cannot run.\n */\nexport function createComponentCommands(controller: ComponentCommandTarget, options: ComponentCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'canvas.';\n\tconst group = options.group ?? 'Components';\n\tconst scope = options.scope === null ? undefined : options.scope ?? 'canvas';\n\tconst base = { group, ...(scope ? { scope } : {}) };\n\tconst idParams: CommandParamsSchema = { type: 'object', properties: { id: ID_PARAM } };\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}createComponent`,\n\t\t\tlabel: 'Create Component',\n\t\t\tkeywords: ['component', 'symbol', 'main component', 'reusable'],\n\t\t\tdescription: 'Turns the selected frame into a main component, or wraps the selection in one.',\n\t\t\tparams: IDS_PARAMS,\n\t\t\tshortcut: 'Mod+Alt+K',\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) => controller.canCreateComponent(params?.ids),\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] }) => outcome(controller.createComponent(params?.ids))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}combineAsVariants`,\n\t\t\tlabel: 'Combine as Variants',\n\t\t\tkeywords: ['component set', 'variant', 'variants'],\n\t\t\tdescription: 'Wraps the selected components in a component set.',\n\t\t\tparams: IDS_PARAMS,\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) => controller.canCombineAsVariants(params?.ids),\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] }) => outcome(controller.combineAsVariants(params?.ids))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}createInstance`,\n\t\t\tlabel: 'Create Instance',\n\t\t\tkeywords: ['instance', 'insert component', 'use component'],\n\t\t\tdescription: 'Places an instance of a component (or a component set’s default variant).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tcomponentId: { type: 'string', description: 'Component or component set id.' },\n\t\t\t\t\tparentId: { type: 'string', description: 'Frame to place it in (default: the canvas).' },\n\t\t\t\t\tx: { type: 'number', description: 'X in the parent’s space (default: next to the main).' },\n\t\t\t\t\ty: { type: 'number', description: 'Y in the parent’s space.' },\n\t\t\t\t\tproperties: { type: 'object', description: 'Variant and component property values.', additionalProperties: true }\n\t\t\t\t},\n\t\t\t\trequired: ['componentId']\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { componentId?: string; parentId?: string }) =>\n\t\t\t\tparams?.componentId === undefined ? true : controller.canCreateInstance(params.componentId, params.parentId),\n\t\t\trun: (_ctx: unknown, params: { componentId: string; parentId?: string; x?: number; y?: number; properties?: Record<string, boolean | string> }) =>\n\t\t\t\toutcome(\n\t\t\t\t\tcontroller.createInstance(params.componentId, {\n\t\t\t\t\t\t...(params.parentId !== undefined ? { parentId: params.parentId } : {}),\n\t\t\t\t\t\t...(params.x !== undefined || params.y !== undefined ? { position: { x: params.x ?? 0, y: params.y ?? 0 } } : {}),\n\t\t\t\t\t\t...(params.properties ? { properties: params.properties } : {})\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}detachInstance`,\n\t\t\tlabel: 'Detach Instance',\n\t\t\tkeywords: ['unlink', 'break instance'],\n\t\t\tdescription: 'Turns the selected instances into plain frames that keep their look.',\n\t\t\tparams: IDS_PARAMS,\n\t\t\tshortcut: 'Mod+Alt+B',\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) => controller.canDetachInstance(params?.ids),\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] }) => outcome(controller.detachInstance(params?.ids))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}resetOverrides`,\n\t\t\tlabel: 'Reset All Changes',\n\t\t\tkeywords: ['reset instance', 'reset overrides', 'revert'],\n\t\t\tdescription: 'Resets the overrides of an instance (or of a layer, or one override group) to its main.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tid: ID_PARAM,\n\t\t\t\t\tgroup: { type: 'string', description: 'One override group to reset, e.g. \"data.label\" or \"shape.fill\" (default: all).' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { id?: string }) => controller.canResetOverrides(params?.id),\n\t\t\trun: (_ctx: unknown, params: { id?: string; group?: string }) => outcome(controller.resetOverrides(params?.id, params?.group))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}pushOverrides`,\n\t\t\tlabel: 'Push Changes to Main Component',\n\t\t\tkeywords: ['push overrides', 'update main component'],\n\t\t\tdescription: 'Copies the instance’s overrides to its main component and every other instance.',\n\t\t\tparams: idParams,\n\t\t\tenabled: (_ctx: unknown, params?: { id?: string }) => controller.canPushOverrides(params?.id),\n\t\t\trun: (_ctx: unknown, params: { id?: string }) => outcome(controller.pushOverrides(params?.id))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}goToMainComponent`,\n\t\t\tlabel: 'Go to Main Component',\n\t\t\tkeywords: ['main component', 'find main', 'reveal'],\n\t\t\tdescription: 'Selects the main component of the selected instance.',\n\t\t\tparams: idParams,\n\t\t\tenabled: (_ctx: unknown, params?: { id?: string }) => controller.canGoToMainComponent(params?.id),\n\t\t\trun: (_ctx: unknown, params: { id?: string }) => {\n\t\t\t\tconst main = controller.goToMainComponent(params?.id);\n\t\t\t\tif (!main) throw new Error('The main component was not found.');\n\t\t\t\treturn { id: main };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}swapInstance`,\n\t\t\tlabel: 'Swap Instance…',\n\t\t\tkeywords: ['replace instance', 'swap component'],\n\t\t\tdescription: 'Makes the selected instances show another component, keeping matching overrides.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tcomponentId: { type: 'string', description: 'Component or component set to swap to.' },\n\t\t\t\t\tids: IDS_PARAMS.properties!.ids\n\t\t\t\t},\n\t\t\t\trequired: ['componentId']\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { componentId?: string; ids?: string[] }) => controller.canSwapInstance(params?.componentId, params?.ids),\n\t\t\trun: (_ctx: unknown, params: { componentId: string; ids?: string[] }) => outcome(controller.swapInstance(params.componentId, params?.ids))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setInstanceProperties`,\n\t\t\tlabel: 'Set Instance Properties…',\n\t\t\tkeywords: ['variant', 'switch variant', 'component property', 'toggle'],\n\t\t\tdescription: 'Sets variant properties (switching variants) and component property values of the selected instances.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tproperties: { type: 'object', description: 'Property name → value (variant value, boolean, text or component id).', additionalProperties: true },\n\t\t\t\t\tids: IDS_PARAMS.properties!.ids\n\t\t\t\t},\n\t\t\t\trequired: ['properties']\n\t\t\t},\n\t\t\tenabled: (_ctx: unknown, params?: { ids?: string[] }) => controller.canSetInstanceProperties(params?.ids),\n\t\t\trun: (_ctx: unknown, params: { properties: Record<string, unknown>; ids?: string[] }) =>\n\t\t\t\toutcome(controller.setInstanceProperties(params.properties, params?.ids))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}restoreMainComponent`,\n\t\t\tlabel: 'Restore Main Component',\n\t\t\tkeywords: ['missing main', 'recover component'],\n\t\t\tdescription: 'Turns an instance whose main was deleted back into the main component.',\n\t\t\tparams: idParams,\n\t\t\tenabled: (_ctx: unknown, params?: { id?: string }) => controller.canRestoreMainComponent(params?.id),\n\t\t\trun: (_ctx: unknown, params: { id?: string }) => outcome(controller.restoreMainComponent(params?.id))\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}listComponents`,\n\t\t\tlabel: 'List Components',\n\t\t\tkeywords: ['components', 'variants', 'assets'],\n\t\t\tdescription: 'Lists the components and component sets (with their variant options).',\n\t\t\treadOnly: true,\n\t\t\trun: () => controller.list()\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}inspectInstance`,\n\t\t\tlabel: 'Inspect Instance',\n\t\t\tkeywords: ['instance', 'overrides', 'properties'],\n\t\t\tdescription: 'Describes an instance: its main, variant, property values and overrides.',\n\t\t\tparams: idParams,\n\t\t\treadOnly: true,\n\t\t\tenabled: (_ctx: unknown, params?: { id?: string }) => (controller.inspect(params?.id) ? true : 'Select an instance.'),\n\t\t\trun: (_ctx: unknown, params: { id?: string }) => controller.inspect(params?.id) ?? null\n\t\t},\n\t\t...(hasVariantCommands(controller) ? variantCommands(controller, prefix, base) : [])\n\t];\n}\n\n// ---------------------------------------------------------------------------\n// Spreadsheet table actions\n// ---------------------------------------------------------------------------\n\n/** Spreadsheet controller surface used by `createSpreadsheetCommands`. */\nexport interface SpreadsheetCommandTarget {\n\tselectedRange: unknown;\n\tgetFilterState(): { enabled: boolean; rules: readonly unknown[] };\n\ttoggleFilters(): void;\n\tclearFilters(): void;\n\tunhideAll(): void;\n\tmergeCells(): boolean;\n\tunmergeCells(): boolean;\n\ttransposeRange(): boolean;\n}\n\nexport interface SpreadsheetCommandOptions {\n\t/** Id prefix (default `spreadsheet.`). */\n\tprefix?: string;\n\t/** Scope (default `spreadsheet`). Pass `null` for global. */\n\tscope?: string | null;\n}\n\n/** Palette / agent commands for common spreadsheet table actions (no default shortcuts). */\nexport function createSpreadsheetCommands(\n\tcontroller: SpreadsheetCommandTarget,\n\toptions: SpreadsheetCommandOptions = {}\n): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'spreadsheet.';\n\tconst scope = options.scope === null ? undefined : options.scope ?? 'spreadsheet';\n\tconst hasRange = () => (controller.selectedRange ? true : 'Select a range first.');\n\tconst base = { group: 'Table', ...(scope ? { scope } : {}) };\n\treturn [\n\t\t{ ...base, id: `${prefix}toggleFilters`, label: 'Toggle Filters', keywords: ['filter'], run: () => controller.toggleFilters() },\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}clearFilters`,\n\t\t\tlabel: 'Clear Filters',\n\t\t\tkeywords: ['filter', 'reset'],\n\t\t\tenabled: () => (controller.getFilterState().rules.length > 0 ? true : 'No filters to clear.'),\n\t\t\trun: () => controller.clearFilters()\n\t\t},\n\t\t{ ...base, id: `${prefix}unhideAll`, label: 'Unhide All Rows and Columns', keywords: ['show', 'hidden'], run: () => controller.unhideAll() },\n\t\t{ ...base, id: `${prefix}mergeCells`, label: 'Merge Cells', keywords: ['combine'], enabled: hasRange, run: () => controller.mergeCells() },\n\t\t{ ...base, id: `${prefix}unmergeCells`, label: 'Unmerge Cells', keywords: ['split'], enabled: hasRange, run: () => controller.unmergeCells() },\n\t\t{ ...base, id: `${prefix}transposeRange`, label: 'Transpose Range', keywords: ['rotate', 'swap rows columns'], enabled: hasRange, run: () => controller.transposeRange() }\n\t];\n}\n"],"mappings":";;;;;;AA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,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC,EAAG;AAC3D,SAAO;AAAA,IACN,EAAE,GAAG,MAAM,IAAI,GAAG,MAAM,iBAAiB,OAAO,kBAAkB,UAAU,CAAC,QAAQ,GAAG,KAAK,MAAM,WAAW,cAAc,EAAE;AAAA,IAC9H;AAAA,MACC,GAAG;AAAA,MACH,IAAI,GAAG,MAAM;AAAA,MACb,OAAO;AAAA,MACP,UAAU,CAAC,UAAU,OAAO;AAAA,MAC5B,SAAS,MAAO,WAAW,eAAe,EAAE,MAAM,SAAS,IAAI,OAAO;AAAA,MACtE,KAAK,MAAM,WAAW,aAAa;AAAA,IACpC;AAAA,IACA,EAAE,GAAG,MAAM,IAAI,GAAG,MAAM,aAAa,OAAO,+BAA+B,UAAU,CAAC,QAAQ,QAAQ,GAAG,KAAK,MAAM,WAAW,UAAU,EAAE;AAAA,IAC3I,EAAE,GAAG,MAAM,IAAI,GAAG,MAAM,cAAc,OAAO,eAAe,UAAU,CAAC,SAAS,GAAG,SAAS,UAAU,KAAK,MAAM,WAAW,WAAW,EAAE;AAAA,IACzI,EAAE,GAAG,MAAM,IAAI,GAAG,MAAM,gBAAgB,OAAO,iBAAiB,UAAU,CAAC,OAAO,GAAG,SAAS,UAAU,KAAK,MAAM,WAAW,aAAa,EAAE;AAAA,IAC7I,EAAE,GAAG,MAAM,IAAI,GAAG,MAAM,kBAAkB,OAAO,mBAAmB,UAAU,CAAC,UAAU,mBAAmB,GAAG,SAAS,UAAU,KAAK,MAAM,WAAW,eAAe,EAAE;AAAA,EAC1K;AACD;","names":[]}
@@ -863,6 +863,27 @@ function remapFormulaReferences(formula, moveCell, options = {}) {
863
863
  return `${formatPart({ ...start, row: minR, col: minC })}:${formatPart({ ...end, row: maxR, col: maxC })}`;
864
864
  });
865
865
  }
866
+ function transposeFormulaReferences(formula, anchor, block) {
867
+ const t = { row: block.startRow + (anchor.col - block.startCol), col: block.startCol + (anchor.row - block.startRow) };
868
+ return mapFormulaReferences(formula, (text, info) => {
869
+ const parts = text.split(":").map(parsePart);
870
+ if (parts.some((p) => p === null || p.row === null)) return text;
871
+ const moved = [];
872
+ for (const part of parts) {
873
+ const row = part.row;
874
+ const colAbs = !!part.colAbs;
875
+ const rowAbs = !!part.rowAbs;
876
+ if ((colAbs || rowAbs) && info.sheet !== void 0) return text;
877
+ if (colAbs && (part.col < block.startCol || part.col > block.endCol)) return text;
878
+ if (rowAbs && (row < block.startRow || row > block.endRow)) return text;
879
+ const newRow = colAbs ? block.startRow + (part.col - block.startCol) : t.row + (part.col - anchor.col);
880
+ const newCol = rowAbs ? block.startCol + (row - block.startRow) : t.col + (row - anchor.row);
881
+ if (newRow < 0 || newCol < 0) return "#REF!";
882
+ moved.push({ colAbs: part.rowAbs, col: newCol, rowAbs: part.colAbs, row: newRow });
883
+ }
884
+ return moved.map(formatPart).join(":");
885
+ });
886
+ }
866
887
  var CELL_LIKE = /^[A-Za-z]{1,3}\d{1,7}$/;
867
888
  var isCellLike = (name) => {
868
889
  if (!CELL_LIKE.test(name)) return false;
@@ -1781,6 +1802,175 @@ function parseRuleRanges(text) {
1781
1802
  }
1782
1803
  return out;
1783
1804
  }
1805
+ function mergeRuleRanges(ranges) {
1806
+ const join = (list, across) => {
1807
+ const [lo, hi, fixedLo, fixedHi] = across === "row" ? ["startRow", "endRow", "startCol", "endCol"] : ["startCol", "endCol", "startRow", "endRow"];
1808
+ const sorted = list.map(normalizeRange).sort((a, b) => a[fixedLo] - b[fixedLo] || a[fixedHi] - b[fixedHi] || a[lo] - b[lo]);
1809
+ const out = [];
1810
+ for (const r of sorted) {
1811
+ const last = out[out.length - 1];
1812
+ if (last && last[fixedLo] === r[fixedLo] && last[fixedHi] === r[fixedHi] && r[lo] <= last[hi] + 1) {
1813
+ last[hi] = Math.max(last[hi], r[hi]);
1814
+ } else {
1815
+ out.push({ ...r });
1816
+ }
1817
+ }
1818
+ return out;
1819
+ };
1820
+ return join(join(ranges, "row"), "col").sort((a, b) => a.startRow - b.startRow || a.startCol - b.startCol);
1821
+ }
1822
+ function sortRuleRanges(ranges, block, newRowOf) {
1823
+ const b = normalizeRange(block);
1824
+ let changed = false;
1825
+ const pieces = [];
1826
+ const moved = /* @__PURE__ */ new Map();
1827
+ for (const range of ranges) {
1828
+ const r = normalizeRange(range);
1829
+ const top = Math.max(r.startRow, b.startRow);
1830
+ const bottom = Math.min(r.endRow, b.endRow);
1831
+ const left = Math.max(r.startCol, b.startCol);
1832
+ const right = Math.min(r.endCol, b.endCol);
1833
+ if (top > bottom || left > right || top === b.startRow && bottom === b.endRow) {
1834
+ pieces.push(r);
1835
+ continue;
1836
+ }
1837
+ changed = true;
1838
+ pieces.push(...subtractRange(r, b));
1839
+ const key = `${left}:${right}`;
1840
+ let entry = moved.get(key);
1841
+ if (!entry) moved.set(key, entry = { startCol: left, endCol: right, rows: [] });
1842
+ for (let row = top; row <= bottom; row++) entry.rows.push(newRowOf(row));
1843
+ }
1844
+ if (!changed) return null;
1845
+ for (const { startCol, endCol, rows } of moved.values()) {
1846
+ rows.sort((x, y) => x - y);
1847
+ let start = rows[0];
1848
+ for (let i = 1; i <= rows.length; i++) {
1849
+ if (i < rows.length && rows[i] <= rows[i - 1] + 1) continue;
1850
+ pieces.push({ startRow: start, startCol, endRow: rows[i - 1], endCol });
1851
+ start = rows[i];
1852
+ }
1853
+ }
1854
+ return mergeRuleRanges(pieces);
1855
+ }
1856
+ function transposeRuleRanges(ranges, block, target) {
1857
+ const s = normalizeRange(block);
1858
+ const t = normalizeRange(target);
1859
+ if (!ranges.some((r) => rangesIntersect(r, s) || rangesIntersect(r, t))) return null;
1860
+ const inside = [];
1861
+ for (const range of ranges) {
1862
+ const r = normalizeRange(range);
1863
+ if (!rangesIntersect(r, s)) continue;
1864
+ const top = Math.max(r.startRow, s.startRow);
1865
+ const bottom = Math.min(r.endRow, s.endRow);
1866
+ const left = Math.max(r.startCol, s.startCol);
1867
+ const right = Math.min(r.endCol, s.endCol);
1868
+ inside.push({
1869
+ startRow: s.startRow + (left - s.startCol),
1870
+ endRow: s.startRow + (right - s.startCol),
1871
+ startCol: s.startCol + (top - s.startRow),
1872
+ endCol: s.startCol + (bottom - s.startRow)
1873
+ });
1874
+ }
1875
+ const outside = subtractRangeFromRanges(subtractRangeFromRanges(ranges, s), t);
1876
+ return { inside: mergeRuleRanges(inside), outside: mergeRuleRanges(outside) };
1877
+ }
1878
+ function reanchorRuleFormula(formula, from, to) {
1879
+ if (from.row === to.row && from.col === to.col) return formula;
1880
+ const hadEquals = formula.trimStart().startsWith("=");
1881
+ const moved = ruleFormulaAt(formula, from, to.row, to.col);
1882
+ return hadEquals ? moved : moved.slice(1);
1883
+ }
1884
+ function transposeRuleFormula(formula, anchor, block) {
1885
+ const hadEquals = formula.trimStart().startsWith("=");
1886
+ const out = transposeFormulaReferences(withEquals(formula), anchor, normalizeRange(block));
1887
+ return hadEquals ? out : out.slice(1);
1888
+ }
1889
+ var isFormulaText = (text) => text !== void 0 && text.trimStart().startsWith("=");
1890
+ function mapConditionalFormatFormulas(rule, fn) {
1891
+ const anchor = (value) => value.type === "formula" ? { ...value, formula: fn(value.formula) } : value;
1892
+ const next = { ...rule };
1893
+ if (next.type === "expression") next.formula = fn(next.formula);
1894
+ if (next.type === "cellIs") {
1895
+ if (isFormulaText(next.value)) next.value = fn(next.value);
1896
+ if (isFormulaText(next.value2)) next.value2 = fn(next.value2);
1897
+ }
1898
+ if (next.type === "colorScale") next.stops = next.stops.map((s) => ({ ...s, value: anchor(s.value) }));
1899
+ if (next.type === "dataBar") {
1900
+ if (next.min) next.min = anchor(next.min);
1901
+ if (next.max) next.max = anchor(next.max);
1902
+ }
1903
+ if (next.type === "iconSet" && next.thresholds) next.thresholds = next.thresholds.map(anchor);
1904
+ return next;
1905
+ }
1906
+ function mapDataValidationFormulas(rule, fn) {
1907
+ const next = { ...rule };
1908
+ if (isFormulaText(next.formula1)) next.formula1 = fn(next.formula1);
1909
+ if (isFormulaText(next.formula2)) next.formula2 = fn(next.formula2);
1910
+ return next;
1911
+ }
1912
+ function hasRuleFormulas(rule, mapFormulas) {
1913
+ let found = false;
1914
+ mapFormulas(rule, (f) => {
1915
+ found = true;
1916
+ return f;
1917
+ });
1918
+ return found;
1919
+ }
1920
+ var sameCell = (a, b) => a.row === b.row && a.col === b.col;
1921
+ function sortRules(rules, block, newRowOf, mapFormulas) {
1922
+ let changed = false;
1923
+ const out = rules.map((rule) => {
1924
+ const ranges = sortRuleRanges(rule.ranges, block, newRowOf);
1925
+ if (!ranges) return rule;
1926
+ changed = true;
1927
+ const from = ruleAnchor(rule.ranges);
1928
+ const to = ruleAnchor(ranges);
1929
+ const next = { ...rule, ranges };
1930
+ return sameCell(from, to) ? next : mapFormulas(next, (f) => reanchorRuleFormula(f, from, to));
1931
+ });
1932
+ return changed ? out : rules;
1933
+ }
1934
+ function transposeRules(rules, block, target, mapFormulas, newId) {
1935
+ const s = normalizeRange(block);
1936
+ let changed = false;
1937
+ const out = [];
1938
+ for (const rule of rules) {
1939
+ const moved = transposeRuleRanges(rule.ranges, s, target);
1940
+ if (!moved) {
1941
+ out.push(rule);
1942
+ continue;
1943
+ }
1944
+ changed = true;
1945
+ const { inside, outside } = moved;
1946
+ const from = ruleAnchor(rule.ranges);
1947
+ const withFormulas = hasRuleFormulas(rule, mapFormulas);
1948
+ const stayed = () => {
1949
+ const to = ruleAnchor(outside);
1950
+ const next = { ...rule, ranges: outside };
1951
+ return withFormulas && !sameCell(from, to) ? mapFormulas(next, (f) => reanchorRuleFormula(f, from, to)) : next;
1952
+ };
1953
+ const transposed = () => {
1954
+ const next = { ...rule, ranges: inside };
1955
+ if (!withFormulas) return next;
1956
+ const first2 = rule.ranges.map(normalizeRange).find((r) => rangesIntersect(r, s));
1957
+ const at = { row: Math.max(first2.startRow, s.startRow), col: Math.max(first2.startCol, s.startCol) };
1958
+ const atT = { row: s.startRow + (at.col - s.startCol), col: s.startCol + (at.row - s.startRow) };
1959
+ const to = ruleAnchor(inside);
1960
+ return mapFormulas(next, (f) => reanchorRuleFormula(transposeRuleFormula(reanchorRuleFormula(f, from, at), at, s), atT, to));
1961
+ };
1962
+ if (inside.length === 0) {
1963
+ if (outside.length > 0) out.push(stayed());
1964
+ } else if (outside.length === 0) {
1965
+ out.push(transposed());
1966
+ } else if (!withFormulas) {
1967
+ out.push({ ...rule, ranges: mergeRuleRanges([...outside, ...inside]) });
1968
+ } else {
1969
+ out.push(stayed(), { ...transposed(), id: newId() });
1970
+ }
1971
+ }
1972
+ return changed ? out : rules;
1973
+ }
1784
1974
 
1785
1975
  // src/spreadsheet/conditional-format/icons.ts
1786
1976
  var RED = "#d9534f";
@@ -1877,13 +2067,13 @@ function defaultIconThresholds(set) {
1877
2067
  return Array.from({ length: k }, (_, i) => ({ type: "percent", value: Math.round(i * 100 / k) }));
1878
2068
  }
1879
2069
  var usesStats = (rule) => rule.type === "colorScale" || rule.type === "dataBar" || rule.type === "iconSet" || rule.type === "top10" || rule.type === "aboveAverage" || rule.type === "duplicate" || rule.type === "unique";
1880
- var isFormulaText = (text) => !!text && text.trimStart().startsWith("=");
2070
+ var isFormulaText2 = (text) => !!text && text.trimStart().startsWith("=");
1881
2071
  function usesFormulas(rule) {
1882
2072
  switch (rule.type) {
1883
2073
  case "expression":
1884
2074
  return true;
1885
2075
  case "cellIs":
1886
- return isFormulaText(rule.value) || isFormulaText(rule.value2);
2076
+ return isFormulaText2(rule.value) || isFormulaText2(rule.value2);
1887
2077
  case "colorScale":
1888
2078
  return rule.stops.some((s) => s.value.type === "formula");
1889
2079
  case "dataBar":
@@ -2056,7 +2246,7 @@ var ConditionalFormatEngine = class {
2056
2246
  /** The operand of a `cellIs` rule: a formula result, or typed input. */
2057
2247
  operand(text, rule, row, col) {
2058
2248
  if (text === void 0) return "";
2059
- if (isFormulaText(text)) return this.evalFormula(text, rule, row, col);
2249
+ if (isFormulaText2(text)) return this.evalFormula(text, rule, row, col);
2060
2250
  return parseCellInput(text).value;
2061
2251
  }
2062
2252
  /** Combines every rule that applies to (row, col). */
@@ -2826,6 +3016,33 @@ var createRuntime = (doc) => ({
2826
3016
  selectedRange: null
2827
3017
  });
2828
3018
  var sameName3 = (a, b) => a.toUpperCase() === b.toUpperCase();
3019
+ var nameKey = (n) => `${n.sheetId ?? ""}!${n.name.toUpperCase()}`;
3020
+ function normalizeSavedName(n, sheetId) {
3021
+ if (!n || typeof n.name !== "string" || typeof n.refersTo !== "string" || n.name === "") return null;
3022
+ const { sheetId: _ignored, ...rest } = n;
3023
+ return {
3024
+ ...rest,
3025
+ refersTo: n.refersTo.startsWith("=") ? n.refersTo : `=${n.refersTo}`,
3026
+ ...sheetId !== void 0 ? { sheetId } : {}
3027
+ };
3028
+ }
3029
+ function namesFromDocument(doc, sheetId) {
3030
+ if (!Array.isArray(doc?.names)) return [];
3031
+ const out = [];
3032
+ const seen = /* @__PURE__ */ new Set();
3033
+ for (const saved of doc.names) {
3034
+ const n = normalizeSavedName(saved, saved?.sheetId !== void 0 ? sheetId : void 0);
3035
+ if (!n || seen.has(nameKey(n))) continue;
3036
+ seen.add(nameKey(n));
3037
+ out.push(n);
3038
+ }
3039
+ return out;
3040
+ }
3041
+ function withoutNames(doc) {
3042
+ if (!("names" in doc)) return doc;
3043
+ const { names: _names, ...rest } = doc;
3044
+ return rest;
3045
+ }
2829
3046
  var DEFAULT_MAX_HISTORY_BYTES = 64 * 1024 * 1024;
2830
3047
  var AST_CACHE_SIZE = 1e5;
2831
3048
  var RANGE_CACHE_MIN_CELLS = 256;
@@ -2952,11 +3169,13 @@ var SpreadsheetController = class {
2952
3169
  ...options.document?.table ? { table: options.document.table } : {}
2953
3170
  };
2954
3171
  if (options.workbook && options.workbook.sheets.length > 0) {
2955
- this.setWorkbookState(options.workbook, false);
3172
+ this.setWorkbookState({ ...options.workbook, sheets: options.workbook.sheets.map((doc) => ({ ...doc })) }, false);
2956
3173
  } else {
2957
3174
  this.runtimes = [createRuntime(first2)];
2958
3175
  this.active = this.ctx = this.runtimes[0];
3176
+ this.names = namesFromDocument(options.document, first2.id);
2959
3177
  }
3178
+ this.syncDocumentNames();
2960
3179
  this.boundSheetId = this.runtimes[0].doc.id;
2961
3180
  this.primaryDataSourceId = options.primaryDataSourceId;
2962
3181
  this.maxHistoryBytes = Math.max(0, options.maxHistoryBytes ?? DEFAULT_MAX_HISTORY_BYTES);
@@ -3068,6 +3287,7 @@ var SpreadsheetController = class {
3068
3287
  for (const n of this.names) if (n.sheetId === previousId) n.sheetId = loaded.id;
3069
3288
  if (this.boundSheetId === previousId) this.boundSheetId = loaded.id;
3070
3289
  }
3290
+ if (Array.isArray(document.names)) this.loadDocumentNames(document, loaded.id);
3071
3291
  this.activeCell = null;
3072
3292
  this.selectedRange = null;
3073
3293
  this.editingCell = null;
@@ -3080,9 +3300,40 @@ var SpreadsheetController = class {
3080
3300
  this.notifyChange();
3081
3301
  }
3082
3302
  // --- Workbook: loading and saving ---
3083
- /** A deep copy of the workbook: every sheet, the active sheet and the defined names. */
3303
+ /**
3304
+ * Installs the names saved in a document loaded into sheet `sheetId`: they
3305
+ * replace that sheet's own names and, when it is the only sheet, the
3306
+ * workbook names; with other sheets, its workbook names are added (or
3307
+ * replace the same name) and the others are kept.
3308
+ */
3309
+ loadDocumentNames(document, sheetId) {
3310
+ const saved = namesFromDocument(document, sheetId);
3311
+ const onlySheet = this.runtimes.length === 1;
3312
+ const keys = new Set(saved.map(nameKey));
3313
+ this.names = this.names.filter(
3314
+ (n) => n.sheetId !== sheetId && !(n.sheetId === void 0 && (onlySheet || keys.has(nameKey(n))))
3315
+ );
3316
+ this.names.push(...saved);
3317
+ }
3318
+ /**
3319
+ * Writes every sheet's current names into its document (`doc.names`), so
3320
+ * documents passed to `onDocumentChange` or read from `document` carry them.
3321
+ */
3322
+ syncDocumentNames() {
3323
+ for (const rt of this.runtimes) {
3324
+ const names = this.names.filter((n) => n.sheetId === void 0 || n.sheetId === rt.doc.id).map((n) => ({ ...n }));
3325
+ if (names.length > 0) rt.doc.names = names;
3326
+ else delete rt.doc.names;
3327
+ }
3328
+ }
3329
+ /**
3330
+ * A deep copy of the workbook: every sheet, the active sheet and the
3331
+ * defined names. The names are in `names` only (not repeated in each
3332
+ * sheet's `names`).
3333
+ */
3084
3334
  getWorkbook() {
3085
- return JSON.parse(JSON.stringify(this.workbookSnapshot()));
3335
+ const snapshot = this.workbookSnapshot();
3336
+ return JSON.parse(JSON.stringify({ ...snapshot, sheets: snapshot.sheets.map(withoutNames) }));
3086
3337
  }
3087
3338
  /** Replaces the whole workbook (sheets, names, active sheet). Clears undo history. */
3088
3339
  loadWorkbook(workbook) {
@@ -3099,6 +3350,11 @@ var SpreadsheetController = class {
3099
3350
  this.notifyChange();
3100
3351
  this.onSelectionChange?.(this.activeCell, this.selectedRange);
3101
3352
  }
3353
+ /** The workbook as undo data; sheets leave out their copies of the names. */
3354
+ serializeWorkbookSnapshot() {
3355
+ const snapshot = this.workbookSnapshot();
3356
+ return JSON.stringify({ ...snapshot, sheets: snapshot.sheets.map(withoutNames) });
3357
+ }
3102
3358
  workbookSnapshot() {
3103
3359
  return {
3104
3360
  sheets: this.runtimes.map((rt) => rt.doc),
@@ -3127,7 +3383,19 @@ var SpreadsheetController = class {
3127
3383
  });
3128
3384
  this.runtimes = runtimes;
3129
3385
  this.active = this.ctx = runtimes.find((rt) => rt.doc.id === workbook.activeSheetId) ?? runtimes[0];
3130
- this.names = (workbook.names ?? []).filter((n) => n.sheetId === void 0 || ids.has(n.sheetId)).map((n) => ({ ...n, refersTo: n.refersTo.startsWith("=") ? n.refersTo : `=${n.refersTo}` }));
3386
+ const seen = /* @__PURE__ */ new Set();
3387
+ this.names = [];
3388
+ const add = (n) => {
3389
+ if (!n || seen.has(nameKey(n))) return;
3390
+ seen.add(nameKey(n));
3391
+ this.names.push(n);
3392
+ };
3393
+ for (const n of workbook.names ?? []) {
3394
+ if (n?.sheetId === void 0 || ids.has(n.sheetId)) add(normalizeSavedName(n, n?.sheetId));
3395
+ }
3396
+ for (const rt of runtimes) {
3397
+ for (const n of namesFromDocument(rt.doc, rt.doc.id)) add(n);
3398
+ }
3131
3399
  if (resetSelection) {
3132
3400
  this.activeCell = null;
3133
3401
  this.selectedRange = null;
@@ -4464,6 +4732,10 @@ var SpreadsheetController = class {
4464
4732
  if (target === void 0 || col < startCol || col > endCol) return null;
4465
4733
  return { row: target, col };
4466
4734
  });
4735
+ this.moveRulesForSort(
4736
+ { startRow, startCol, endRow, endCol: wholeRows ? Number.MAX_SAFE_INTEGER : endCol },
4737
+ (row) => newIndexOf.get(row) ?? row
4738
+ );
4467
4739
  if (wholeRows) {
4468
4740
  const moved = sorted.map((r) => this.document.rows[r]);
4469
4741
  this.document.rows.splice(startRow, moved.length, ...moved);
@@ -4890,6 +5162,7 @@ var SpreadsheetController = class {
4890
5162
  if (!rangeContains(s, row, col)) return null;
4891
5163
  return { row: s.startRow + (col - s.startCol), col: s.startCol + (row - s.startRow) };
4892
5164
  });
5165
+ this.moveRulesForTranspose(s, t);
4893
5166
  const rowId = (r) => this.document.rows[r].id;
4894
5167
  const colId = (c) => this.document.columns[c].id;
4895
5168
  const moved = [];
@@ -4997,6 +5270,10 @@ var SpreadsheetController = class {
4997
5270
  id,
4998
5271
  name
4999
5272
  };
5273
+ const existingNames = new Set(this.names.map(nameKey));
5274
+ for (const n of namesFromDocument(options.document, id)) {
5275
+ if (!existingNames.has(nameKey(n))) this.names.push(n);
5276
+ }
5000
5277
  const rt = createRuntime(doc);
5001
5278
  const index = Math.max(0, Math.min(options.index ?? this.runtimes.length, this.runtimes.length));
5002
5279
  this.runtimes.splice(index, 0, rt);
@@ -5084,6 +5361,7 @@ var SpreadsheetController = class {
5084
5361
  doc.id = this.generateSheetId();
5085
5362
  doc.name = name;
5086
5363
  doc.createdAt = doc.updatedAt = Date.now();
5364
+ delete doc.names;
5087
5365
  const copies = this.names.filter((n) => n.sheetId === source.doc.id).map((n) => ({ ...n, sheetId: doc.id, refersTo: renameSheetInFormula(n.refersTo, source.doc.name, name) }));
5088
5366
  this.names.push(...copies);
5089
5367
  const rt = createRuntime(doc);
@@ -5283,7 +5561,7 @@ var SpreadsheetController = class {
5283
5561
  }
5284
5562
  recordWorkbookSnapshot() {
5285
5563
  if (this.isApplyingHistory || this.batching) return;
5286
- this.pushUndo({ kind: "workbook", data: JSON.stringify(this.workbookSnapshot()) });
5564
+ this.pushUndo({ kind: "workbook", data: this.serializeWorkbookSnapshot() });
5287
5565
  }
5288
5566
  pushUndo(entry) {
5289
5567
  this.undoStack.push(entry);
@@ -5363,7 +5641,7 @@ var SpreadsheetController = class {
5363
5641
  this.activateRuntime(rt);
5364
5642
  }
5365
5643
  } else {
5366
- to.push({ kind: "workbook", data: JSON.stringify(this.workbookSnapshot()) });
5644
+ to.push({ kind: "workbook", data: this.serializeWorkbookSnapshot() });
5367
5645
  const previousActive = this.active.doc.id;
5368
5646
  const selection = { activeCell: this.activeCell, selectedRange: this.selectedRange };
5369
5647
  const saved = new Map(this.runtimes.map((rt) => [rt.doc.id, rt]));
@@ -5394,6 +5672,7 @@ var SpreadsheetController = class {
5394
5672
  notifyChange() {
5395
5673
  if (!this.cfIncremental) this.cfDirty = "all";
5396
5674
  this.invalidCircles = null;
5675
+ this.syncDocumentNames();
5397
5676
  this.onDocumentChange?.(this.active.doc);
5398
5677
  if (this.onWorkbookChange) {
5399
5678
  const snapshot = this.workbookSnapshot();
@@ -5477,6 +5756,43 @@ var SpreadsheetController = class {
5477
5756
  }).filter((rule) => rule.ranges.length > 0);
5478
5757
  }
5479
5758
  }
5759
+ /**
5760
+ * Moves conditional formats and validations with sorted rows: per-row
5761
+ * parts follow their rows, parts spanning every sorted row stay (Excel).
5762
+ */
5763
+ moveRulesForSort(block, newRowOf) {
5764
+ const table = this.document.table;
5765
+ if (!table) return;
5766
+ if (table.conditionalFormats?.length) {
5767
+ table.conditionalFormats = sortRules(table.conditionalFormats, block, newRowOf, mapConditionalFormatFormulas);
5768
+ }
5769
+ if (table.dataValidations?.length) {
5770
+ table.dataValidations = sortRules(table.dataValidations, block, newRowOf, mapDataValidationFormulas);
5771
+ }
5772
+ }
5773
+ /** Moves conditional formats and validations of a transposed block with its cells. */
5774
+ moveRulesForTranspose(block, target) {
5775
+ const table = this.document.table;
5776
+ if (!table) return;
5777
+ if (table.conditionalFormats?.length) {
5778
+ table.conditionalFormats = transposeRules(
5779
+ table.conditionalFormats,
5780
+ block,
5781
+ target,
5782
+ mapConditionalFormatFormulas,
5783
+ () => this.generateRuleId("cf")
5784
+ );
5785
+ }
5786
+ if (table.dataValidations?.length) {
5787
+ table.dataValidations = transposeRules(
5788
+ table.dataValidations,
5789
+ block,
5790
+ target,
5791
+ mapDataValidationFormulas,
5792
+ () => this.generateRuleId("dv")
5793
+ );
5794
+ }
5795
+ }
5480
5796
  /** Conditional formats of the sheet, highest priority first. */
5481
5797
  getConditionalFormats() {
5482
5798
  return this.document.table?.conditionalFormats ?? [];
@@ -6355,6 +6671,7 @@ export {
6355
6671
  mapFormulaReferences,
6356
6672
  offsetFormulaReferences,
6357
6673
  remapFormulaReferences,
6674
+ transposeFormulaReferences,
6358
6675
  sheetNameNeedsQuotes,
6359
6676
  quoteSheetName,
6360
6677
  formatSheetPrefix,
@@ -6411,6 +6728,15 @@ export {
6411
6728
  forEachRangeCell,
6412
6729
  formatRuleRanges,
6413
6730
  parseRuleRanges,
6731
+ mergeRuleRanges,
6732
+ sortRuleRanges,
6733
+ transposeRuleRanges,
6734
+ reanchorRuleFormula,
6735
+ transposeRuleFormula,
6736
+ mapConditionalFormatFormulas,
6737
+ mapDataValidationFormulas,
6738
+ sortRules,
6739
+ transposeRules,
6414
6740
  CONDITIONAL_FORMAT_ICON_SETS,
6415
6741
  conditionalFormatIconCount,
6416
6742
  getConditionalFormatIcon,
@@ -6475,4 +6801,4 @@ export {
6475
6801
  getSpreadsheetScrollToCell,
6476
6802
  sameSpreadsheetViewWindow
6477
6803
  };
6478
- //# sourceMappingURL=chunk-X7HXL2SB.js.map
6804
+ //# sourceMappingURL=chunk-JT7AXQTE.js.map