@pixerate/editor 0.126.0 → 0.128.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/dist/agent/index.cjs +2 -2
- package/dist/agent/index.d.cts +3 -3
- package/dist/agent/index.d.ts +3 -3
- package/dist/agent/index.js +1 -1
- package/dist/animation/index.d.cts +2 -3
- package/dist/animation/index.d.ts +2 -3
- package/dist/animation-editor/index.cjs +63 -63
- package/dist/animation-editor/index.cjs.map +1 -1
- package/dist/animation-editor/index.d.cts +7 -9
- package/dist/animation-editor/index.d.ts +7 -9
- package/dist/animation-editor/index.js +10 -10
- package/dist/{arrange-BlfgJ_wt.d.ts → arrange-BUREmgD9.d.ts} +1 -1
- package/dist/{arrange-CD6Gh-pd.d.cts → arrange-CKXK_hf7.d.cts} +1 -1
- package/dist/{bezier-CWv6LQal.d.ts → bezier-CvgQiYRg.d.cts} +23 -3
- package/dist/{bezier-CBzKKDjl.d.cts → bezier-DP4NnJp3.d.ts} +23 -3
- package/dist/{brushTypes-IG7ZZjIN.d.cts → brushTypes-C7N3EBK7.d.cts} +56 -1
- package/dist/{brushTypes-IG7ZZjIN.d.ts → brushTypes-C7N3EBK7.d.ts} +56 -1
- package/dist/{brushstrokeRender-EELTV7U4.cjs → brushstrokeRender-JNHVEUFG.cjs} +29 -10
- package/dist/brushstrokeRender-JNHVEUFG.cjs.map +1 -0
- package/dist/{brushstrokeRender-LRV7GXGD.js → brushstrokeRender-SII6MG4R.js} +25 -6
- package/dist/brushstrokeRender-SII6MG4R.js.map +1 -0
- package/dist/{builtins-DMIsnNst.d.cts → builtins-Cc-bH-3U.d.cts} +3 -2
- package/dist/{builtins-B5-ipm5u.d.ts → builtins-ZU1GJnUA.d.ts} +3 -2
- package/dist/canvas/index.cjs +435 -38
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.d.cts +206 -16
- package/dist/canvas/index.d.ts +206 -16
- package/dist/canvas/index.js +408 -11
- package/dist/canvas/index.js.map +1 -1
- package/dist/{chunk-MPQAO33O.js → chunk-A6KHMKI4.js} +3 -3
- package/dist/{chunk-V5YGPRCZ.cjs → chunk-BEGEWQHD.cjs} +41 -41
- package/dist/{chunk-V5YGPRCZ.cjs.map → chunk-BEGEWQHD.cjs.map} +1 -1
- package/dist/{chunk-N3FVUOZD.cjs → chunk-BJTCSLF6.cjs} +7 -7
- package/dist/{chunk-N3FVUOZD.cjs.map → chunk-BJTCSLF6.cjs.map} +1 -1
- package/dist/{chunk-7LQO6OHH.cjs → chunk-DDSO4HS7.cjs} +9 -5
- package/dist/chunk-DDSO4HS7.cjs.map +1 -0
- package/dist/{chunk-AKU2KQ47.cjs → chunk-DFSZO2B5.cjs} +70 -3
- package/dist/chunk-DFSZO2B5.cjs.map +1 -0
- package/dist/{chunk-WUDPFWAN.js → chunk-F7Q2NE2Y.js} +3 -3
- package/dist/{chunk-GUZ47CJM.cjs → chunk-IZ4WRXZA.cjs} +1 -1
- package/dist/{chunk-GUZ47CJM.cjs.map → chunk-IZ4WRXZA.cjs.map} +1 -1
- package/dist/{chunk-GLWZXQ4Q.js → chunk-KHNZ6MOU.js} +1 -1
- package/dist/chunk-KHNZ6MOU.js.map +1 -0
- package/dist/{chunk-GCJWMEYW.cjs → chunk-KSJLDRHK.cjs} +46 -46
- package/dist/{chunk-GCJWMEYW.cjs.map → chunk-KSJLDRHK.cjs.map} +1 -1
- package/dist/{chunk-2SDGZAJR.js → chunk-LSXXAJG3.js} +70 -3
- package/dist/chunk-LSXXAJG3.js.map +1 -0
- package/dist/{chunk-QQKTOA4U.cjs → chunk-ORE334I6.cjs} +132 -132
- package/dist/{chunk-QQKTOA4U.cjs.map → chunk-ORE334I6.cjs.map} +1 -1
- package/dist/{chunk-X6KTSFAE.js → chunk-Q4NBEVV5.js} +2 -2
- package/dist/{chunk-FPRIUR4T.js → chunk-ROZFX4QI.js} +3 -3
- package/dist/{chunk-J67OLQUQ.js → chunk-SVYE5HIM.js} +7 -3
- package/dist/chunk-SVYE5HIM.js.map +1 -0
- package/dist/{chunk-O5RVCDEC.cjs → chunk-XLUYXUBD.cjs} +88 -88
- package/dist/{chunk-O5RVCDEC.cjs.map → chunk-XLUYXUBD.cjs.map} +1 -1
- package/dist/{chunk-FG274FYT.js → chunk-YGJIER2R.js} +2 -2
- package/dist/commands/index.cjs +2 -2
- package/dist/commands/index.d.cts +3 -3
- package/dist/commands/index.d.ts +3 -3
- package/dist/commands/index.js +1 -1
- package/dist/effects/index.d.cts +6 -38
- package/dist/effects/index.d.ts +6 -38
- package/dist/evaluate-BbCeF6pt.d.ts +114 -0
- package/dist/evaluate-BsxYieLN.d.cts +114 -0
- package/dist/{export-Bp7ji2r4.d.cts → export-BkYQvV56.d.cts} +4 -4
- package/dist/{export-DVl4fWy5.d.cts → export-Cbr9IqpJ.d.cts} +1 -1
- package/dist/{export-C1s4eolZ.d.ts → export-ClPKUB-v.d.ts} +1 -1
- package/dist/{export-DAyPY94f.d.ts → export-DHrFJ8r_.d.ts} +4 -4
- package/dist/{helpers-i95Ob6Vi.d.cts → helpers-C5aAd44p.d.cts} +67 -4
- package/dist/{helpers-BBLlekuM.d.ts → helpers-CPWcK504.d.ts} +67 -4
- package/dist/image-editor/index.cjs +606 -606
- package/dist/image-editor/index.cjs.map +1 -1
- package/dist/image-editor/index.d.cts +12 -14
- package/dist/image-editor/index.d.ts +12 -14
- package/dist/image-editor/index.js +4 -4
- package/dist/{opentype-D80AVmMu.d.cts → opentype-BOewaGQx.d.cts} +1 -1
- package/dist/{opentype-14PDI5D2.d.ts → opentype-sQrF3Ry1.d.ts} +1 -1
- package/dist/paint/index.d.cts +2 -2
- package/dist/paint/index.d.ts +2 -2
- package/dist/paint-editor/index.cjs +9 -9
- package/dist/paint-editor/index.cjs.map +1 -1
- package/dist/paint-editor/index.d.cts +9 -11
- package/dist/paint-editor/index.d.ts +9 -11
- package/dist/paint-editor/index.js +4 -4
- package/dist/{pathfinder-DjISxkUv.d.ts → pathfinder-BwJx0_zM.d.ts} +2 -2
- package/dist/{pathfinder-C0UoFypx.d.cts → pathfinder-CnkW7zLI.d.cts} +2 -2
- package/dist/{player-cGLrngL_.d.ts → player-BK2kKbfd.d.ts} +1 -1
- package/dist/{player-CBtEoU2x.d.cts → player-CmbY3218.d.cts} +1 -1
- package/dist/pool-C7GtrL34.d.cts +34 -0
- package/dist/pool-CTrtciaN.d.ts +34 -0
- package/dist/{rand-CfinE-1c.d.cts → rand-DTXAssW1.d.cts} +4 -4
- package/dist/{rand-DtazXGOB.d.ts → rand-pQQ2sJTk.d.ts} +4 -4
- package/dist/{svg-DJKriJ4A.d.ts → svg-C4LlFnEw.d.cts} +2 -3
- package/dist/{svg-BkRL-fZJ.d.cts → svg-CUzZa0EO.d.ts} +2 -3
- package/dist/{tools-CM8Oe8F3.d.ts → tools-AugT22z3.d.ts} +1 -1
- package/dist/{tools-DZCv2kX1.d.cts → tools-BpCmUNxb.d.cts} +1 -1
- package/dist/vector/index.cjs +918 -918
- package/dist/vector/index.cjs.map +1 -1
- package/dist/vector/index.d.cts +11 -13
- package/dist/vector/index.d.ts +11 -13
- package/dist/vector/index.js +11 -11
- package/dist/video-editor/index.d.cts +6 -8
- package/dist/video-editor/index.d.ts +6 -8
- package/dist/{warp-k_PdtXOG.d.ts → warp-CIsO617e.d.ts} +1 -1
- package/dist/{warp-CH9MM435.d.cts → warp-D62N_5VK.d.cts} +1 -1
- package/package.json +1 -1
- package/skills/pixerate-canvas/SKILL.md +30 -2
- package/dist/behavior-Ymbld6jL.d.cts +0 -60
- package/dist/behavior-Ymbld6jL.d.ts +0 -60
- package/dist/brushstrokeRender-EELTV7U4.cjs.map +0 -1
- package/dist/brushstrokeRender-LRV7GXGD.js.map +0 -1
- package/dist/chunk-2SDGZAJR.js.map +0 -1
- package/dist/chunk-7LQO6OHH.cjs.map +0 -1
- package/dist/chunk-AKU2KQ47.cjs.map +0 -1
- package/dist/chunk-GLWZXQ4Q.js.map +0 -1
- package/dist/chunk-J67OLQUQ.js.map +0 -1
- package/dist/evaluate-2S3vSPLy.d.cts +0 -55
- package/dist/evaluate-CfmT6xA3.d.ts +0 -55
- package/dist/gradient-KDfCvhuj.d.cts +0 -66
- package/dist/gradient-KDfCvhuj.d.ts +0 -66
- /package/dist/{chunk-MPQAO33O.js.map → chunk-A6KHMKI4.js.map} +0 -0
- /package/dist/{chunk-WUDPFWAN.js.map → chunk-F7Q2NE2Y.js.map} +0 -0
- /package/dist/{chunk-X6KTSFAE.js.map → chunk-Q4NBEVV5.js.map} +0 -0
- /package/dist/{chunk-FPRIUR4T.js.map → chunk-ROZFX4QI.js.map} +0 -0
- /package/dist/{chunk-FG274FYT.js.map → chunk-YGJIER2R.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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 { CanvasBrush, CanvasBrushPreset } from '../canvas/brushTypes.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 freehand drawing\n// ---------------------------------------------------------------------------\n\n/** Draw surface of the freehand draw controller (`createCanvasDrawController` satisfies it). */\nexport interface DrawCommandTarget {\n\tdrawStroke(input: {\n\t\tpoints: readonly (readonly [number, number])[];\n\t\ttool?: 'pen' | 'highlighter';\n\t\tstyle?: { color?: string; width?: number; opacity?: number; brush?: CanvasBrush };\n\t\tpressure?: readonly number[];\n\t\ttiltX?: readonly number[];\n\t\ttiltY?: readonly number[];\n\t\tstreamline?: boolean;\n\t}): Promise<{ id: string; bounds: { x: number; y: number; width: number; height: number }; brush?: unknown }>;\n\t/** The dry paint presets a stroke can be brushed with (loads the paint engine). */\n\tlistBrushes(): Promise<CanvasBrushPreset[]>;\n}\n\nexport interface DrawCommandOptions {\n\t/** Id prefix (default `canvas.`). */\n\tprefix?: string;\n\tgroup?: string;\n\t/** Scope of the commands (default `canvas`). Pass `null` for global. */\n\tscope?: string | null;\n\t/** Refuse drawing with this reason (e.g. a read-only canvas); `canvas.listBrushes` still runs. */\n\treadOnlyReason?: () => string | null | undefined;\n}\n\nconst PROFILE_PARAM = (what: string, lo: number, hi: number) =>\n\t({\n\t\ttype: 'array',\n\t\tminItems: 1,\n\t\tmaxItems: 256,\n\t\titems: { type: 'number', minimum: lo, maximum: hi },\n\t\tdescription: `${what} spread evenly along the stroke's length: the first value at the start, the last at the end, linearly in between; one value is constant. Only with a brush.`\n\t}) as const;\n\nconst BRUSH_SETTINGS_PARAM = {\n\ttype: 'object',\n\tadditionalProperties: false,\n\tdescription: 'Tip settings instead of a preset.',\n\tproperties: {\n\t\tsize: { type: 'number', minimum: 1, maximum: 2500, description: 'Brush diameter in canvas units (default: the stroke width).' },\n\t\thardness: { type: 'number', minimum: 0, maximum: 1, description: 'Edge hardness, 0 soft to 1 hard (default 1).' },\n\t\tspacing: { type: 'number', minimum: 0.01, maximum: 10, description: 'Dab spacing as a fraction of the diameter (default 0.1).' },\n\t\tangle: { type: 'number', minimum: -360, maximum: 360, description: 'Tip angle in degrees (default 0).' },\n\t\troundness: { type: 'number', minimum: 0.01, maximum: 1, description: 'Tip roundness, 1 round to 0.01 flat (default 1).' },\n\t\topacity: { type: 'number', minimum: 0, maximum: 1, description: 'Opacity ceiling of the stroke 0..1 (default 1).' },\n\t\tflow: { type: 'number', minimum: 0, maximum: 1, description: 'Build-up per dab 0..1 (default 1).' },\n\t\tpressureSize: { type: 'boolean', description: 'Pressure scales the size (default true).' },\n\t\tpressureOpacity: { type: 'boolean', description: 'Pressure scales the opacity (default false).' }\n\t}\n} as const;\n\n/**\n * Agent / palette commands for freehand drawing: `canvas.drawFreehand` (a pen or highlighter\n * stroke through given points, optionally brushed with a dry paint preset and a pressure / tilt\n * profile; one undo step) and the read-only `canvas.listBrushes` (the dry presets it accepts).\n */\nexport function createDrawCommands(target: DrawCommandTarget, options: DrawCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'canvas.';\n\tconst group = options.group ?? 'Draw';\n\tconst scope = options.scope === null ? undefined : options.scope ?? 'canvas';\n\tconst base = { group, ...(scope ? { scope } : {}) };\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}drawFreehand`,\n\t\t\tlabel: 'Draw Freehand Stroke',\n\t\t\tkeywords: ['pen', 'highlighter', 'brush', 'sketch', 'draw', 'stroke', 'pencil', 'ink'],\n\t\t\tdescription:\n\t\t\t\t'Draws a freehand pen or highlighter stroke through points (canvas coordinates) as one path shape node, in one undo step. With `brush` it is painted with a dry paint brush (a preset id from canvas.listBrushes, or tip settings) and `pressure` / `tiltX` / `tiltY` profiles shape it along its length; wet brushes are refused. Returns the new node `id`, its `bounds` and the stored `brush`.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tadditionalProperties: false,\n\t\t\t\trequired: ['points'],\n\t\t\t\tproperties: {\n\t\t\t\t\tpoints: {\n\t\t\t\t\t\ttype: 'array',\n\t\t\t\t\t\tminItems: 1,\n\t\t\t\t\t\tmaxItems: 5000,\n\t\t\t\t\t\titems: { type: 'array', minItems: 2, maxItems: 2, items: { type: 'number' } },\n\t\t\t\t\t\tdescription: 'Stroke points as [x, y] pairs in canvas (flow) units, in drawing order. Use a point every few units along curves.'\n\t\t\t\t\t},\n\t\t\t\t\ttool: { type: 'string', enum: ['pen', 'highlighter'], description: 'Pen (default: blue, width 3) or highlighter (yellow, width 24, opacity 0.35); sets the defaults below.' },\n\t\t\t\t\tcolor: { type: 'string', description: 'Stroke colour, any CSS colour (default from the tool).' },\n\t\t\t\t\twidth: { type: 'number', exclusiveMinimum: 0, maximum: 2500, description: 'Stroke width in canvas units; the brush size for brushed strokes (default from the tool).' },\n\t\t\t\t\topacity: { type: 'number', minimum: 0, maximum: 1, description: 'Stroke opacity 0..1 (default from the tool).' },\n\t\t\t\t\tbrush: {\n\t\t\t\t\t\tdescription: 'Paint the stroke with a dry paint brush: a preset id such as \"ink-pen\", \"pencil-hb\", \"brush-pen\", \"charcoal-stick\", \"soft-pastel\", \"marker\" or \"airbrush\" (all ids: canvas.listBrushes), or tip settings. Omit for a plain vector stroke.',\n\t\t\t\t\t\toneOf: [{ type: 'string', minLength: 1 }, BRUSH_SETTINGS_PARAM]\n\t\t\t\t\t},\n\t\t\t\t\tpressure: PROFILE_PARAM('Pen pressure 0..1', 0, 1),\n\t\t\t\t\ttiltX: PROFILE_PARAM('Pen tilt along x in degrees (−90..90)', -90, 90),\n\t\t\t\t\ttiltY: PROFILE_PARAM('Pen tilt along y in degrees (−90..90)', -90, 90),\n\t\t\t\t\tstreamline: { type: 'boolean', description: 'Smooth jittery points before fitting the path (default false).' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: () => options.readOnlyReason?.() || true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: {\n\t\t\t\t\tpoints: [number, number][];\n\t\t\t\t\ttool?: 'pen' | 'highlighter';\n\t\t\t\t\tcolor?: string;\n\t\t\t\t\twidth?: number;\n\t\t\t\t\topacity?: number;\n\t\t\t\t\tbrush?: CanvasBrush;\n\t\t\t\t\tpressure?: number[];\n\t\t\t\t\ttiltX?: number[];\n\t\t\t\t\ttiltY?: number[];\n\t\t\t\t\tstreamline?: boolean;\n\t\t\t\t}\n\t\t\t) =>\n\t\t\t\ttarget.drawStroke({\n\t\t\t\t\tpoints: params.points,\n\t\t\t\t\t...(params.tool ? { tool: params.tool } : {}),\n\t\t\t\t\tstyle: {\n\t\t\t\t\t\t...(params.color !== undefined ? { color: params.color } : {}),\n\t\t\t\t\t\t...(params.width !== undefined ? { width: params.width } : {}),\n\t\t\t\t\t\t...(params.opacity !== undefined ? { opacity: params.opacity } : {}),\n\t\t\t\t\t\t...(params.brush !== undefined ? { brush: params.brush } : {})\n\t\t\t\t\t},\n\t\t\t\t\t...(params.pressure ? { pressure: params.pressure } : {}),\n\t\t\t\t\t...(params.tiltX ? { tiltX: params.tiltX } : {}),\n\t\t\t\t\t...(params.tiltY ? { tiltY: params.tiltY } : {}),\n\t\t\t\t\t...(params.streamline ? { streamline: true } : {})\n\t\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}listBrushes`,\n\t\t\tlabel: 'List Freehand Brushes',\n\t\t\tkeywords: ['brushes', 'presets', 'paint', 'pencil', 'ink'],\n\t\t\tdescription: 'Read-only: the dry paint presets canvas.drawFreehand accepts as `brush`, as { id, name, category, size } (size is the preset\\'s own diameter; the stroke width replaces it).',\n\t\t\tparams: { type: 'object', additionalProperties: false, properties: {} },\n\t\t\treadOnly: true,\n\t\t\trun: async () => ({ brushes: await target.listBrushes() })\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/** Turns a controller's `false` (nothing changed) into a failure the palette and agents see. */\nfunction orFail(changed: boolean, message: string): true {\n\tif (!changed) throw new Error(message);\n\treturn true;\n}\n\n/**\n * Palette / agent commands for common spreadsheet table actions (no default shortcuts).\n * Merge, unmerge and transpose act on the user's selection; agents should use the\n * `merge_cells` / `unmerge_cells` / `transpose_range` tools, which take a range.\n */\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{\n\t\t\t...base,\n\t\t\tid: `${prefix}mergeCells`,\n\t\t\tlabel: 'Merge Cells',\n\t\t\tkeywords: ['combine'],\n\t\t\tenabled: hasRange,\n\t\t\trun: () =>\n\t\t\t\torFail(controller.mergeCells(), 'Cannot merge the selection: it is a single cell, or it partly overlaps a merge or a spill range.')\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}unmergeCells`,\n\t\t\tlabel: 'Unmerge Cells',\n\t\t\tkeywords: ['split'],\n\t\t\tenabled: hasRange,\n\t\t\trun: () => orFail(controller.unmergeCells(), 'There are no merged cells in the selection.')\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transposeRange`,\n\t\t\tlabel: 'Transpose Range',\n\t\t\tkeywords: ['rotate', 'swap rows columns'],\n\t\t\tenabled: hasRange,\n\t\t\trun: () =>\n\t\t\t\torFail(controller.transposeRange(), 'Cannot transpose the selection: it is a single cell, or a merge or a spill range is in the way.')\n\t\t}\n\t];\n}\n"],"mappings":";;;;;;AAqBO,IAAM,4BAAwD;AAAA,EACpE,EAAE,SAAS,QAAQ,OAAO,QAAQ;AAAA,EAClC,EAAE,SAAS,QAAQ,OAAO,cAAc;AAAA,EACxC,EAAE,SAAS,QAAQ,OAAO,SAAS,WAAW,CAAC,WAAW,OAAO,EAAE;AACpE;AAUO,SAAS,sBAAsB,SAA+B,UAAiC,CAAC,GAAkB;AACxH,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,cAAc,CAAC,YACpB,0BAA0B,OAAO,CAAC,MAAM,EAAE,YAAY,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,IAAI,GAAG,KAAK,MAAM,IAAI;AACtG,SAAO;AAAA,IACN;AAAA,MACC,IAAI,GAAG,MAAM;AAAA,MACb,OAAO;AAAA,MACP;AAAA,MACA,UAAU,CAAC,UAAU,MAAM;AAAA,MAC3B,aAAa;AAAA,MACb,UAAU,YAAY,MAAM;AAAA,MAC5B,GAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;AAAA,MAChD,SAAS,MAAO,QAAQ,SAAS,EAAE,UAAU,OAAO;AAAA,MACpD,KAAK,MAAM;AACV,gBAAQ,KAAK;AACb,eAAO,EAAE,QAAQ,MAAM,OAAO,QAAQ,SAAS,EAAE;AAAA,MAClD;AAAA,IACD;AAAA,IACA;AAAA,MACC,IAAI,GAAG,MAAM;AAAA,MACb,OAAO;AAAA,MACP;AAAA,MACA,UAAU,CAAC,UAAU,SAAS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AC","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-7LQO6OHH.cjs","sourcesContent":[null,"/**\n * Brushed freehand strokes: a path shape with a `brush` keeps its path (selection, editing, eraser\n * hit-testing, grouping and export work as for any path) and is drawn with the paint engine's\n * dry brushstroke renderer instead of an SVG stroke. The renderer, the paint presets and the colour\n * parser live in a separate chunk, loaded the first time a brushed stroke is drawn, so canvases\n * without brushes never load the paint engine.\n */\nimport { brushstrokeScaleBucket } from '../paint/brushstroke-scale.js';\nimport { parseSvgPath, type PathShape, type ShapeDescription, type ShapeSize } from './shapeGeometry.js';\nimport type { Point } from './types.js';\nimport type { CanvasBrush, CanvasBrushPreset, CanvasBrushstroke } from './brushTypes.js';\n\nexport type { CanvasBrush, CanvasBrushPreset, CanvasBrushSettings, CanvasBrushstroke } from './brushTypes.js';\n\nexport { brushstrokeScaleBucket };\n\n/** A brushed stroke's image, placed in the path's coordinates (the shape's view box). */\nexport interface CanvasBrushstrokeImage {\n\t/** PNG data URL. */\n\thref: string;\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\t/** Image pixels per path unit. */\n\tscale: number;\n}\n\n/** A path shape with a brush. */\nexport type BrushedPathShape = PathShape & { brush: CanvasBrushstroke };\n\n/** Whether a shape is a brushed stroke. */\nexport function isBrushedShape(shape: ShapeDescription | null | undefined): shape is BrushedPathShape {\n\treturn !!shape && shape.kind === 'path' && !!shape.brush && typeof shape.brush === 'object' && shape.brush.brush != null;\n}\n\n/**\n * The open polyline of a path's first subpath, in path coordinates: lines kept, curves sampled\n * every `step` units or so. Brushed strokes are drawn along it.\n */\nexport function pathDataToPolyline(d: string, step = 2): Point[] {\n\tconst out: Point[] = [];\n\tlet x = 0;\n\tlet y = 0;\n\tlet started = false;\n\tconst push = (px: number, py: number) => {\n\t\tconst last = out[out.length - 1];\n\t\tif (!last || last[0] !== px || last[1] !== py) out.push([px, py]);\n\t};\n\tfor (const c of parseSvgPath(d)) {\n\t\tif (c.type === 'M') {\n\t\t\tif (started) break;\n\t\t\tstarted = true;\n\t\t\tx = c.x;\n\t\t\ty = c.y;\n\t\t\tpush(x, y);\n\t\t} else if (c.type === 'Z') {\n\t\t\tif (out.length) push(out[0][0], out[0][1]);\n\t\t\tbreak;\n\t\t} else if (c.type === 'C' || c.type === 'Q') {\n\t\t\tconst pts = c.type === 'C' ? [[x, y], [c.x1, c.y1], [c.x2, c.y2], [c.x, c.y]] : [[x, y], [c.x1, c.y1], [c.x, c.y]];\n\t\t\tlet hull = 0;\n\t\t\tfor (let i = 1; i < pts.length; i++) hull += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);\n\t\t\tconst n = Math.max(1, Math.min(256, Math.ceil(hull / Math.max(0.25, step))));\n\t\t\tfor (let k = 1; k <= n; k++) {\n\t\t\t\tconst t = k / n;\n\t\t\t\tconst u = 1 - t;\n\t\t\t\tif (c.type === 'C') {\n\t\t\t\t\tpush(\n\t\t\t\t\t\tu * u * u * x + 3 * u * u * t * c.x1 + 3 * u * t * t * c.x2 + t * t * t * c.x,\n\t\t\t\t\t\tu * u * u * y + 3 * u * u * t * c.y1 + 3 * u * t * t * c.y2 + t * t * t * c.y\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tpush(u * u * x + 2 * u * t * c.x1 + t * t * c.x, u * u * y + 2 * u * t * c.y1 + t * t * c.y);\n\t\t\t\t}\n\t\t\t}\n\t\t\tx = c.x;\n\t\t\ty = c.y;\n\t\t} else {\n\t\t\t// Lines, and arcs as their chords (freehand paths have none).\n\t\t\tx = c.x;\n\t\t\ty = c.y;\n\t\t\tpush(x, y);\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Resamples per-point values into `count` values spread evenly along the polyline's length (the\n * profile a brushed stroke stores). Values are rounded to three decimals.\n */\nexport function profileAlongPolyline(points: readonly Point[], values: readonly number[], count = 32): number[] {\n\tconst n = Math.min(points.length, values.length);\n\tif (n === 0) return [];\n\tif (n === 1) return [round3(values[0])];\n\tconst lengths = [0];\n\tfor (let i = 1; i < n; i++) lengths.push(lengths[i - 1] + Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]));\n\tconst total = lengths[n - 1];\n\tconst m = Math.max(2, Math.min(count, n));\n\tconst out: number[] = [];\n\tlet j = 0;\n\tfor (let k = 0; k < m; k++) {\n\t\tconst at = total > 0 ? (total * k) / (m - 1) : 0;\n\t\twhile (j < n - 2 && lengths[j + 1] < at) j++;\n\t\tconst span = lengths[j + 1] - lengths[j];\n\t\tconst f = span > 0 ? Math.min(1, Math.max(0, (at - lengths[j]) / span)) : 0;\n\t\tout.push(round3(values[j] + (values[j + 1] - values[j]) * f));\n\t}\n\treturn out;\n}\n\nconst round3 = (v: number) => Math.round(v * 1000) / 1000;\n\n// ---------------------------------------------------------------------------\n// The lazily loaded renderer\n// ---------------------------------------------------------------------------\n\n/** The renderer chunk (`./brushstrokeRender.ts`). */\nexport interface CanvasBrushstrokeRenderer {\n\tlistCanvasBrushes(): CanvasBrushPreset[];\n\t/** Throws for an unknown or non-dry brush; the result is the paint engine's brush. */\n\tresolveCanvasBrush(brush: CanvasBrush, width: number): unknown;\n\trenderShapeBrushstrokeNow(shape: BrushedPathShape, scale: number): CanvasBrushstrokeImage | null;\n\tbrushedShapeSvgNow(shape: BrushedPathShape, size: ShapeSize, scale: number): string;\n}\n\nlet loading: Promise<CanvasBrushstrokeRenderer> | null = null;\n\n/**\n * Loads the brushstroke renderer (the paint engine's dry brushes, the paint presets and a CSS\n * colour parser). Called for you by the functions below; call it early to warm up.\n */\nexport function loadCanvasBrushstrokeRenderer(): Promise<CanvasBrushstrokeRenderer> {\n\tloading ??= (import('./brushstrokeRender.js') as Promise<CanvasBrushstrokeRenderer>).catch((error) => {\n\t\tloading = null;\n\t\tthrow error;\n\t});\n\treturn loading;\n}\n\n/** The dry paint presets a freehand stroke can use (wet, mixer, blender, smudge and eraser presets are left out). */\nexport async function listCanvasBrushes(): Promise<CanvasBrushPreset[]> {\n\treturn (await loadCanvasBrushstrokeRenderer()).listCanvasBrushes();\n}\n\n/**\n * Checks a brush: an unknown preset id, a wet (or other non-dry) preset, or settings that are not\n * an object throw an error saying which presets can be used.\n */\nexport async function validateCanvasBrush(brush: CanvasBrush): Promise<void> {\n\t(await loadCanvasBrushstrokeRenderer()).resolveCanvasBrush(brush, 1);\n}\n\nexport interface RenderShapeBrushstrokeOptions {\n\t/** Image pixels per path unit; pass `brushstrokeScaleBucket(zoom × node scale, devicePixelRatio)` (default 1). */\n\tscale?: number;\n}\n\n/**\n * Renders a brushed path shape to a cached PNG placed in path coordinates, or null for a shape\n * without a brush or an empty path. Throws for an unknown or non-dry brush.\n */\nexport async function renderShapeBrushstroke(shape: ShapeDescription, options: RenderShapeBrushstrokeOptions = {}): Promise<CanvasBrushstrokeImage | null> {\n\tif (!isBrushedShape(shape)) return null;\n\treturn (await loadCanvasBrushstrokeRenderer()).renderShapeBrushstrokeNow(shape, options.scale ?? 1);\n}\n\n/**\n * The brushed stroke as a standalone SVG document of `size` (the node box), with the image\n * embedded as a PNG data URL: what an SVG export writes for the node. Shapes without a brush give\n * null (export them as paths).\n */\nexport async function getBrushedShapeSvg(shape: ShapeDescription, size: ShapeSize, options: RenderShapeBrushstrokeOptions = {}): Promise<string | null> {\n\tif (!isBrushedShape(shape)) return null;\n\treturn (await loadCanvasBrushstrokeRenderer()).brushedShapeSvgNow(shape, size, options.scale ?? 2);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-AKU2KQ47.cjs","../src/commands/builtins.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACgBO,IAAM,0BAAA,EAAwD;AAAA,EACpE,EAAE,OAAA,EAAS,MAAA,EAAQ,KAAA,EAAO,QAAQ,CAAA;AAAA,EAClC,EAAE,OAAA,EAAS,MAAA,EAAQ,KAAA,EAAO,cAAc,CAAA;AAAA,EACxC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;AACA,IAAA;AACI,MAAA;AACC,MAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACK,MAAA;AACN,IAAA;AACI,IAAA;AACL,EAAA;AACD;AA0BS;AACH,EAAA;AACE,EAAA;AACR;AAOgB;AAIT,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACD,IAAA;AACL,IAAA;AACI,MAAA;AACC,MAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACK,MAAA;AACN,IAAA;AACK,IAAA;AACL,IAAA;AACI,MAAA;AACC,MAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACK,MAAA;AAEN,IAAA;AACA,IAAA;AACI,MAAA;AACC,MAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACK,MAAA;AACN,IAAA;AACA,IAAA;AACI,MAAA;AACC,MAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACK,MAAA;AAEN,IAAA;AACD,EAAA;AACD;AD1TW;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-AKU2KQ47.cjs","sourcesContent":[null,"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 { CanvasBrush, CanvasBrushPreset } from '../canvas/brushTypes.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 freehand drawing\n// ---------------------------------------------------------------------------\n\n/** Draw surface of the freehand draw controller (`createCanvasDrawController` satisfies it). */\nexport interface DrawCommandTarget {\n\tdrawStroke(input: {\n\t\tpoints: readonly (readonly [number, number])[];\n\t\ttool?: 'pen' | 'highlighter';\n\t\tstyle?: { color?: string; width?: number; opacity?: number; brush?: CanvasBrush };\n\t\tpressure?: readonly number[];\n\t\ttiltX?: readonly number[];\n\t\ttiltY?: readonly number[];\n\t\tstreamline?: boolean;\n\t}): Promise<{ id: string; bounds: { x: number; y: number; width: number; height: number }; brush?: unknown }>;\n\t/** The dry paint presets a stroke can be brushed with (loads the paint engine). */\n\tlistBrushes(): Promise<CanvasBrushPreset[]>;\n}\n\nexport interface DrawCommandOptions {\n\t/** Id prefix (default `canvas.`). */\n\tprefix?: string;\n\tgroup?: string;\n\t/** Scope of the commands (default `canvas`). Pass `null` for global. */\n\tscope?: string | null;\n\t/** Refuse drawing with this reason (e.g. a read-only canvas); `canvas.listBrushes` still runs. */\n\treadOnlyReason?: () => string | null | undefined;\n}\n\nconst PROFILE_PARAM = (what: string, lo: number, hi: number) =>\n\t({\n\t\ttype: 'array',\n\t\tminItems: 1,\n\t\tmaxItems: 256,\n\t\titems: { type: 'number', minimum: lo, maximum: hi },\n\t\tdescription: `${what} spread evenly along the stroke's length: the first value at the start, the last at the end, linearly in between; one value is constant. Only with a brush.`\n\t}) as const;\n\nconst BRUSH_SETTINGS_PARAM = {\n\ttype: 'object',\n\tadditionalProperties: false,\n\tdescription: 'Tip settings instead of a preset.',\n\tproperties: {\n\t\tsize: { type: 'number', minimum: 1, maximum: 2500, description: 'Brush diameter in canvas units (default: the stroke width).' },\n\t\thardness: { type: 'number', minimum: 0, maximum: 1, description: 'Edge hardness, 0 soft to 1 hard (default 1).' },\n\t\tspacing: { type: 'number', minimum: 0.01, maximum: 10, description: 'Dab spacing as a fraction of the diameter (default 0.1).' },\n\t\tangle: { type: 'number', minimum: -360, maximum: 360, description: 'Tip angle in degrees (default 0).' },\n\t\troundness: { type: 'number', minimum: 0.01, maximum: 1, description: 'Tip roundness, 1 round to 0.01 flat (default 1).' },\n\t\topacity: { type: 'number', minimum: 0, maximum: 1, description: 'Opacity ceiling of the stroke 0..1 (default 1).' },\n\t\tflow: { type: 'number', minimum: 0, maximum: 1, description: 'Build-up per dab 0..1 (default 1).' },\n\t\tpressureSize: { type: 'boolean', description: 'Pressure scales the size (default true).' },\n\t\tpressureOpacity: { type: 'boolean', description: 'Pressure scales the opacity (default false).' }\n\t}\n} as const;\n\n/**\n * Agent / palette commands for freehand drawing: `canvas.drawFreehand` (a pen or highlighter\n * stroke through given points, optionally brushed with a dry paint preset and a pressure / tilt\n * profile; one undo step) and the read-only `canvas.listBrushes` (the dry presets it accepts).\n */\nexport function createDrawCommands(target: DrawCommandTarget, options: DrawCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'canvas.';\n\tconst group = options.group ?? 'Draw';\n\tconst scope = options.scope === null ? undefined : options.scope ?? 'canvas';\n\tconst base = { group, ...(scope ? { scope } : {}) };\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}drawFreehand`,\n\t\t\tlabel: 'Draw Freehand Stroke',\n\t\t\tkeywords: ['pen', 'highlighter', 'brush', 'sketch', 'draw', 'stroke', 'pencil', 'ink'],\n\t\t\tdescription:\n\t\t\t\t'Draws a freehand pen or highlighter stroke through points (canvas coordinates) as one path shape node, in one undo step. With `brush` it is painted with a dry paint brush (a preset id from canvas.listBrushes, or tip settings) and `pressure` / `tiltX` / `tiltY` profiles shape it along its length; wet brushes are refused. Returns the new node `id`, its `bounds` and the stored `brush`.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tadditionalProperties: false,\n\t\t\t\trequired: ['points'],\n\t\t\t\tproperties: {\n\t\t\t\t\tpoints: {\n\t\t\t\t\t\ttype: 'array',\n\t\t\t\t\t\tminItems: 1,\n\t\t\t\t\t\tmaxItems: 5000,\n\t\t\t\t\t\titems: { type: 'array', minItems: 2, maxItems: 2, items: { type: 'number' } },\n\t\t\t\t\t\tdescription: 'Stroke points as [x, y] pairs in canvas (flow) units, in drawing order. Use a point every few units along curves.'\n\t\t\t\t\t},\n\t\t\t\t\ttool: { type: 'string', enum: ['pen', 'highlighter'], description: 'Pen (default: blue, width 3) or highlighter (yellow, width 24, opacity 0.35); sets the defaults below.' },\n\t\t\t\t\tcolor: { type: 'string', description: 'Stroke colour, any CSS colour (default from the tool).' },\n\t\t\t\t\twidth: { type: 'number', exclusiveMinimum: 0, maximum: 2500, description: 'Stroke width in canvas units; the brush size for brushed strokes (default from the tool).' },\n\t\t\t\t\topacity: { type: 'number', minimum: 0, maximum: 1, description: 'Stroke opacity 0..1 (default from the tool).' },\n\t\t\t\t\tbrush: {\n\t\t\t\t\t\tdescription: 'Paint the stroke with a dry paint brush: a preset id such as \"ink-pen\", \"pencil-hb\", \"brush-pen\", \"charcoal-stick\", \"soft-pastel\", \"marker\" or \"airbrush\" (all ids: canvas.listBrushes), or tip settings. Omit for a plain vector stroke.',\n\t\t\t\t\t\toneOf: [{ type: 'string', minLength: 1 }, BRUSH_SETTINGS_PARAM]\n\t\t\t\t\t},\n\t\t\t\t\tpressure: PROFILE_PARAM('Pen pressure 0..1', 0, 1),\n\t\t\t\t\ttiltX: PROFILE_PARAM('Pen tilt along x in degrees (−90..90)', -90, 90),\n\t\t\t\t\ttiltY: PROFILE_PARAM('Pen tilt along y in degrees (−90..90)', -90, 90),\n\t\t\t\t\tstreamline: { type: 'boolean', description: 'Smooth jittery points before fitting the path (default false).' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: () => options.readOnlyReason?.() || true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: {\n\t\t\t\t\tpoints: [number, number][];\n\t\t\t\t\ttool?: 'pen' | 'highlighter';\n\t\t\t\t\tcolor?: string;\n\t\t\t\t\twidth?: number;\n\t\t\t\t\topacity?: number;\n\t\t\t\t\tbrush?: CanvasBrush;\n\t\t\t\t\tpressure?: number[];\n\t\t\t\t\ttiltX?: number[];\n\t\t\t\t\ttiltY?: number[];\n\t\t\t\t\tstreamline?: boolean;\n\t\t\t\t}\n\t\t\t) =>\n\t\t\t\ttarget.drawStroke({\n\t\t\t\t\tpoints: params.points,\n\t\t\t\t\t...(params.tool ? { tool: params.tool } : {}),\n\t\t\t\t\tstyle: {\n\t\t\t\t\t\t...(params.color !== undefined ? { color: params.color } : {}),\n\t\t\t\t\t\t...(params.width !== undefined ? { width: params.width } : {}),\n\t\t\t\t\t\t...(params.opacity !== undefined ? { opacity: params.opacity } : {}),\n\t\t\t\t\t\t...(params.brush !== undefined ? { brush: params.brush } : {})\n\t\t\t\t\t},\n\t\t\t\t\t...(params.pressure ? { pressure: params.pressure } : {}),\n\t\t\t\t\t...(params.tiltX ? { tiltX: params.tiltX } : {}),\n\t\t\t\t\t...(params.tiltY ? { tiltY: params.tiltY } : {}),\n\t\t\t\t\t...(params.streamline ? { streamline: true } : {})\n\t\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}listBrushes`,\n\t\t\tlabel: 'List Freehand Brushes',\n\t\t\tkeywords: ['brushes', 'presets', 'paint', 'pencil', 'ink'],\n\t\t\tdescription: 'Read-only: the dry paint presets canvas.drawFreehand accepts as `brush`, as { id, name, category, size } (size is the preset\\'s own diameter; the stroke width replaces it).',\n\t\t\tparams: { type: 'object', additionalProperties: false, properties: {} },\n\t\t\treadOnly: true,\n\t\t\trun: async () => ({ brushes: await target.listBrushes() })\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/** Turns a controller's `false` (nothing changed) into a failure the palette and agents see. */\nfunction orFail(changed: boolean, message: string): true {\n\tif (!changed) throw new Error(message);\n\treturn true;\n}\n\n/**\n * Palette / agent commands for common spreadsheet table actions (no default shortcuts).\n * Merge, unmerge and transpose act on the user's selection; agents should use the\n * `merge_cells` / `unmerge_cells` / `transpose_range` tools, which take a range.\n */\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{\n\t\t\t...base,\n\t\t\tid: `${prefix}mergeCells`,\n\t\t\tlabel: 'Merge Cells',\n\t\t\tkeywords: ['combine'],\n\t\t\tenabled: hasRange,\n\t\t\trun: () =>\n\t\t\t\torFail(controller.mergeCells(), 'Cannot merge the selection: it is a single cell, or it partly overlaps a merge or a spill range.')\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}unmergeCells`,\n\t\t\tlabel: 'Unmerge Cells',\n\t\t\tkeywords: ['split'],\n\t\t\tenabled: hasRange,\n\t\t\trun: () => orFail(controller.unmergeCells(), 'There are no merged cells in the selection.')\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transposeRange`,\n\t\t\tlabel: 'Transpose Range',\n\t\t\tkeywords: ['rotate', 'swap rows columns'],\n\t\t\tenabled: hasRange,\n\t\t\trun: () =>\n\t\t\t\torFail(controller.transposeRange(), 'Cannot transpose the selection: it is a single cell, or a merge or a spill range is in the way.')\n\t\t}\n\t];\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/canvas/gradient.ts","../src/canvas/curveFit.ts","../src/canvas/shapeGeometry.ts"],"sourcesContent":["/**\n * Canvas gradient models, parsing, presets, and SVG defs generation.\n * Supports linear and radial gradients for shape fills, strokes, and freehand drawing.\n */\n\nexport interface GradientStop {\n\toffset: number; // 0 to 1\n\tcolor: string;\n\topacity?: number;\n}\n\nexport interface CanvasLinearGradient {\n\ttype: 'linear';\n\tangle?: number; // degrees clockwise, default 90 (top-to-bottom) or custom\n\tstops: GradientStop[];\n}\n\nexport interface CanvasRadialGradient {\n\ttype: 'radial';\n\tcx?: number; // 0 to 1 (default 0.5)\n\tcy?: number; // 0 to 1 (default 0.5)\n\tr?: number; // 0 to 1 (default 0.5)\n\tstops: GradientStop[];\n}\n\nexport type CanvasGradientDef = CanvasLinearGradient | CanvasRadialGradient;\n\nexport interface SvgGradientStop {\n\toffset: string;\n\tstopColor: string;\n\tstopOpacity?: number;\n}\n\nexport interface SvgGradientDef {\n\tid: string;\n\ttype: 'linear' | 'radial';\n\tattrs: Record<string, string | number>;\n\tstops: SvgGradientStop[];\n}\n\nexport const PIXERATE_BRAND_GRADIENT: CanvasLinearGradient = {\n\ttype: 'linear',\n\tangle: 135,\n\tstops: [\n\t\t{ offset: 0, color: '#8E51FF' },\n\t\t{ offset: 1, color: '#e12afb' }\n\t]\n};\n\nexport const CANVAS_GRADIENT_PRESETS: Record<string, CanvasLinearGradient> = {\n\tpixerate: PIXERATE_BRAND_GRADIENT,\n\tsunset: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#f97316' },\n\t\t\t{ offset: 1, color: '#ec4899' }\n\t\t]\n\t},\n\tocean: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#06b6d4' },\n\t\t\t{ offset: 1, color: '#3b82f6' }\n\t\t]\n\t},\n\taurora: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#10b981' },\n\t\t\t{ offset: 1, color: '#6366f1' }\n\t\t]\n\t},\n\tneon: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#a855f7' },\n\t\t\t{ offset: 1, color: '#ec4899' }\n\t\t]\n\t},\n\tamber: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#f59e0b' },\n\t\t\t{ offset: 1, color: '#ef4444' }\n\t\t]\n\t},\n\tcosmic: {\n\t\ttype: 'linear',\n\t\tangle: 90,\n\t\tstops: [\n\t\t\t{ offset: 0, color: '#3b82f6' },\n\t\t\t{ offset: 0.5, color: '#8b5cf6' },\n\t\t\t{ offset: 1, color: '#ec4899' }\n\t\t]\n\t}\n};\n\n/** Whether an arbitrary value matches a CanvasGradientDef object. */\nexport function isCanvasGradient(value: unknown): value is CanvasGradientDef {\n\tif (!value || typeof value !== 'object') return false;\n\tconst val = value as Partial<CanvasGradientDef>;\n\tif (val.type !== 'linear' && val.type !== 'radial') return false;\n\tif (!Array.isArray(val.stops)) return false;\n\treturn true;\n}\n\n/**\n * Splits CSS function arguments respecting nested parentheses.\n * e.g. \"rgba(255, 0, 0, 0.5) 0%, #00f 100%\" -> [\"rgba(255, 0, 0, 0.5) 0%\", \"#00f 100%\"]\n */\nfunction splitCssArgs(str: string): string[] {\n\tconst parts: string[] = [];\n\tlet depth = 0;\n\tlet current = '';\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst char = str[i];\n\t\tif (char === '(') depth++;\n\t\telse if (char === ')') depth = Math.max(0, depth - 1);\n\t\tif (char === ',' && depth === 0) {\n\t\t\tif (current.trim()) parts.push(current.trim());\n\t\t\tcurrent = '';\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\tif (current.trim()) parts.push(current.trim());\n\treturn parts;\n}\n\n/** Parses CSS angle strings like \"90deg\", \"0.25turn\", \"1.57rad\" or named directions like \"to bottom\" */\nfunction parseCssAngle(val: string): number {\n\tconst trimmed = val.trim().toLowerCase();\n\tif (trimmed.endsWith('deg')) {\n\t\treturn parseFloat(trimmed);\n\t}\n\tif (trimmed.endsWith('turn')) {\n\t\treturn parseFloat(trimmed) * 360;\n\t}\n\tif (trimmed.endsWith('rad')) {\n\t\treturn (parseFloat(trimmed) * 180) / Math.PI;\n\t}\n\tif (trimmed.startsWith('to ')) {\n\t\tconst dir = trimmed.slice(3).trim();\n\t\tif (dir === 'bottom') return 180;\n\t\tif (dir === 'top') return 0;\n\t\tif (dir === 'right') return 90;\n\t\tif (dir === 'left') return 270;\n\t\tif (dir === 'bottom right' || dir === 'right bottom') return 135;\n\t\tif (dir === 'bottom left' || dir === 'left bottom') return 225;\n\t\tif (dir === 'top right' || dir === 'right top') return 45;\n\t\tif (dir === 'top left' || dir === 'left top') return 315;\n\t}\n\tconst n = parseFloat(trimmed);\n\treturn Number.isFinite(n) ? n : 180;\n}\n\n/**\n * Parses CSS linear-gradient or radial-gradient strings into CanvasGradientDef.\n * Supports forms like:\n * - linear-gradient(90deg, #ff0000 0%, #0000ff 100%)\n * - linear-gradient(to right, red, blue)\n * - radial-gradient(circle, red 0%, blue 100%)\n */\nexport function parseCssGradient(css: string): CanvasGradientDef | null {\n\tconst trimmed = css.trim();\n\tconst linearMatch = trimmed.match(/^linear-gradient\\s*\\((.*)\\)$/is);\n\tif (linearMatch) {\n\t\tconst rawArgs = splitCssArgs(linearMatch[1]);\n\t\tif (rawArgs.length === 0) return null;\n\t\tlet angle = 180; // default in CSS linear-gradient without direction is to bottom (180deg)\n\t\tlet stopStartIndex = 0;\n\n\t\tconst first = rawArgs[0].trim().toLowerCase();\n\t\tif (first.endsWith('deg') || first.endsWith('turn') || first.endsWith('rad') || first.startsWith('to ')) {\n\t\t\tangle = parseCssAngle(first);\n\t\t\tstopStartIndex = 1;\n\t\t}\n\n\t\tconst stopStrings = rawArgs.slice(stopStartIndex);\n\t\tif (stopStrings.length === 0) return null;\n\t\tconst stops = parseStopStrings(stopStrings);\n\t\tif (stops.length === 0) return null;\n\t\treturn {\n\t\t\ttype: 'linear',\n\t\t\tangle,\n\t\t\tstops\n\t\t};\n\t}\n\n\tconst radialMatch = trimmed.match(/^radial-gradient\\s*\\((.*)\\)$/is);\n\tif (radialMatch) {\n\t\tconst rawArgs = splitCssArgs(radialMatch[1]);\n\t\tif (rawArgs.length === 0) return null;\n\t\tlet stopStartIndex = 0;\n\t\tconst first = rawArgs[0].trim().toLowerCase();\n\t\tif (first.startsWith('circle') || first.startsWith('ellipse') || first.includes('at ')) {\n\t\t\tstopStartIndex = 1;\n\t\t}\n\t\tconst stopStrings = rawArgs.slice(stopStartIndex);\n\t\tif (stopStrings.length === 0) return null;\n\t\tconst stops = parseStopStrings(stopStrings);\n\t\tif (stops.length === 0) return null;\n\t\treturn {\n\t\t\ttype: 'radial',\n\t\t\tcx: 0.5,\n\t\t\tcy: 0.5,\n\t\t\tr: 0.5,\n\t\t\tstops\n\t\t};\n\t}\n\n\treturn null;\n}\n\nfunction parseStopStrings(stopStrings: string[]): GradientStop[] {\n\tconst count = stopStrings.length;\n\treturn stopStrings.map((str, idx) => {\n\t\tconst parts = str.trim().split(/\\s+(?=[0-9%])/);\n\t\tconst color = parts[0];\n\t\tlet offset = count === 1 ? 0 : idx / (count - 1);\n\t\tif (parts.length > 1) {\n\t\t\tconst posStr = parts[1].trim();\n\t\t\tif (posStr.endsWith('%')) {\n\t\t\t\toffset = parseFloat(posStr) / 100;\n\t\t\t} else {\n\t\t\t\tconst val = parseFloat(posStr);\n\t\t\t\tif (Number.isFinite(val)) offset = val;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\toffset: Math.min(1, Math.max(0, offset)),\n\t\t\tcolor\n\t\t};\n\t});\n}\n\n/**\n * Resolves a paint value (which could be a CSS color, preset name, CSS gradient string, or CanvasGradientDef)\n * into either a CanvasGradientDef (if gradient) or null (if solid color or invalid).\n */\nexport function resolveCanvasGradient(value: unknown): CanvasGradientDef | null {\n\tif (!value) return null;\n\tif (isCanvasGradient(value)) return value;\n\tif (typeof value === 'string') {\n\t\tconst lower = value.trim().toLowerCase();\n\t\tif (CANVAS_GRADIENT_PRESETS[lower]) {\n\t\t\treturn CANVAS_GRADIENT_PRESETS[lower];\n\t\t}\n\t\tif (lower.startsWith('linear-gradient') || lower.startsWith('radial-gradient')) {\n\t\t\treturn parseCssGradient(value);\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Converts degrees clockwise (CSS angle: 0 = top, 90 = right, 180 = bottom, 270 = left)\n * to SVG linearGradient vector coordinates (x1, y1, x2, y2) normalized [0, 1].\n */\nexport function angleToSvgLinearCoords(angleDeg: number = 180): { x1: number; y1: number; x2: number; y2: number } {\n\t// Standard CSS angle: 0deg points UP (towards -Y in standard canvas coordinates)\n\t// Convert to standard mathematical angle in radians (0 at +X, counterclockwise)\n\t// CSS 0deg = Math 90deg (up)\n\t// CSS angle A -> Math theta = 90 - A\n\tconst rad = ((90 - angleDeg) * Math.PI) / 180;\n\t// Vector direction\n\tconst dx = Math.cos(rad);\n\tconst dy = -Math.sin(rad); // invert for SVG/screen y-down coords\n\n\t// Project from center (0.5, 0.5) to edges\n\tconst half = 0.5;\n\treturn {\n\t\tx1: Math.round((half - dx * half) * 1000) / 1000,\n\t\ty1: Math.round((half - dy * half) * 1000) / 1000,\n\t\tx2: Math.round((half + dx * half) * 1000) / 1000,\n\t\ty2: Math.round((half + dy * half) * 1000) / 1000\n\t};\n}\n\n/**\n * Converts a CanvasGradientDef to an SvgGradientDef descriptor ready for rendering `<linearGradient>` / `<radialGradient>`.\n */\nexport function gradientToSvgDef(gradient: CanvasGradientDef, id: string): SvgGradientDef {\n\tconst stops: SvgGradientStop[] = (gradient.stops ?? []).map((s) => ({\n\t\toffset: `${Math.round(s.offset * 1000) / 10}%`,\n\t\tstopColor: s.color,\n\t\tstopOpacity: s.opacity\n\t}));\n\n\tif (gradient.type === 'radial') {\n\t\treturn {\n\t\t\tid,\n\t\t\ttype: 'radial',\n\t\t\tattrs: {\n\t\t\t\tcx: gradient.cx !== undefined ? `${gradient.cx * 100}%` : '50%',\n\t\t\t\tcy: gradient.cy !== undefined ? `${gradient.cy * 100}%` : '50%',\n\t\t\t\tr: gradient.r !== undefined ? `${gradient.r * 100}%` : '50%'\n\t\t\t},\n\t\t\tstops\n\t\t};\n\t}\n\n\tconst coords = angleToSvgLinearCoords(gradient.angle ?? 180);\n\treturn {\n\t\tid,\n\t\ttype: 'linear',\n\t\tattrs: {\n\t\t\tx1: `${coords.x1 * 100}%`,\n\t\t\ty1: `${coords.y1 * 100}%`,\n\t\t\tx2: `${coords.x2 * 100}%`,\n\t\t\ty2: `${coords.y2 * 100}%`\n\t\t},\n\t\tstops\n\t};\n}\n","/**\n * Least-squares cubic Bézier fitting of point sequences (Schneider-style: fit one cubic with\n * fixed end tangents, reparameterise with Newton steps, split at the worst point), with\n * corner preservation by a turning-angle test.\n *\n * Portions ported from vectorcraft-main/crates/pathops/src/fit.rs and\n * vectorcraft-main/crates/pathops/src/edit.rs (MIT OR Apache-2.0, © ArtCraft Team and\n * contributors). See THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from './types.js';\n\n/** Same as `formatNumber` in shapeGeometry (kept local to avoid an import cycle). */\nfunction formatNumber(value: number, precision: number): string {\n\tconst factor = 10 ** precision;\n\tconst rounded = Math.round(value * factor) / factor;\n\treturn Object.is(rounded, -0) ? '0' : String(rounded);\n}\n\n/** One cubic Bézier segment. */\nexport interface CubicSegment {\n\tp0: Point;\n\tp1: Point;\n\tp2: Point;\n\tp3: Point;\n}\n\nexport interface FitCubicsOptions {\n\t/**\n\t * Vertices where the polyline turns by more than this many degrees stay sharp corners\n\t * (default 30). Use 180 to smooth through every vertex.\n\t */\n\tcornerAngleDeg?: number;\n\t/** Treat the points as a closed ring (the last point connects back to the first). */\n\tclosed?: boolean;\n}\n\n/** Maximum Newton reparameterisation rounds per fit. */\nconst MAX_REPARAM = 6;\n\ntype Vec = [number, number];\n\nconst sub = (a: Point, b: Point): Vec => [a[0] - b[0], a[1] - b[1]];\nconst add = (a: Point, v: Vec, s = 1): Vec => [a[0] + v[0] * s, a[1] + v[1] * s];\nconst dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1];\nconst dist = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1]);\n\nfunction unit(v: Vec): Vec | null {\n\tconst l = Math.hypot(v[0], v[1]);\n\treturn l > 1e-12 && Number.isFinite(l) ? [v[0] / l, v[1] / l] : null;\n}\n\nfunction evalCubic(c: CubicSegment, t: number): Vec {\n\tconst s = 1 - t;\n\tconst b0 = s * s * s;\n\tconst b1 = 3 * s * s * t;\n\tconst b2 = 3 * s * t * t;\n\tconst b3 = t * t * t;\n\treturn [\n\t\tb0 * c.p0[0] + b1 * c.p1[0] + b2 * c.p2[0] + b3 * c.p3[0],\n\t\tb0 * c.p0[1] + b1 * c.p1[1] + b2 * c.p2[1] + b3 * c.p3[1]\n\t];\n}\n\n/** Evaluates a cubic segment at `t` ∈ [0, 1]. */\nexport function cubicPointAt(c: CubicSegment, t: number): Point {\n\treturn evalCubic(c, t);\n}\n\nfunction dedup(points: readonly Point[]): Point[] {\n\tconst out: Point[] = [];\n\tfor (const p of points) {\n\t\tif (!Number.isFinite(p[0]) || !Number.isFinite(p[1])) continue;\n\t\tif (out.length === 0 || dist(out[out.length - 1], p) > 1e-12) out.push(p);\n\t}\n\treturn out;\n}\n\n/** Chord-length parameters (0 to 1), one per point. */\nfunction chordParams(pts: Point[]): number[] {\n\tconst u = [0];\n\tlet acc = 0;\n\tfor (let i = 1; i < pts.length; i++) {\n\t\tacc += dist(pts[i - 1], pts[i]);\n\t\tu.push(acc);\n\t}\n\treturn acc > 0 ? u.map((x) => x / acc) : u;\n}\n\n/** Solves the 2×2 normal equations for the handle lengths along the fixed tangents. */\nfunction generate(pts: Point[], u: number[], t0: Vec, t1: Vec): CubicSegment {\n\tconst p0 = pts[0];\n\tconst p3 = pts[pts.length - 1];\n\tconst dirIn: Vec = [-t1[0], -t1[1]];\n\tlet c00 = 0;\n\tlet c01 = 0;\n\tlet c11 = 0;\n\tlet x0 = 0;\n\tlet x1 = 0;\n\tfor (let i = 0; i < pts.length; i++) {\n\t\tconst t = u[i];\n\t\tconst s = 1 - t;\n\t\tconst b0 = s * s * s;\n\t\tconst b1 = 3 * s * s * t;\n\t\tconst b2 = 3 * s * t * t;\n\t\tconst b3 = t * t * t;\n\t\tconst a0: Vec = [t0[0] * b1, t0[1] * b1];\n\t\tconst a1: Vec = [dirIn[0] * b2, dirIn[1] * b2];\n\t\tc00 += dot(a0, a0);\n\t\tc01 += dot(a0, a1);\n\t\tc11 += dot(a1, a1);\n\t\tconst tmp: Vec = [\n\t\t\tpts[i][0] - (p0[0] * (b0 + b1) + p3[0] * (b2 + b3)),\n\t\t\tpts[i][1] - (p0[1] * (b0 + b1) + p3[1] * (b2 + b3))\n\t\t];\n\t\tx0 += dot(a0, tmp);\n\t\tx1 += dot(a1, tmp);\n\t}\n\tconst det = c00 * c11 - c01 * c01;\n\tconst seg = dist(p0, p3);\n\tconst eps = 1e-6 * seg;\n\tlet al = seg / 3;\n\tlet ar = seg / 3;\n\tif (Math.abs(det) > 1e-12) {\n\t\tal = (x0 * c11 - x1 * c01) / det;\n\t\tar = (c00 * x1 - c01 * x0) / det;\n\t}\n\tif (!Number.isFinite(al) || !Number.isFinite(ar) || al < eps || ar < eps) {\n\t\tal = seg / 3;\n\t\tar = seg / 3;\n\t}\n\t// Guard against wild handles on nearly degenerate data.\n\tconst cap = seg * 4 + 1e-9;\n\tal = Math.min(al, cap);\n\tar = Math.min(ar, cap);\n\treturn { p0, p1: add(p0, t0, al), p2: add(p3, dirIn, ar), p3 };\n}\n\n/** Largest distance between a point and the curve at its parameter, and that point's index. */\nfunction maxError(pts: Point[], c: CubicSegment, u: number[]): [number, number] {\n\tlet e = 0;\n\tlet idx = pts.length >> 1;\n\tfor (let i = 0; i < pts.length; i++) {\n\t\tconst d = dist(evalCubic(c, u[i]), pts[i]);\n\t\tif (d > e) {\n\t\t\te = d;\n\t\t\tidx = i;\n\t\t}\n\t}\n\treturn [e, idx];\n}\n\n/** One Newton–Raphson step towards the parameter of the point on `c` nearest `p`. */\nfunction newton(c: CubicSegment, p: Point, t: number): number {\n\tconst s = 1 - t;\n\tconst q = evalCubic(c, t);\n\tconst d1: Vec = [\n\t\t3 * (s * s * (c.p1[0] - c.p0[0]) + 2 * s * t * (c.p2[0] - c.p1[0]) + t * t * (c.p3[0] - c.p2[0])),\n\t\t3 * (s * s * (c.p1[1] - c.p0[1]) + 2 * s * t * (c.p2[1] - c.p1[1]) + t * t * (c.p3[1] - c.p2[1]))\n\t];\n\tconst d2: Vec = [\n\t\t6 * (s * (c.p2[0] - 2 * c.p1[0] + c.p0[0]) + t * (c.p3[0] - 2 * c.p2[0] + c.p1[0])),\n\t\t6 * (s * (c.p2[1] - 2 * c.p1[1] + c.p0[1]) + t * (c.p3[1] - 2 * c.p2[1] + c.p1[1]))\n\t];\n\tconst diff: Vec = [q[0] - p[0], q[1] - p[1]];\n\tconst num = dot(diff, d1);\n\tconst den = dot(d1, d1) + dot(diff, d2);\n\tif (Math.abs(den) < 1e-12) return t;\n\tconst nt = t - num / den;\n\treturn Number.isFinite(nt) ? Math.min(1, Math.max(0, nt)) : t;\n}\n\n/**\n * Best single cubic through `pts` with the given unit end tangents (`t1` points forward at\n * the end), starting from parameters `u`. Returns the curve, its max error and the index of\n * the worst point.\n */\nfunction fitSingleFrom(pts: Point[], u: number[], t0: Vec, t1: Vec): [CubicSegment, number, number] {\n\tlet best = generate(pts, u, t0, t1);\n\tlet [bestErr, bestSplit] = maxError(pts, best, u);\n\tconst params = u.slice();\n\tfor (let round = 0; round < MAX_REPARAM; round++) {\n\t\tfor (let i = 0; i < params.length; i++) params[i] = newton(best, pts[i], params[i]);\n\t\tconst c = generate(pts, params, t0, t1);\n\t\tconst [e, s] = maxError(pts, c, params);\n\t\tif (e < bestErr) {\n\t\t\tbest = c;\n\t\t\tbestErr = e;\n\t\t\tbestSplit = s;\n\t\t} else break;\n\t}\n\treturn [best, bestErr, bestSplit];\n}\n\n/**\n * The best single cubic from the first to the last of `points`, leaving along the unit tangent\n * `t0` and arriving along `t1` (forward), with the points starting at parameters `params`\n * (refined by Newton steps). Returns the curve and its largest point error.\n */\nexport function fitCubicWithTangents(points: readonly Point[], params: readonly number[], t0: Point, t1: Point): { curve: CubicSegment; error: number } {\n\tconst [curve, error] = fitSingleFrom(points.slice(), params.slice(), [t0[0], t0[1]], [t1[0], t1[1]]);\n\treturn { curve, error };\n}\n\nfunction fitRec(pts: Point[], t0: Vec, t1: Vec, tol: number, out: CubicSegment[], depth: number) {\n\tconst n = pts.length;\n\tif (n === 2) {\n\t\tconst d = dist(pts[0], pts[1]) / 3;\n\t\tout.push({ p0: pts[0], p1: add(pts[0], t0, d), p2: add(pts[1], t1, -d), p3: pts[1] });\n\t\treturn;\n\t}\n\tconst [c, err, splitAt] = fitSingleFrom(pts, chordParams(pts), t0, t1);\n\tif (err <= tol || depth > 40) {\n\t\tout.push(c);\n\t\treturn;\n\t}\n\t// Split at the worst point with a centre tangent estimated from its neighbours.\n\tconst split = Math.min(n - 2, Math.max(1, splitAt));\n\tconst tc = unit(sub(pts[split + 1], pts[split - 1])) ?? t0;\n\tfitRec(pts.slice(0, split + 1), t0, tc, tol, out, depth + 1);\n\tfitRec(pts.slice(split), tc, t1, tol, out, depth + 1);\n}\n\n/**\n * Unit tangent at `a` estimated from the parabola through `a`, `b`, `c` (chord-length\n * parameters): second-order accurate, so polylines sampled from curves get their true end\n * direction rather than the first chord's.\n */\nfunction tangentFrom(a: Point, b: Point, c: Point | undefined): Vec | null {\n\tconst chord = unit(sub(b, a));\n\tif (!c) return chord;\n\tconst d1 = dist(a, b);\n\tconst d2 = dist(b, c);\n\tif (!(d1 > 0) || !(d2 > 0)) return chord;\n\tconst ka = -(2 * d1 + d2) / (d1 * (d1 + d2));\n\tconst kb = (d1 + d2) / (d1 * d2);\n\tconst kc = -d1 / (d2 * (d1 + d2));\n\tconst est = unit([ka * a[0] + kb * b[0] + kc * c[0], ka * a[1] + kb * b[1] + kc * c[1]]);\n\t// Fall back to the chord when the estimate swings too far (noisy or sharp data).\n\treturn est && chord && dot(est, chord) > Math.cos(Math.PI / 4) ? est : chord;\n}\n\n/**\n * Fits a G1-continuous chain of cubics through `points` (an open run) with the unit\n * tangents `t0` (leaving the first point) and `t1` (arriving at the last point, forward);\n * both are estimated from the end points when omitted. Every point lies within `tolerance`\n * of the curve at its fitted parameter.\n */\nexport function fitCubicRun(points: readonly Point[], tolerance: number, t0?: Point, t1?: Point): CubicSegment[] {\n\tconst pts = dedup(points);\n\tconst out: CubicSegment[] = [];\n\tif (pts.length < 2) return out;\n\tconst n = pts.length;\n\tconst start = (t0 && unit([t0[0], t0[1]])) ?? tangentFrom(pts[0], pts[1], pts[2]) ?? [1, 0];\n\tconst back = tangentFrom(pts[n - 1], pts[n - 2], pts[n - 3]);\n\tconst end = (t1 && unit([t1[0], t1[1]])) ?? (back ? ([-back[0], -back[1]] as Vec) : [1, 0]);\n\tfitRec(pts, start, end, Math.max(tolerance, 1e-9), out, 0);\n\treturn out;\n}\n\n/** Turning angle in degrees between the directions `a`→`b` and `b`→`c`. */\nfunction turnDeg(a: Point, b: Point, c: Point): number {\n\tconst u = unit(sub(b, a));\n\tconst v = unit(sub(c, b));\n\tif (!u || !v) return 0;\n\treturn (Math.acos(Math.min(1, Math.max(-1, dot(u, v)))) * 180) / Math.PI;\n}\n\n/**\n * Corner vertices of a polyline. The turn at each vertex is measured to the nearest\n * neighbours at least `span` away on each side (so sample noise smaller than the fitting\n * tolerance does not read as corners), and only the sharpest vertex of a neighbourhood is\n * kept. End points of open polylines are not included.\n */\nfunction findCorners(pts: Point[], closed: boolean, cornerAngle: number, span: number): number[] {\n\tconst n = pts.length;\n\tconst at = (i: number) => pts[closed ? ((i % n) + n) % n : i];\n\tconst reach = (i: number, step: 1 | -1): number | null => {\n\t\tfor (let k = 1; k < (closed ? n : Infinity); k++) {\n\t\t\tconst j = i + step * k;\n\t\t\tif (!closed && (j < 0 || j >= n)) return k > 1 ? j - step : null;\n\t\t\tif (dist(at(j), pts[i]) >= span) return j;\n\t\t}\n\t\treturn null;\n\t};\n\tconst turns = new Float64Array(n);\n\tconst windows: [number, number][] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\twindows.push([i, i]);\n\t\tif (!closed && (i === 0 || i === n - 1)) continue;\n\t\tconst prev = reach(i, -1);\n\t\tconst next = reach(i, 1);\n\t\tif (prev === null || next === null) continue;\n\t\twindows[i] = [prev, next];\n\t\tturns[i] = turnDeg(at(prev), pts[i], at(next));\n\t}\n\tconst corners: number[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tif (!(turns[i] > cornerAngle)) continue;\n\t\tconst [lo, hi] = windows[i];\n\t\tlet sharpest = true;\n\t\tfor (let j = lo; j <= hi && sharpest; j++) {\n\t\t\tconst k = closed ? ((j % n) + n) % n : j;\n\t\t\tif (k === i || dist(pts[k], pts[i]) >= span) continue;\n\t\t\tif (turns[k] > turns[i] || (turns[k] === turns[i] && k < i)) sharpest = false;\n\t\t}\n\t\tif (sharpest) corners.push(i);\n\t}\n\treturn corners;\n}\n\n/**\n * Points to fit for a run of polyline vertices: the vertices, plus extra samples along edges\n * much longer than the run's typical edge so straight stretches stay straight.\n */\nfunction densify(run: Point[]): Point[] {\n\tif (run.length < 3) return run;\n\tconst lengths: number[] = [];\n\tfor (let i = 1; i < run.length; i++) lengths.push(dist(run[i - 1], run[i]));\n\tconst sorted = [...lengths].sort((a, b) => a - b);\n\tconst median = sorted[sorted.length >> 1];\n\tif (!(median > 0)) return run;\n\tconst out: Point[] = [run[0]];\n\tfor (let i = 1; i < run.length; i++) {\n\t\tconst len = lengths[i - 1];\n\t\tif (len > 2 * median) {\n\t\t\tconst steps = Math.min(64, Math.ceil(len / median));\n\t\t\tconst a = run[i - 1];\n\t\t\tconst b = run[i];\n\t\t\tfor (let k = 1; k < steps; k++) {\n\t\t\t\tconst t = k / steps;\n\t\t\t\tout.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);\n\t\t\t}\n\t\t}\n\t\tout.push(run[i]);\n\t}\n\treturn out;\n}\n\n/**\n * Fits cubic Bézier segments to a polyline (`closed` for a ring), keeping vertices that turn\n * by more than `cornerAngleDeg` (default 30°) as sharp corners. Each stretch between corners\n * is fitted Schneider-style so that every input point is within `tolerance` of the result.\n *\n * Returns the segments in order (consecutive segments share end points; a closed result ends\n * where it starts). Fewer than two distinct points give an empty array.\n */\nexport function fitCubics(points: readonly Point[], tolerance: number, options: FitCubicsOptions = {}): CubicSegment[] {\n\tlet pts = dedup(points);\n\tconst closed = options.closed === true;\n\tif (closed && pts.length > 1 && dist(pts[0], pts[pts.length - 1]) <= 1e-12) pts = pts.slice(0, -1);\n\tif (pts.length < 2) return [];\n\tconst tol = Math.max(tolerance, 1e-6);\n\tconst cornerAngle = options.cornerAngleDeg ?? 30;\n\tconst n = pts.length;\n\tconst span = 4 * tol;\n\n\tif (!closed || n < 3) {\n\t\tconst corners = [0, ...(n > 2 ? findCorners(pts, false, cornerAngle, span) : []), n - 1];\n\t\tconst out: CubicSegment[] = [];\n\t\tfor (let k = 1; k < corners.length; k++) {\n\t\t\tconst run = pts.slice(corners[k - 1], corners[k] + 1);\n\t\t\tout.push(...fitCubicRun(densify(run), tol));\n\t\t}\n\t\tif (closed && n === 2) out.push(...fitCubicRun([pts[1], pts[0]], tol));\n\t\treturn out;\n\t}\n\n\tconst corners = findCorners(pts, true, cornerAngle, span);\n\tif (corners.length === 0) {\n\t\t// Smooth ring: start anywhere, with the same tangent leaving and arriving.\n\t\tconst ring = [...pts, pts[0]];\n\t\tconst t = unit(sub(pts[1], pts[n - 1])) ?? [1, 0];\n\t\t// (A central difference: already second-order accurate at the seam.)\n\t\treturn fitCubicRun(densify(ring), tol, t, t);\n\t}\n\tconst out: CubicSegment[] = [];\n\tfor (let k = 0; k < corners.length; k++) {\n\t\tconst from = corners[k];\n\t\tconst to = corners[(k + 1) % corners.length];\n\t\tconst run: Point[] = [];\n\t\tfor (let i = from; ; i = (i + 1) % n) {\n\t\t\trun.push(pts[i]);\n\t\t\tif (run.length > 1 && i === to) break;\n\t\t}\n\t\tout.push(...fitCubicRun(densify(run), tol));\n\t}\n\treturn out;\n}\n\n/** Whether a cubic is (within `tol`) the straight line from `p0` to `p3`. */\nexport function isStraightCubic(c: CubicSegment, tol: number): boolean {\n\tconst chord = sub(c.p3, c.p0);\n\tconst len = Math.hypot(chord[0], chord[1]);\n\tif (len < 1e-12) return dist(c.p1, c.p0) <= tol && dist(c.p2, c.p0) <= tol;\n\tconst dir: Vec = [chord[0] / len, chord[1] / len];\n\treturn [c.p1, c.p2].every((h) => {\n\t\tconst v = sub(h, c.p0);\n\t\tconst along = dot(v, dir);\n\t\tconst across = Math.abs(v[0] * dir[1] - v[1] * dir[0]);\n\t\treturn across <= tol && along >= -tol && along <= len + tol;\n\t});\n}\n\nexport interface FitPathDataOptions extends FitCubicsOptions {\n\t/** Fitting tolerance in path units (default 0.5). */\n\ttolerance?: number;\n\t/** Decimal places (default 3). */\n\tprecision?: number;\n\t/** Added to every point before formatting. */\n\toffset?: { x: number; y: number };\n\t/**\n\t * Keep the original polyline when fitting would need more segments than it has edges\n\t * (default `true`), so fitting never makes a path heavier.\n\t */\n\tnoWorse?: boolean;\n}\n\n/** SVG `d` for fitted segments (`L` for straight ones, `C` otherwise). */\nexport function cubicsToPathData(\n\tsegments: readonly CubicSegment[],\n\toptions: { precision?: number; offset?: { x: number; y: number }; closed?: boolean; straightTolerance?: number } = {}\n): string {\n\tif (segments.length === 0) return '';\n\tconst f = (n: number) => formatNumber(n, options.precision ?? 3);\n\tconst dx = options.offset?.x ?? 0;\n\tconst dy = options.offset?.y ?? 0;\n\tconst pt = (p: Point) => `${f(p[0] + dx)} ${f(p[1] + dy)}`;\n\tconst straight = options.straightTolerance ?? 1e-3;\n\tlet d = `M${pt(segments[0].p0)}`;\n\tsegments.forEach((c, i) => {\n\t\tconst last = options.closed && i === segments.length - 1;\n\t\tif (isStraightCubic(c, straight)) {\n\t\t\tif (!last) d += `L${pt(c.p3)}`;\n\t\t} else d += `C${pt(c.p1)} ${pt(c.p2)} ${pt(c.p3)}`;\n\t});\n\treturn options.closed ? `${d}Z` : d;\n}\n\nfunction polylineToPathData(points: readonly Point[], closed: boolean, options: FitPathDataOptions): string {\n\tif (points.length < 2) return '';\n\tconst f = (n: number) => formatNumber(n, options.precision ?? 3);\n\tconst dx = options.offset?.x ?? 0;\n\tconst dy = options.offset?.y ?? 0;\n\tlet d = `M${f(points[0][0] + dx)} ${f(points[0][1] + dy)}`;\n\tfor (let i = 1; i < points.length; i++) d += `L${f(points[i][0] + dx)} ${f(points[i][1] + dy)}`;\n\treturn closed ? `${d}Z` : d;\n}\n\n/**\n * Fits smooth curves to a polygon ring (closed by default) and returns SVG path data with\n * `C` curves for smooth stretches, `L` lines for straight ones and sharp corners kept.\n * Use it for boolean results of curved shapes or to smooth freehand strokes\n * (`{ closed: false }`, see `fitFreehandPath`).\n */\nexport function fitPathData(ring: readonly Point[], options: FitPathDataOptions = {}): string {\n\tconst closed = options.closed ?? true;\n\tconst tolerance = options.tolerance ?? 0.5;\n\tconst pts = dedup(ring);\n\tconst segments = fitCubics(pts, tolerance, { ...options, closed });\n\tif (segments.length === 0) return '';\n\tconst edges = closed ? pts.length : pts.length - 1;\n\tif (options.noWorse !== false) {\n\t\tconst straight = segments.filter((c) => isStraightCubic(c, tolerance * 0.02)).length;\n\t\t// Fitting only pays off when it removes vertices.\n\t\tif (segments.length >= edges && straight === segments.length) return polylineToPathData(pts, closed, options);\n\t\tif (segments.length > edges) return polylineToPathData(pts, closed, options);\n\t}\n\treturn cubicsToPathData(segments, {\n\t\tprecision: options.precision,\n\t\toffset: options.offset,\n\t\tclosed,\n\t\tstraightTolerance: tolerance * 0.02\n\t});\n}\n\n/**\n * Smooths a freehand stroke (pointer samples) into an open SVG path of cubic curves.\n * `tolerance` is the largest distance (in the points' units) a sample may be from the\n * curve (default 1); sharp turns above `cornerAngleDeg` (default 30) stay corners.\n */\nexport function fitFreehandPath(\n\tpoints: readonly Point[],\n\toptions: Omit<FitPathDataOptions, 'closed'> = {}\n): string {\n\treturn fitPathData(points, { tolerance: 1, ...options, closed: false });\n}\n","/**\n * Shape geometry: shape descriptions (rect, rounded rect, ellipse, regular polygon, star and\n * SVG path data) to polygons, SVG path parsing / flattening, and polygons back to path data.\n */\nimport type { Point } from './types.js';\nimport type { MultiPolygon, PolygonFillRule, PolygonRing } from './polygonBoolean.js';\nimport { fitPathData } from './curveFit.js';\n\n// ---------------------------------------------------------------------------\n// Shape descriptions\n// ---------------------------------------------------------------------------\n\nimport type { CanvasGradientDef, SvgGradientDef } from './gradient.js';\nimport type { CanvasBrushstroke } from './brushTypes.js';\nimport { gradientToSvgDef, resolveCanvasGradient } from './gradient.js';\n\n/** Paint shared by every shape kind. Colours are any CSS colour, preset name, or gradient definition. */\nexport interface ShapePaint {\n\tfill?: string | CanvasGradientDef;\n\tstroke?: string | CanvasGradientDef;\n\tstrokeWidth?: number;\n\topacity?: number;\n\tstrokeLinecap?: 'round' | 'butt' | 'square';\n\tstrokeLinejoin?: 'round' | 'bevel' | 'miter';\n\tfillGradient?: CanvasGradientDef;\n\tstrokeGradient?: CanvasGradientDef;\n}\n\ninterface ShapeBase extends ShapePaint {\n\t/** Clockwise rotation in degrees (on a y-down canvas) about the centre of the node box. */\n\trotation?: number;\n}\n\n/** Rectangle filling the node box, optionally with rounded corners. */\nexport interface RectShape extends ShapeBase {\n\tkind: 'rect';\n\t/** One radius, or `[topLeft, topRight, bottomRight, bottomLeft]`. Clamped to fit. */\n\tcornerRadius?: number | readonly [number, number, number, number];\n}\n\n/** Ellipse (circle when the node is square) inscribed in the node box. */\nexport interface EllipseShape extends ShapeBase {\n\tkind: 'ellipse';\n}\n\n/** Regular polygon, stretched so its bounding box fills the node box. */\nexport interface RegularPolygonShape extends ShapeBase {\n\tkind: 'polygon';\n\t/** Number of sides (at least 3, default 6). The first vertex points up. */\n\tsides?: number;\n}\n\n/** Star, stretched so its bounding box fills the node box. */\nexport interface StarShape extends ShapeBase {\n\tkind: 'star';\n\t/** Number of points (at least 3, default 5). The first point points up. */\n\tpoints?: number;\n\t/** Inner radius as a fraction of the outer radius (default 0.5). */\n\tinnerRadius?: number;\n}\n\n/** Arbitrary SVG path data. */\nexport interface PathShape extends ShapeBase {\n\tkind: 'path';\n\td: string;\n\t/**\n\t * `[minX, minY, width, height]` of the path's coordinate space, scaled to the node box.\n\t * Without it the path coordinates are node-local pixels.\n\t */\n\tviewBox?: readonly [number, number, number, number];\n\t/** Fill rule (default `nonzero`, as in SVG). */\n\tfillRule?: PolygonFillRule;\n\t/**\n\t * Draw the path with a dry paint brush instead of an SVG stroke (a brushed freehand stroke):\n\t * the brush and pen profiles along the path. Rendered by `renderShapeBrushstroke`.\n\t */\n\tbrush?: CanvasBrushstroke;\n}\n\n/**\n * Shape description stored on a node as `data.shape`. Geometry is relative to the node\n * box (`0,0` to `width,height`), so resizing the node resizes the shape.\n */\nexport type ShapeDescription = RectShape | EllipseShape | RegularPolygonShape | StarShape | PathShape;\n\nexport type ShapeKind = ShapeDescription['kind'];\n\nexport const SHAPE_KINDS: readonly ShapeKind[] = ['rect', 'ellipse', 'polygon', 'star', 'path'];\n\n/** Whether a value is a supported shape description. */\nexport function isShapeDescription(value: unknown): value is ShapeDescription {\n\tif (!value || typeof value !== 'object') return false;\n\tconst kind = (value as { kind?: unknown }).kind;\n\tif (!SHAPE_KINDS.includes(kind as ShapeKind)) return false;\n\treturn kind !== 'path' || typeof (value as PathShape).d === 'string';\n}\n\nexport interface ShapeSize {\n\twidth: number;\n\theight: number;\n}\n\nexport interface FlattenOptions {\n\t/** Maximum distance between a curve and its polyline, in output units (default 0.25). */\n\ttolerance?: number;\n\t/** Upper bound on the segments one curve is split into (default 512). */\n\tmaxSegments?: number;\n}\n\n// ---------------------------------------------------------------------------\n// SVG path parsing\n// ---------------------------------------------------------------------------\n\n/** Normalised absolute path command produced by `parseSvgPath`. */\nexport type PathCommand =\n\t| { type: 'M'; x: number; y: number }\n\t| { type: 'L'; x: number; y: number }\n\t| { type: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n\t| { type: 'Q'; x1: number; y1: number; x: number; y: number }\n\t| {\n\t\t\ttype: 'A';\n\t\t\trx: number;\n\t\t\try: number;\n\t\t\trotation: number;\n\t\t\tlargeArc: boolean;\n\t\t\tsweep: boolean;\n\t\t\tx: number;\n\t\t\ty: number;\n\t }\n\t| { type: 'Z' };\n\nconst PARAM_COUNTS: Record<string, number> = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };\n\n/** Character scanner for path data (handles `1.5.5`, `1e-3`, `-1-2` and compact arc flags). */\nclass PathScanner {\n\tprivate pos = 0;\n\tconstructor(private readonly text: string) {}\n\n\tprivate skip() {\n\t\twhile (this.pos < this.text.length && /[\\s,]/.test(this.text[this.pos])) this.pos++;\n\t}\n\n\t/** The next command letter, or `null` when a number (or the end) follows. */\n\tcommand(): string | null {\n\t\tthis.skip();\n\t\tconst ch = this.text[this.pos];\n\t\tif (ch && /[MmLlHhVvCcSsQqTtAaZz]/.test(ch)) {\n\t\t\tthis.pos++;\n\t\t\treturn ch;\n\t\t}\n\t\treturn null;\n\t}\n\n\tdone(): boolean {\n\t\tthis.skip();\n\t\treturn this.pos >= this.text.length;\n\t}\n\n\tnumber(): number | null {\n\t\tthis.skip();\n\t\tconst match = /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?/.exec(this.text.slice(this.pos, this.pos + 64));\n\t\tif (!match) return null;\n\t\tthis.pos += match[0].length;\n\t\tconst value = Number(match[0]);\n\t\treturn Number.isFinite(value) ? value : null;\n\t}\n\n\tflag(): number | null {\n\t\tthis.skip();\n\t\tconst ch = this.text[this.pos];\n\t\tif (ch === '0' || ch === '1') {\n\t\t\tthis.pos++;\n\t\t\treturn ch === '1' ? 1 : 0;\n\t\t}\n\t\treturn null;\n\t}\n}\n\n/**\n * Parses SVG path data into absolute `M`, `L`, `C`, `Q`, `A` and `Z` commands. Relative\n * commands, `H` / `V`, smooth curves (`S` / `T`) and implicit repeated commands are\n * normalised. Parsing stops at the first malformed command (as browsers do).\n */\nexport function parseSvgPath(d: string): PathCommand[] {\n\tconst scanner = new PathScanner(d ?? '');\n\tconst commands: PathCommand[] = [];\n\tlet cx = 0;\n\tlet cy = 0;\n\tlet startX = 0;\n\tlet startY = 0;\n\tlet lastControl: { x: number; y: number; type: 'C' | 'Q' } | null = null;\n\tlet command = '';\n\n\twhile (!scanner.done()) {\n\t\tconst letter = scanner.command();\n\t\tif (letter) {\n\t\t\tcommand = letter;\n\t\t\tif (command === 'z' || command === 'Z') {\n\t\t\t\tcommands.push({ type: 'Z' });\n\t\t\t\tcx = startX;\n\t\t\t\tcy = startY;\n\t\t\t\tlastControl = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!command || command === 'z' || command === 'Z') {\n\t\t\tbreak;\n\t\t}\n\t\tconst lower = command.toLowerCase();\n\t\tconst count = PARAM_COUNTS[lower];\n\t\tconst args: number[] = [];\n\t\tfor (let k = 0; k < count; k++) {\n\t\t\tconst value = lower === 'a' && (k === 3 || k === 4) ? scanner.flag() : scanner.number();\n\t\t\tif (value === null) return commands;\n\t\t\targs.push(value);\n\t\t}\n\t\tconst rel = command !== command.toUpperCase();\n\t\tconst ox = rel ? cx : 0;\n\t\tconst oy = rel ? cy : 0;\n\t\tswitch (lower) {\n\t\t\tcase 'm': {\n\t\t\t\tcx = args[0] + ox;\n\t\t\t\tcy = args[1] + oy;\n\t\t\t\tstartX = cx;\n\t\t\t\tstartY = cy;\n\t\t\t\tcommands.push({ type: 'M', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\t// Extra coordinate pairs after a moveto are implicit linetos.\n\t\t\t\tcommand = rel ? 'l' : 'L';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'l':\n\t\t\t\tcx = args[0] + ox;\n\t\t\t\tcy = args[1] + oy;\n\t\t\t\tcommands.push({ type: 'L', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tcx = args[0] + (rel ? cx : 0);\n\t\t\t\tcommands.push({ type: 'L', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\tbreak;\n\t\t\tcase 'v':\n\t\t\t\tcy = args[0] + (rel ? cy : 0);\n\t\t\t\tcommands.push({ type: 'L', x: cx, y: cy });\n\t\t\t\tlastControl = null;\n\t\t\t\tbreak;\n\t\t\tcase 'c': {\n\t\t\t\tconst c: PathCommand = {\n\t\t\t\t\ttype: 'C',\n\t\t\t\t\tx1: args[0] + ox,\n\t\t\t\t\ty1: args[1] + oy,\n\t\t\t\t\tx2: args[2] + ox,\n\t\t\t\t\ty2: args[3] + oy,\n\t\t\t\t\tx: args[4] + ox,\n\t\t\t\t\ty: args[5] + oy\n\t\t\t\t};\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: c.x2, y: c.y2, type: 'C' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 's': {\n\t\t\t\tconst x1: number = lastControl?.type === 'C' ? 2 * cx - lastControl.x : cx;\n\t\t\t\tconst y1: number = lastControl?.type === 'C' ? 2 * cy - lastControl.y : cy;\n\t\t\t\tconst c: PathCommand = {\n\t\t\t\t\ttype: 'C',\n\t\t\t\t\tx1,\n\t\t\t\t\ty1,\n\t\t\t\t\tx2: args[0] + ox,\n\t\t\t\t\ty2: args[1] + oy,\n\t\t\t\t\tx: args[2] + ox,\n\t\t\t\t\ty: args[3] + oy\n\t\t\t\t};\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: c.x2, y: c.y2, type: 'C' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'q': {\n\t\t\t\tconst c: PathCommand = { type: 'Q', x1: args[0] + ox, y1: args[1] + oy, x: args[2] + ox, y: args[3] + oy };\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: c.x1, y: c.y1, type: 'Q' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 't': {\n\t\t\t\tconst x1: number = lastControl?.type === 'Q' ? 2 * cx - lastControl.x : cx;\n\t\t\t\tconst y1: number = lastControl?.type === 'Q' ? 2 * cy - lastControl.y : cy;\n\t\t\t\tconst c: PathCommand = { type: 'Q', x1, y1, x: args[0] + ox, y: args[1] + oy };\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = { x: x1, y: y1, type: 'Q' };\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'a': {\n\t\t\t\tconst c: PathCommand = {\n\t\t\t\t\ttype: 'A',\n\t\t\t\t\trx: Math.abs(args[0]),\n\t\t\t\t\try: Math.abs(args[1]),\n\t\t\t\t\trotation: args[2],\n\t\t\t\t\tlargeArc: args[3] !== 0,\n\t\t\t\t\tsweep: args[4] !== 0,\n\t\t\t\t\tx: args[5] + ox,\n\t\t\t\t\ty: args[6] + oy\n\t\t\t\t};\n\t\t\t\tcommands.push(c);\n\t\t\t\tlastControl = null;\n\t\t\t\tcx = c.x;\n\t\t\t\tcy = c.y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn commands;\n}\n\n// ---------------------------------------------------------------------------\n// Curve flattening\n// ---------------------------------------------------------------------------\n\nfunction segmentCount(curvature: number, tolerance: number, max: number): number {\n\tif (!(curvature > 0)) return 1;\n\treturn Math.max(1, Math.min(max, Math.ceil(Math.sqrt(curvature / tolerance))));\n}\n\nfunction flattenCubic(\n\tout: Point[],\n\tp0: Point,\n\tx1: number,\n\ty1: number,\n\tx2: number,\n\ty2: number,\n\tx: number,\n\ty: number,\n\ttolerance: number,\n\tmax: number\n) {\n\t// Uniform subdivision error <= max|B''| / (8 n²) with |B''| <= 6 * max second difference.\n\tconst dd = Math.max(\n\t\tMath.hypot(p0[0] - 2 * x1 + x2, p0[1] - 2 * y1 + y2),\n\t\tMath.hypot(x1 - 2 * x2 + x, y1 - 2 * y2 + y)\n\t);\n\tconst n = segmentCount((6 * dd) / 8, tolerance, max);\n\tfor (let k = 1; k <= n; k++) {\n\t\tconst t = k / n;\n\t\tconst mt = 1 - t;\n\t\tconst a = mt * mt * mt;\n\t\tconst b = 3 * mt * mt * t;\n\t\tconst c = 3 * mt * t * t;\n\t\tconst e = t * t * t;\n\t\tout.push([a * p0[0] + b * x1 + c * x2 + e * x, a * p0[1] + b * y1 + c * y2 + e * y]);\n\t}\n}\n\nfunction flattenQuadratic(\n\tout: Point[],\n\tp0: Point,\n\tx1: number,\n\ty1: number,\n\tx: number,\n\ty: number,\n\ttolerance: number,\n\tmax: number\n) {\n\tconst dd = Math.hypot(p0[0] - 2 * x1 + x, p0[1] - 2 * y1 + y);\n\tconst n = segmentCount((2 * dd) / 8, tolerance, max);\n\tfor (let k = 1; k <= n; k++) {\n\t\tconst t = k / n;\n\t\tconst mt = 1 - t;\n\t\tout.push([mt * mt * p0[0] + 2 * mt * t * x1 + t * t * x, mt * mt * p0[1] + 2 * mt * t * y1 + t * t * y]);\n\t}\n}\n\nfunction arcSteps(radius: number, sweep: number, tolerance: number, max: number): number {\n\tif (radius <= tolerance) return Math.max(1, Math.ceil(Math.abs(sweep) / (Math.PI / 2)));\n\tconst step = 2 * Math.acos(1 - tolerance / radius);\n\treturn Math.max(1, Math.min(max, Math.ceil(Math.abs(sweep) / step)));\n}\n\n/** Flattens an SVG elliptical arc (endpoint parameterisation, SVG 1.1 F.6.5). */\nfunction flattenArc(\n\tout: Point[],\n\tp0: Point,\n\tcmd: Extract<PathCommand, { type: 'A' }>,\n\ttolerance: number,\n\tmax: number\n) {\n\tconst [x0, y0] = p0;\n\tlet { rx, ry } = cmd;\n\tconst { x, y } = cmd;\n\tif (x0 === x && y0 === y) return;\n\tif (rx === 0 || ry === 0) {\n\t\tout.push([x, y]);\n\t\treturn;\n\t}\n\tconst phi = (cmd.rotation * Math.PI) / 180;\n\tconst cos = Math.cos(phi);\n\tconst sin = Math.sin(phi);\n\tconst dx = (x0 - x) / 2;\n\tconst dy = (y0 - y) / 2;\n\tconst x1p = cos * dx + sin * dy;\n\tconst y1p = -sin * dx + cos * dy;\n\tconst lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);\n\tif (lambda > 1) {\n\t\tconst s = Math.sqrt(lambda);\n\t\trx *= s;\n\t\try *= s;\n\t}\n\tconst num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;\n\tconst den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;\n\tlet coef = den === 0 ? 0 : Math.sqrt(Math.max(0, num / den));\n\tif (cmd.largeArc === cmd.sweep) coef = -coef;\n\tconst cxp = (coef * rx * y1p) / ry;\n\tconst cyp = (-coef * ry * x1p) / rx;\n\tconst cx = cos * cxp - sin * cyp + (x0 + x) / 2;\n\tconst cy = sin * cxp + cos * cyp + (y0 + y) / 2;\n\tconst angle = (ux: number, uy: number, vx: number, vy: number) => {\n\t\tconst a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);\n\t\treturn a;\n\t};\n\tconst theta1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);\n\tlet delta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);\n\tif (!cmd.sweep && delta > 0) delta -= 2 * Math.PI;\n\telse if (cmd.sweep && delta < 0) delta += 2 * Math.PI;\n\tconst n = arcSteps(Math.max(rx, ry), delta, tolerance, max);\n\tfor (let k = 1; k < n; k++) {\n\t\tconst t = theta1 + (delta * k) / n;\n\t\tconst ex = rx * Math.cos(t);\n\t\tconst ey = ry * Math.sin(t);\n\t\tout.push([cos * ex - sin * ey + cx, sin * ex + cos * ey + cy]);\n\t}\n\tout.push([x, y]);\n}\n\n/**\n * Flattens SVG path data into closed rings (one per subpath; open subpaths are closed the\n * way SVG fills them). Curves are approximated within `tolerance`.\n */\nexport function flattenSvgPath(d: string | PathCommand[], options: FlattenOptions = {}): PolygonRing[] {\n\tconst tolerance = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.25;\n\tconst max = options.maxSegments ?? 512;\n\tconst commands = typeof d === 'string' ? parseSvgPath(d) : d;\n\tconst rings: PolygonRing[] = [];\n\tlet current: Point[] = [];\n\tlet start: Point = [0, 0];\n\tconst flush = () => {\n\t\tif (current.length >= 3) rings.push(current);\n\t\tcurrent = [];\n\t};\n\tconst last = (): Point => current[current.length - 1] ?? start;\n\tfor (const cmd of commands) {\n\t\tswitch (cmd.type) {\n\t\t\tcase 'M':\n\t\t\t\tflush();\n\t\t\t\tstart = [cmd.x, cmd.y];\n\t\t\t\tcurrent = [start];\n\t\t\t\tbreak;\n\t\t\tcase 'L':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tcurrent.push([cmd.x, cmd.y]);\n\t\t\t\tbreak;\n\t\t\tcase 'C':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tflattenCubic(current, last(), cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y, tolerance, max);\n\t\t\t\tbreak;\n\t\t\tcase 'Q':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tflattenQuadratic(current, last(), cmd.x1, cmd.y1, cmd.x, cmd.y, tolerance, max);\n\t\t\t\tbreak;\n\t\t\tcase 'A':\n\t\t\t\tif (current.length === 0) current = [start];\n\t\t\t\tflattenArc(current, last(), cmd, tolerance, max);\n\t\t\t\tbreak;\n\t\t\tcase 'Z':\n\t\t\t\tflush();\n\t\t\t\t// A command after Z without a moveto starts at the subpath start.\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tflush();\n\treturn rings.map(dedupeRing).filter((r) => r.length >= 3);\n}\n\nfunction dedupeRing(ring: Point[]): Point[] {\n\tconst out: Point[] = [];\n\tfor (const p of ring) {\n\t\tconst prev = out[out.length - 1];\n\t\tif (!prev || prev[0] !== p[0] || prev[1] !== p[1]) out.push(p);\n\t}\n\twhile (out.length > 1 && out[0][0] === out[out.length - 1][0] && out[0][1] === out[out.length - 1][1]) out.pop();\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Shapes to polygons\n// ---------------------------------------------------------------------------\n\nfunction cornerRadii(shape: RectShape, width: number, height: number): [number, number, number, number] {\n\tconst raw = shape.cornerRadius ?? 0;\n\tlet radii = (typeof raw === 'number' ? [raw, raw, raw, raw] : [...raw]).map((r) =>\n\t\tNumber.isFinite(r) && r > 0 ? r : 0\n\t) as [number, number, number, number];\n\t// Scale all radii down together when adjacent corners would overlap (CSS rule).\n\tconst factor = Math.min(\n\t\t1,\n\t\twidth / Math.max(radii[0] + radii[1], 1e-12),\n\t\theight / Math.max(radii[1] + radii[2], 1e-12),\n\t\twidth / Math.max(radii[2] + radii[3], 1e-12),\n\t\theight / Math.max(radii[3] + radii[0], 1e-12)\n\t);\n\tif (factor < 1) radii = radii.map((r) => r * factor) as [number, number, number, number];\n\treturn radii;\n}\n\n/** Unit vertices of a regular polygon / star, stretched to fill the box. */\nfunction polygonVertices(count: number, inner: number | null, width: number, height: number): Point[] {\n\tconst raw: Point[] = [];\n\tconst total = inner === null ? count : count * 2;\n\tfor (let k = 0; k < total; k++) {\n\t\tconst angle = -Math.PI / 2 + (k * 2 * Math.PI) / total;\n\t\tconst r = inner !== null && k % 2 === 1 ? inner : 1;\n\t\traw.push([r * Math.cos(angle), r * Math.sin(angle)]);\n\t}\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of raw) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\tconst sx = width / (maxX - minX || 1);\n\tconst sy = height / (maxY - minY || 1);\n\treturn raw.map(([x, y]) => [(x - minX) * sx, (y - minY) * sy]);\n}\n\nfunction rotationTransform(shape: ShapeDescription, size: ShapeSize): ((p: Point) => Point) | null {\n\tconst deg = shape.rotation ?? 0;\n\tif (!deg || !Number.isFinite(deg)) return null;\n\tconst rad = (deg * Math.PI) / 180;\n\tconst cos = Math.cos(rad);\n\tconst sin = Math.sin(rad);\n\tconst cx = size.width / 2;\n\tconst cy = size.height / 2;\n\treturn ([x, y]) => [cx + (x - cx) * cos - (y - cy) * sin, cy + (x - cx) * sin + (y - cy) * cos];\n}\n\n/**\n * SVG path data for a shape in node-local pixels (exact curves: arcs for rounded corners\n * and ellipses), plus the fill rule and a `transform` for rotation / path view boxes.\n * Use it to render a shape; use `shapeToPolygon` for geometry.\n */\nexport function getShapeSvg(\n\tshape: ShapeDescription,\n\tsize: ShapeSize\n): { d: string; transform?: string; fillRule: PolygonFillRule } {\n\tconst { width: w, height: h } = size;\n\tconst f = (n: number) => formatNumber(n, 3);\n\tconst transforms: string[] = [];\n\tif (shape.rotation) transforms.push(`rotate(${f(shape.rotation)} ${f(w / 2)} ${f(h / 2)})`);\n\tlet d = '';\n\tlet fillRule: PolygonFillRule = 'nonzero';\n\tswitch (shape.kind) {\n\t\tcase 'rect': {\n\t\t\tconst [tl, tr, br, bl] = cornerRadii(shape, w, h);\n\t\t\tif (tl + tr + br + bl === 0) {\n\t\t\t\td = `M0 0H${f(w)}V${f(h)}H0Z`;\n\t\t\t} else {\n\t\t\t\tconst arc = (r: number, x: number, y: number) => (r > 0 ? `A${f(r)} ${f(r)} 0 0 1 ${f(x)} ${f(y)}` : '');\n\t\t\t\td =\n\t\t\t\t\t`M${f(tl)} 0H${f(w - tr)}${arc(tr, w, tr)}V${f(h - br)}${arc(br, w - br, h)}` +\n\t\t\t\t\t`H${f(bl)}${arc(bl, 0, h - bl)}V${f(tl)}${arc(tl, tl, 0)}Z`;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'ellipse': {\n\t\t\tconst rx = w / 2;\n\t\t\tconst ry = h / 2;\n\t\t\td = `M0 ${f(ry)}A${f(rx)} ${f(ry)} 0 1 1 ${f(w)} ${f(ry)}A${f(rx)} ${f(ry)} 0 1 1 0 ${f(ry)}Z`;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'polygon':\n\t\tcase 'star': {\n\t\t\tconst points =\n\t\t\t\tshape.kind === 'polygon'\n\t\t\t\t\t? polygonVertices(Math.max(3, Math.floor(shape.sides ?? 6)), null, w, h)\n\t\t\t\t\t: polygonVertices(Math.max(3, Math.floor(shape.points ?? 5)), clampRatio(shape.innerRadius), w, h);\n\t\t\td = ringsToPath([points], f);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'path': {\n\t\t\td = shape.d;\n\t\t\tfillRule = shape.fillRule ?? 'nonzero';\n\t\t\tconst vb = validViewBox(shape.viewBox);\n\t\t\tif (vb) {\n\t\t\t\ttransforms.push(\n\t\t\t\t\t`scale(${f(w / vb[2])} ${f(h / vb[3])})`,\n\t\t\t\t\t`translate(${f(-vb[0])} ${f(-vb[1])})`\n\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn transforms.length > 0 ? { d, transform: transforms.join(' '), fillRule } : { d, fillRule };\n}\n\n/** Everything a renderer needs to draw a shape as one SVG `<path>`. */\nexport interface ShapeRenderData {\n\t/** SVG `viewBox` (`0 0 width height`): node-local pixels. */\n\tviewBox: string;\n\twidth: number;\n\theight: number;\n\td: string;\n\ttransform?: string;\n\tfillRule: PolygonFillRule;\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: number;\n\topacity?: number;\n\tstrokeLinecap?: 'round' | 'butt' | 'square';\n\tstrokeLinejoin?: 'round' | 'bevel' | 'miter';\n\t/** Gradient def for the fill, when fill uses a gradient. */\n\tfillGradient?: SvgGradientDef;\n\t/** Gradient def for the stroke, when stroke uses a gradient. */\n\tstrokeGradient?: SvgGradientDef;\n}\n\nexport interface GetShapeRenderDataOptions {\n\t/** Unique ID suffix or base ID used when generating SVG gradient IDs (default: auto random). */\n\tid?: string;\n}\n\n/**\n * Resolves the SVG drawing of a shape for a node size. Without a size, a path's view box\n * size (or 100x100) is used. Paint defaults: `fill: currentColor`, `stroke: none`,\n * `strokeWidth: 1`. Supports solid colors, CSS gradients, presets, and CanvasGradientDef.\n */\nexport function getShapeRenderData(\n\tshape: ShapeDescription,\n\tsize: Partial<ShapeSize> = {},\n\toptions: GetShapeRenderDataOptions = {}\n): ShapeRenderData {\n\tconst vb = shape.kind === 'path' ? validViewBox(shape.viewBox) : null;\n\tconst width = size.width && size.width > 0 ? size.width : vb ? vb[2] : 100;\n\tconst height = size.height && size.height > 0 ? size.height : vb ? vb[3] : 100;\n\tconst svg = getShapeSvg(shape, { width, height });\n\n\tconst baseId = options.id || Math.random().toString(36).slice(2, 9);\n\n\t// Resolve fill (gradient or solid)\n\tlet fillStr = 'currentColor';\n\tlet fillGradientDef: SvgGradientDef | undefined;\n\tconst rawFill = shape.fillGradient ?? shape.fill;\n\tconst resolvedFillGradient = resolveCanvasGradient(rawFill);\n\tif (resolvedFillGradient) {\n\t\tconst gradId = `shape-fill-${baseId}`;\n\t\tfillGradientDef = gradientToSvgDef(resolvedFillGradient, gradId);\n\t\tfillStr = `url(#${gradId})`;\n\t} else if (typeof shape.fill === 'string') {\n\t\tfillStr = shape.fill;\n\t} else if (shape.fill === undefined) {\n\t\tfillStr = 'currentColor';\n\t}\n\n\t// Resolve stroke (gradient or solid)\n\tlet strokeStr = 'none';\n\tlet strokeGradientDef: SvgGradientDef | undefined;\n\tconst rawStroke = shape.strokeGradient ?? shape.stroke;\n\tconst resolvedStrokeGradient = resolveCanvasGradient(rawStroke);\n\tif (resolvedStrokeGradient) {\n\t\tconst gradId = `shape-stroke-${baseId}`;\n\t\tstrokeGradientDef = gradientToSvgDef(resolvedStrokeGradient, gradId);\n\t\tstrokeStr = `url(#${gradId})`;\n\t} else if (typeof shape.stroke === 'string') {\n\t\tstrokeStr = shape.stroke;\n\t} else if (shape.stroke === undefined) {\n\t\tstrokeStr = 'none';\n\t}\n\n\tconst data: ShapeRenderData = {\n\t\tviewBox: `0 0 ${formatNumber(width, 3)} ${formatNumber(height, 3)}`,\n\t\twidth,\n\t\theight,\n\t\td: svg.d,\n\t\tfillRule: svg.fillRule,\n\t\tfill: fillStr,\n\t\tstroke: strokeStr,\n\t\tstrokeWidth: shape.strokeWidth ?? 1\n\t};\n\tif (svg.transform) data.transform = svg.transform;\n\tif (shape.opacity !== undefined) data.opacity = shape.opacity;\n\tif (shape.strokeLinecap) data.strokeLinecap = shape.strokeLinecap;\n\tif (shape.strokeLinejoin) data.strokeLinejoin = shape.strokeLinejoin;\n\tif (fillGradientDef) data.fillGradient = fillGradientDef;\n\tif (strokeGradientDef) data.strokeGradient = strokeGradientDef;\n\treturn data;\n}\n\nfunction clampRatio(value: number | undefined): number {\n\tif (value === undefined || !Number.isFinite(value)) return 0.5;\n\treturn Math.min(1, Math.max(0.01, value));\n}\n\nfunction validViewBox(vb: PathShape['viewBox']): readonly [number, number, number, number] | null {\n\tif (!vb || vb.length !== 4 || !vb.every(Number.isFinite) || vb[2] <= 0 || vb[3] <= 0) return null;\n\treturn vb;\n}\n\n/**\n * Converts a shape to rings in node-local pixels (rotation applied), flattening curves at\n * `tolerance`. Returns the rings with the fill rule they must be read with.\n */\nexport function shapeToPolygon(\n\tshape: ShapeDescription,\n\tsize: ShapeSize,\n\toptions: FlattenOptions = {}\n): { rings: PolygonRing[]; fillRule: PolygonFillRule } {\n\tconst { width: w, height: h } = size;\n\tif (!(w > 0) || !(h > 0)) return { rings: [], fillRule: 'nonzero' };\n\tlet rings: PolygonRing[];\n\tlet fillRule: PolygonFillRule = 'nonzero';\n\tif (shape.kind === 'path') {\n\t\tfillRule = shape.fillRule ?? 'nonzero';\n\t\tconst vb = validViewBox(shape.viewBox);\n\t\tif (vb) {\n\t\t\tconst sx = w / vb[2];\n\t\t\tconst sy = h / vb[3];\n\t\t\t// Flatten in path units with the tolerance scaled to stay within `tolerance` px.\n\t\t\tconst tolerance = (options.tolerance ?? 0.25) / Math.max(sx, sy);\n\t\t\trings = flattenSvgPath(shape.d, { ...options, tolerance }).map((ring) =>\n\t\t\t\tring.map(([x, y]) => [(x - vb[0]) * sx, (y - vb[1]) * sy] as Point)\n\t\t\t);\n\t\t} else {\n\t\t\trings = flattenSvgPath(shape.d, options);\n\t\t}\n\t} else {\n\t\tconst { d } = getShapeSvg({ ...shape, rotation: 0 }, size);\n\t\trings = flattenSvgPath(d, options);\n\t}\n\tconst rotate = rotationTransform(shape, size);\n\tif (rotate) rings = rings.map((ring) => ring.map(rotate));\n\treturn { rings, fillRule };\n}\n\n// ---------------------------------------------------------------------------\n// Polygons to path data\n// ---------------------------------------------------------------------------\n\n/** Formats a number with at most `precision` decimals, without trailing zeros. */\nexport function formatNumber(value: number, precision = 3): string {\n\tconst factor = 10 ** precision;\n\tconst rounded = Math.round(value * factor) / factor;\n\treturn Object.is(rounded, -0) ? '0' : String(rounded);\n}\n\nfunction ringsToPath(rings: readonly (readonly Point[])[], f: (n: number) => string): string {\n\tlet d = '';\n\tfor (const ring of rings) {\n\t\tif (ring.length < 2) continue;\n\t\td += `M${f(ring[0][0])} ${f(ring[0][1])}`;\n\t\tfor (let i = 1; i < ring.length; i++) d += `L${f(ring[i][0])} ${f(ring[i][1])}`;\n\t\td += 'Z';\n\t}\n\treturn d;\n}\n\n/** Perpendicular distance from `p` to the segment `a`–`b`. */\nfunction segmentDistance(p: Point, a: Point, b: Point): number {\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 === 0) return Math.hypot(p[0] - a[0], p[1] - a[1]);\n\tconst t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2));\n\treturn Math.hypot(p[0] - (a[0] + t * dx), p[1] - (a[1] + t * dy));\n}\n\nfunction rdp(points: Point[], tolerance: number): Point[] {\n\tif (points.length <= 2) return points;\n\tconst keep = new Uint8Array(points.length);\n\tkeep[0] = 1;\n\tkeep[points.length - 1] = 1;\n\tconst stack: [number, number][] = [[0, points.length - 1]];\n\twhile (stack.length) {\n\t\tconst [s, e] = stack.pop()!;\n\t\tlet maxDist = -1;\n\t\tlet index = -1;\n\t\tfor (let i = s + 1; i < e; i++) {\n\t\t\tconst dist = segmentDistance(points[i], points[s], points[e]);\n\t\t\tif (dist > maxDist) {\n\t\t\t\tmaxDist = dist;\n\t\t\t\tindex = i;\n\t\t\t}\n\t\t}\n\t\tif (index !== -1 && maxDist > tolerance) {\n\t\t\tkeep[index] = 1;\n\t\t\tstack.push([s, index], [index, e]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n/**\n * Simplifies a closed ring with Ramer–Douglas–Peucker at `tolerance`. Returns an empty\n * ring when fewer than three points survive.\n */\nexport function simplifyRing(ring: readonly Point[], tolerance: number): Point[] {\n\tif (ring.length <= 3 || !(tolerance > 0)) return [...ring];\n\t// Anchor on the point farthest from the first one so the closing seam is not lost.\n\tlet far = 0;\n\tlet farDist = -1;\n\tfor (let i = 1; i < ring.length; i++) {\n\t\tconst dist = Math.hypot(ring[i][0] - ring[0][0], ring[i][1] - ring[0][1]);\n\t\tif (dist > farDist) {\n\t\t\tfarDist = dist;\n\t\t\tfar = i;\n\t\t}\n\t}\n\tconst first = rdp(ring.slice(0, far + 1) as Point[], tolerance);\n\tconst second = rdp([...ring.slice(far), ring[0]] as Point[], tolerance);\n\tconst out = [...first.slice(0, -1), ...second.slice(0, -1)];\n\treturn out.length >= 3 ? out : [];\n}\n\nexport interface PolygonToPathOptions {\n\t/** Decimal places in the output (default 3). */\n\tprecision?: number;\n\t/** Ramer–Douglas–Peucker tolerance; `0` (default) keeps every vertex. */\n\tsimplify?: number;\n\t/** Added to every point before formatting (e.g. to make coordinates node-local). */\n\toffset?: { x: number; y: number };\n\t/**\n\t * `'lines'` (default) writes every ring as `M`/`L`/`Z`. `'fit'` fits cubic Béziers to each\n\t * ring (`fitPathData`), so flattened curves come back as smooth `C` curves while sharp\n\t * corners (turning more than `cornerAngleDeg`) and straight edges stay as they are.\n\t */\n\tcurves?: 'lines' | 'fit';\n\t/** Curve-fitting tolerance in path units for `curves: 'fit'` (default 0.25). */\n\tcurveTolerance?: number;\n\t/** Corner threshold in degrees for `curves: 'fit'` (default 30). */\n\tcornerAngleDeg?: number;\n}\n\n/**\n * Converts a multi-polygon (or a list of rings) to SVG path data using `M`/`L`/`Z`. Holes\n * keep their opposite orientation, so the path fills correctly with either fill rule.\n */\nexport function polygonToSvgPath(input: MultiPolygon | PolygonRing[], options: PolygonToPathOptions = {}): string {\n\tconst precision = options.precision ?? 3;\n\tconst f = (n: number) => formatNumber(n, precision);\n\tconst dx = options.offset?.x ?? 0;\n\tconst dy = options.offset?.y ?? 0;\n\tconst rings: Point[][] = [];\n\tconst fit = options.curves === 'fit';\n\tlet fitted = '';\n\tfor (const item of input as any[]) {\n\t\tconst list: Point[][] =\n\t\t\titem.length > 0 && Array.isArray(item[0]) && Array.isArray(item[0][0]) ? item : [item];\n\t\tfor (const ring of list) {\n\t\t\tlet r = ring;\n\t\t\tif (options.simplify && options.simplify > 0) r = simplifyRing(r, options.simplify);\n\t\t\tif (r.length < 3) continue;\n\t\t\tif (fit) {\n\t\t\t\tfitted += fitPathData(r, {\n\t\t\t\t\ttolerance: options.curveTolerance ?? 0.25,\n\t\t\t\t\tcornerAngleDeg: options.cornerAngleDeg,\n\t\t\t\t\tprecision,\n\t\t\t\t\toffset: { x: dx, y: dy }\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trings.push(dx || dy ? r.map(([x, y]) => [x + dx, y + dy] as Point) : r);\n\t\t}\n\t}\n\treturn fit ? fitted : ringsToPath(rings, f);\n}\n"],"mappings":";AAwCO,IAAM,0BAAgD;AAAA,EAC5D,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,IACN,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,IAC9B,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,EAC/B;AACD;AAEO,IAAM,0BAAgE;AAAA,EAC5E,UAAU;AAAA,EACV,QAAQ;AAAA,IACP,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,MACN,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,MAC9B,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,IAC/B;AAAA,EACD;AAAA,EACA,OAAO;AAAA,IACN,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,MACN,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,MAC9B,EAAE,QAAQ,GAAG,OAAO,UAAU;AAAA,IAC/B;AAAA,EACD;AA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