@pixerate/editor 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/agent/index.cjs +248 -29
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +18 -6
  4. package/dist/agent/index.d.ts +18 -6
  5. package/dist/agent/index.js +228 -9
  6. package/dist/agent/index.js.map +1 -1
  7. package/dist/{builtins-xs7rK6ys.d.cts → builtins-1kqwLUnb.d.cts} +1 -1
  8. package/dist/{builtins-D2nMtw2W.d.ts → builtins-BKYlHH1s.d.ts} +1 -1
  9. package/dist/chart/index.cjs +216 -3541
  10. package/dist/chart/index.cjs.map +1 -1
  11. package/dist/chart/index.d.cts +4 -494
  12. package/dist/chart/index.d.ts +4 -494
  13. package/dist/chart/index.js +155 -3480
  14. package/dist/chart/index.js.map +1 -1
  15. package/dist/{chunk-5VXI5GED.js → chunk-2CJ3LPYQ.js} +3 -3
  16. package/dist/{chunk-TXXNBDQX.cjs → chunk-2Q46FKZK.cjs} +113 -34
  17. package/dist/chunk-2Q46FKZK.cjs.map +1 -0
  18. package/dist/chunk-3JNRQVTS.cjs +521 -0
  19. package/dist/chunk-3JNRQVTS.cjs.map +1 -0
  20. package/dist/chunk-5TWIN7ZJ.js +113 -0
  21. package/dist/chunk-5TWIN7ZJ.js.map +1 -0
  22. package/dist/{chunk-PQFAHT5O.js → chunk-DQPBQXKG.js} +27 -94
  23. package/dist/chunk-DQPBQXKG.js.map +1 -0
  24. package/dist/{chunk-ZFBBVGCI.js → chunk-EKYHKQPG.js} +243 -243
  25. package/dist/{chunk-ZFBBVGCI.js.map → chunk-EKYHKQPG.js.map} +1 -1
  26. package/dist/{chunk-J3R2OWOE.cjs → chunk-FEMIVHN3.cjs} +610 -15
  27. package/dist/chunk-FEMIVHN3.cjs.map +1 -0
  28. package/dist/{chunk-C3NWJE3K.js → chunk-GJBIVWB2.js} +11 -672
  29. package/dist/chunk-GJBIVWB2.js.map +1 -0
  30. package/dist/chunk-GTZXF4BI.cjs +3424 -0
  31. package/dist/chunk-GTZXF4BI.cjs.map +1 -0
  32. package/dist/chunk-JOX6MJW4.cjs +674 -0
  33. package/dist/chunk-JOX6MJW4.cjs.map +1 -0
  34. package/dist/{chunk-REAGGLXS.js → chunk-JQ3BB3E6.js} +2 -2
  35. package/dist/{chunk-H4PICYNL.cjs → chunk-LNKZPIQD.cjs} +113 -180
  36. package/dist/chunk-LNKZPIQD.cjs.map +1 -0
  37. package/dist/chunk-OV7UAKIY.js +674 -0
  38. package/dist/chunk-OV7UAKIY.js.map +1 -0
  39. package/dist/{chunk-TK2XZK6Z.js → chunk-QFTVLEVN.js} +596 -1
  40. package/dist/chunk-QFTVLEVN.js.map +1 -0
  41. package/dist/{chunk-KRGXUQ2Y.js → chunk-T6XU4B54.js} +82 -3
  42. package/dist/chunk-T6XU4B54.js.map +1 -0
  43. package/dist/chunk-TGBCBQFV.cjs +113 -0
  44. package/dist/chunk-TGBCBQFV.cjs.map +1 -0
  45. package/dist/{chunk-SQC26VQV.cjs → chunk-UN33YOXW.cjs} +191 -191
  46. package/dist/{chunk-SQC26VQV.cjs.map → chunk-UN33YOXW.cjs.map} +1 -1
  47. package/dist/chunk-WBOAXDKD.js +3424 -0
  48. package/dist/chunk-WBOAXDKD.js.map +1 -0
  49. package/dist/{chunk-LYGEEDNR.cjs → chunk-XP5IUZUO.cjs} +242 -242
  50. package/dist/chunk-XP5IUZUO.cjs.map +1 -0
  51. package/dist/{chunk-BBRK6MOI.cjs → chunk-YU4WQE5M.cjs} +100 -100
  52. package/dist/{chunk-BBRK6MOI.cjs.map → chunk-YU4WQE5M.cjs.map} +1 -1
  53. package/dist/commands/index.d.cts +1 -1
  54. package/dist/commands/index.d.ts +1 -1
  55. package/dist/controller-ChjCCMLl.d.cts +822 -0
  56. package/dist/controller-DtbEo3om.d.ts +822 -0
  57. package/dist/export/index.cjs +4 -2
  58. package/dist/export/index.cjs.map +1 -1
  59. package/dist/export/index.d.cts +5 -1
  60. package/dist/export/index.d.ts +5 -1
  61. package/dist/export/index.js +3 -1
  62. package/dist/extensions/index.cjs +33 -4
  63. package/dist/extensions/index.cjs.map +1 -1
  64. package/dist/extensions/index.d.cts +4 -2
  65. package/dist/extensions/index.d.ts +4 -2
  66. package/dist/extensions/index.js +32 -3
  67. package/dist/{index-QrqMmZ75.d.cts → index-DoHqT1mq.d.cts} +203 -7
  68. package/dist/{index-CSUCQYAH.d.ts → index-YLZ0fKqE.d.ts} +203 -7
  69. package/dist/index.cjs +39 -13
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +9 -7
  72. package/dist/index.d.ts +9 -7
  73. package/dist/index.js +33 -7
  74. package/dist/index.js.map +1 -1
  75. package/dist/spreadsheet/index.cjs +4 -4
  76. package/dist/spreadsheet/index.js +3 -3
  77. package/package.json +1 -1
  78. package/dist/chunk-C3NWJE3K.js.map +0 -1
  79. package/dist/chunk-H4PICYNL.cjs.map +0 -1
  80. package/dist/chunk-J3R2OWOE.cjs.map +0 -1
  81. package/dist/chunk-KRGXUQ2Y.js.map +0 -1
  82. package/dist/chunk-LYGEEDNR.cjs.map +0 -1
  83. package/dist/chunk-NEOO6QJD.cjs +0 -1182
  84. package/dist/chunk-NEOO6QJD.cjs.map +0 -1
  85. package/dist/chunk-PQFAHT5O.js.map +0 -1
  86. package/dist/chunk-TK2XZK6Z.js.map +0 -1
  87. package/dist/chunk-TXXNBDQX.cjs.map +0 -1
  88. package/dist/types-BVqWm3d1.d.cts +0 -320
  89. package/dist/types-BVqWm3d1.d.ts +0 -320
  90. /package/dist/{chunk-5VXI5GED.js.map → chunk-2CJ3LPYQ.js.map} +0 -0
  91. /package/dist/{chunk-REAGGLXS.js.map → chunk-JQ3BB3E6.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/chart/numfmt.ts","../../src/chart/scale.ts","../../src/chart/date.ts","../../src/chart/stats.ts","../../src/chart/trend.ts","../../src/chart/layout-shared.ts","../../src/chart/layout-cartesian.ts","../../src/chart/layout-families.ts","../../src/chart/layout.ts","../../src/chart/summary.ts","../../src/chart/svg.ts","../../src/chart/sparkline.ts","../../src/chart/presets.ts","../../src/chart/recommend.ts","../../src/chart/controller.ts","../../src/chart/mermaid.ts","../../src/chart/schemas.ts","../../src/chart/commands.ts","../../src/chart/interaction.ts","../../src/chart/tools.ts","../../src/chart/stream.ts","../../src/chart/presence.ts"],"sourcesContent":["import { NumberFormat } from '../spreadsheet/numfmt/index.js';\n\n/**\n * A compiled spreadsheet number format code for chart labels, e.g. `#,##0.00`, `0.0%`,\n * `#,##0,,\"M\"`, `$#,##0;[Red]($#,##0);\"–\"` or `yyyy-mm-dd`. Backed by the spreadsheet's\n * format engine (`NumberFormat`), so charts and sheets write numbers the same way; colours\n * such as `[Red]` are ignored on charts.\n */\nexport interface ChartFormatCode {\n\tformat(value: number): string;\n\t/** The code is a date or time format (values are serial day numbers from 1899-12-30). */\n\tisDate: boolean;\n\t/** The code shows a percentage (values are multiplied by 100). */\n\tisPercent: boolean;\n}\n\n/** Compiles a spreadsheet format code (cached). */\nexport function compileChartFormatCode(code: string): ChartFormatCode {\n\tconst fmt = NumberFormat.parseCached(code);\n\treturn {\n\t\tisDate: fmt.isDate(),\n\t\tisPercent: fmt.isPercent(),\n\t\tformat: (value: number) => (Number.isFinite(value) ? fmt.formatNumber(value).text : '')\n\t};\n}\n\n/** Formats `value` with a spreadsheet format code. */\nexport function formatChartValueWithCode(value: number, code: string): string {\n\treturn compileChartFormatCode(code).format(value);\n}\n\n/** A spreadsheet serial day number (1 = 1900-01-01, with the 1900 leap-year quirk) as a UTC date. */\nexport function chartSerialToDate(serial: number): Date {\n\t// Day 60 is the fictional 1900-02-29; serials from 61 count from 1899-12-30, earlier ones from 1899-12-31.\n\tconst origin = serial < 61 ? Date.UTC(1899, 11, 31) : Date.UTC(1899, 11, 30);\n\treturn new Date(origin + Math.round(serial * 86400000));\n}\n\n/** A UTC date as a spreadsheet serial day number. */\nexport function chartDateToSerial(date: Date): number {\n\tconst serial = (date.getTime() - Date.UTC(1899, 11, 30)) / 86400000;\n\treturn serial < 61 ? serial - 1 : serial;\n}\n","import { formatChartValueWithCode } from './numfmt.js';\nimport type { ChartNumberFormat } from './types.js';\n\n/** A \"nice\" step (1, 2, 2.5 or 5 × 10ⁿ) for about `count` intervals over `span`. */\nexport function niceStep(span: number, count: number): number {\n\tif (!(span > 0) || !(count > 0)) return 1;\n\tconst raw = span / count;\n\tconst power = Math.pow(10, Math.floor(Math.log10(raw)));\n\tconst fraction = raw / power;\n\tconst nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 2.5 ? 2.5 : fraction <= 5 ? 5 : 10;\n\treturn nice * power;\n}\n\n/** Removes float noise such as 0.30000000000000004. */\nconst clean = (n: number) => (Math.abs(n) < 1e-12 ? 0 : Number(n.toPrecision(12)));\n\nexport interface NiceScale {\n\tmin: number;\n\tmax: number;\n\tstep: number;\n\tticks: number[];\n}\n\n/**\n * Extends `[min, max]` to round numbers and lists the ticks between them. Fixed ends\n * (`fixedMin` / `fixedMax`) are kept exactly; ticks then start at the first nice value\n * inside them.\n */\nexport function niceScale(min: number, max: number, count = 5, fixedMin: number | null = null, fixedMax: number | null = null): NiceScale {\n\t// Non-finite fixed ends fall back to the data range, and a non-finite data range to 0..1.\n\tif (fixedMin !== null && !Number.isFinite(fixedMin)) fixedMin = null;\n\tif (fixedMax !== null && !Number.isFinite(fixedMax)) fixedMax = null;\n\tlet lo = fixedMin ?? min;\n\tlet hi = fixedMax ?? max;\n\tif (!Number.isFinite(lo) || !Number.isFinite(hi)) {\n\t\tfixedMin = fixedMax = null;\n\t\tlo = 0;\n\t\thi = 1;\n\t}\n\tif (lo > hi) [lo, hi] = [hi, lo];\n\tif (lo === hi) {\n\t\tconst pad = lo === 0 ? 1 : Math.abs(lo) * 0.1;\n\t\t// A flat series at 0 grows upwards; anything else gets room on both free sides.\n\t\tif (fixedMin === null && lo !== 0) lo -= pad;\n\t\tif (fixedMax === null || lo === hi) hi += pad;\n\t}\n\t// Near ±Number.MAX_VALUE the span overflows to Infinity: halve it and double the step.\n\tconst span = hi - lo;\n\tconst step = Number.isFinite(span) ? niceStep(span, count) : niceStep(hi / 2 - lo / 2, count) * 2;\n\t// Rounding outwards can overflow too; keep the data end then.\n\tconst finiteOr = (n: number, fallback: number) => (Number.isFinite(n) ? n : fallback);\n\tconst niceMin = fixedMin ?? finiteOr(snap(Math.floor(lo / step + 1e-9) * step, step), lo);\n\tconst niceMax = fixedMax ?? finiteOr(snap(Math.ceil(hi / step - 1e-9) * step, step), hi);\n\t// Ticks are first + i·step (never a running sum, which stalls once step is below the\n\t// float spacing, e.g. near 1e16) and deduplicated where neighbours round to one float.\n\tconst firstIndex = Math.ceil(niceMin / step - 1e-9);\n\tconst lastIndex = Math.floor(niceMax / step + 1e-9);\n\tconst n = Math.min(999, Math.max(-1, lastIndex - firstIndex));\n\tconst ticks: number[] = [];\n\tfor (let i = 0; i <= n; i++) {\n\t\tconst t = snap((firstIndex + i) * step, step);\n\t\tif (Number.isFinite(t) && t !== ticks[ticks.length - 1]) ticks.push(t);\n\t}\n\treturn { min: niceMin, max: niceMax, step, ticks };\n}\n\n/** `clean`, unless that moves `n` by a noticeable part of `step` (large numbers such as 1e16 + 2). */\nfunction snap(n: number, step: number): number {\n\tconst c = clean(n);\n\treturn Math.abs(c - n) <= step * 1e-6 ? c : n;\n}\n\n/** Decimals needed to write ticks `step` apart exactly: 1 → 0, 2.5 → 1, 0.25 → 2 (at most 6). */\nexport function stepDecimals(step: number): number {\n\tif (!(step > 0) || !Number.isFinite(step)) return 0;\n\tfor (let d = 0; d < 6; d++) {\n\t\tconst scaled = step * Math.pow(10, d);\n\t\tif (Math.abs(scaled - Math.round(scaled)) < 1e-9) return d;\n\t}\n\treturn 6;\n}\n\n/** Decimals that show the leading digit of `value` (0.12 → 1, 0.012 → 2; at most 6). */\nfunction magnitudeDecimals(value: number): number {\n\tif (!(value > 0) || value >= 1) return 0;\n\treturn Math.min(6, Math.max(0, Math.ceil(-Math.log10(value) - 1e-9)));\n}\n\nconst COMPACT = [\n\t{ value: 1e12, suffix: 'T' },\n\t{ value: 1e9, suffix: 'B' },\n\t{ value: 1e6, suffix: 'M' },\n\t{ value: 1e3, suffix: 'K' }\n];\n\nfunction grouped(value: number, decimals: number): string {\n\tconst fixed = Math.abs(value).toFixed(decimals);\n\tconst [int, frac] = fixed.split('.');\n\tconst withCommas = int.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n\treturn `${value < 0 && Number(fixed) !== 0 ? '-' : ''}${withCommas}${frac ? `.${frac}` : ''}`;\n}\n\nconst CURRENCY_SYMBOLS: Record<string, string> = { USD: '$', EUR: '€', GBP: '£', JPY: '¥', CNY: '¥', INR: '₹', AUD: 'A$', CAD: 'C$' };\n\n/**\n * Writes a number for a chart label. Locale-independent (so labels and tests are the same\n * everywhere): `,` thousands, `.` decimals. `decimals` defaults to `fallbackDecimals`\n * (e.g. from the tick step), else up to 2 trimmed.\n */\nexport function formatChartNumber(value: number | null | undefined, format: ChartNumberFormat = {}, fallbackDecimals?: number): string {\n\tif (value === null || value === undefined || !Number.isFinite(value)) return '';\n\tif (format.code) return `${format.prefix ?? ''}${formatChartValueWithCode(value, format.code)}${format.suffix ?? ''}`;\n\tconst style = format.style ?? 'number';\n\tlet body: string;\n\tconst decimalsFor = (v: number) => {\n\t\tif (format.decimals !== undefined) return format.decimals;\n\t\tif (fallbackDecimals !== undefined) return fallbackDecimals;\n\t\treturn Number.isInteger(v) ? 0 : Math.abs(v) < 1 ? Math.min(4, Math.max(2, magnitudeDecimals(Math.abs(v)) + 1)) : 2;\n\t};\n\tconst trim = (s: string) => (format.decimals === undefined && fallbackDecimals === undefined && s.includes('.') ? s.replace(/\\.?0+$/, '') : s);\n\tif (style === 'percent') {\n\t\tconst v = value * 100;\n\t\tconst d = format.decimals ?? (fallbackDecimals !== undefined ? Math.max(0, fallbackDecimals - 2) : Number.isInteger(clean(v)) ? 0 : 1);\n\t\tbody = `${grouped(clean(v), d)}%`;\n\t} else if (style === 'compact') {\n\t\tconst unit = COMPACT.find((u) => Math.abs(value) >= u.value);\n\t\tif (unit) {\n\t\t\tconst v = value / unit.value;\n\t\t\tconst d = format.decimals ?? (Math.abs(v) >= 100 || Number.isInteger(clean(v)) ? 0 : 1);\n\t\t\tbody = `${trim(grouped(v, d))}${unit.suffix}`;\n\t\t} else body = trim(grouped(value, decimalsFor(value)));\n\t} else if (style === 'currency') {\n\t\tconst code = (format.currency || 'USD').toUpperCase();\n\t\tconst symbol = CURRENCY_SYMBOLS[code] ?? `${code} `;\n\t\tconst d = format.decimals ?? (fallbackDecimals !== undefined ? fallbackDecimals : Number.isInteger(value) ? 0 : 2);\n\t\tconst s = grouped(Math.abs(value), d);\n\t\tbody = `${value < 0 ? '-' : ''}${symbol}${s}`;\n\t} else body = trim(grouped(value, decimalsFor(value)));\n\treturn `${format.prefix ?? ''}${body}${format.suffix ?? ''}`;\n}\n\n/** Linear map from `domain` to `range`. */\nexport function linearMap(value: number, domain: readonly [number, number], range: readonly [number, number]): number {\n\tconst [d0, d1] = domain;\n\tconst [r0, r1] = range;\n\tif (d1 === d0) return (r0 + r1) / 2;\n\treturn r0 + ((value - d0) / (d1 - d0)) * (r1 - r0);\n}\n","// The label ladder follows `ruler_steps` in filmcraft-main/crates/ui-egui/src/panels/timeline.rs (the first\n// step on a ladder that keeps labels a minimum distance apart) (MIT OR Apache-2.0, © ArtCraft Team and\n// contributors), adapted to calendar units. See THIRD_PARTY_NOTICES.md.\n\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n/**\n * Reads a category label as a UTC date: `2024`, `2024-03`, `2024-03-05`, ISO date-times,\n * `2024/03/05`, `Mar 2024` and `5 Mar 2024`. Returns milliseconds since the epoch, or `null`.\n */\nexport function parseChartDate(label: string): number | null {\n\tconst text = label.trim();\n\tlet m = /^(\\d{4})$/.exec(text);\n\tif (m) return Date.UTC(Number(m[1]), 0, 1);\n\tm = /^(\\d{4})[-/](\\d{1,2})$/.exec(text);\n\tif (m) return valid(Number(m[1]), Number(m[2]) - 1, 1);\n\tm = /^(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})(?:[T ](\\d{1,2}):(\\d{2})(?::(\\d{2}))?(?:\\.\\d+)?(Z|[+-]\\d{2}:?\\d{2})?)?$/.exec(text);\n\tif (m) {\n\t\tif (m[4] !== undefined) {\n\t\t\tconst t = Date.parse(text.replace(' ', 'T').replace(/\\//g, '-') + (m[7] ? '' : 'Z'));\n\t\t\treturn Number.isFinite(t) ? t : null;\n\t\t}\n\t\treturn valid(Number(m[1]), Number(m[2]) - 1, Number(m[3]));\n\t}\n\tm = /^(?:(\\d{1,2})\\s+)?([A-Za-z]{3})[a-z]*\\.?,?\\s+(\\d{4})$/.exec(text);\n\tif (m) {\n\t\tconst month = MONTHS.findIndex((x) => x.toLowerCase() === m![2].toLowerCase());\n\t\tif (month >= 0) return valid(Number(m[3]), month, m[1] ? Number(m[1]) : 1);\n\t}\n\treturn null;\n}\n\nfunction valid(y: number, mo: number, d: number): number | null {\n\tconst t = Date.UTC(y, mo, d);\n\tconst date = new Date(t);\n\treturn date.getUTCFullYear() === y && date.getUTCMonth() === mo && date.getUTCDate() === d ? t : null;\n}\n\n/** Calendar steps from fine to coarse. */\nexport const CHART_DATE_STEPS = [\n\t{ unit: 'day', count: 1 },\n\t{ unit: 'day', count: 2 },\n\t{ unit: 'week', count: 1 },\n\t{ unit: 'week', count: 2 },\n\t{ unit: 'month', count: 1 },\n\t{ unit: 'month', count: 3 },\n\t{ unit: 'month', count: 6 },\n\t{ unit: 'year', count: 1 },\n\t{ unit: 'year', count: 2 },\n\t{ unit: 'year', count: 5 },\n\t{ unit: 'year', count: 10 },\n\t{ unit: 'year', count: 25 },\n\t{ unit: 'year', count: 50 },\n\t{ unit: 'year', count: 100 }\n] as const;\n\nexport type ChartDateStep = (typeof CHART_DATE_STEPS)[number];\n\n/** Which bucket of `step` a time falls in (equal buckets share a label). */\nfunction bucket(t: number, step: ChartDateStep): number {\n\tconst d = new Date(t);\n\tconst y = d.getUTCFullYear();\n\tswitch (step.unit) {\n\t\tcase 'day':\n\t\t\treturn Math.floor(Math.floor(t / 86400000) / step.count);\n\t\tcase 'week':\n\t\t\t// Weeks start on Monday (1970-01-05 was one).\n\t\t\treturn Math.floor(Math.floor((t / 86400000 - 4) / 7) / step.count);\n\t\tcase 'month':\n\t\t\treturn Math.floor((y * 12 + d.getUTCMonth()) / step.count);\n\t\tcase 'year':\n\t\t\treturn Math.floor(y / step.count);\n\t}\n}\n\n/** A label for a date at `step`: years as `2024`, months as `Mar 2024` (`Mar` within a year), days as `5 Mar`. */\nexport function formatChartDate(t: number, step: ChartDateStep, previous: number | null = null): string {\n\tconst d = new Date(t);\n\tconst y = d.getUTCFullYear();\n\tconst mo = MONTHS[d.getUTCMonth()];\n\tconst sameYear = previous !== null && new Date(previous).getUTCFullYear() === y;\n\tif (step.unit === 'year') return String(y);\n\tif (step.unit === 'month') return sameYear ? mo : `${mo} ${y}`;\n\treturn sameYear ? `${d.getUTCDate()} ${mo}` : `${d.getUTCDate()} ${mo} ${y}`;\n}\n\nexport interface ChartDateLabels {\n\t/** The calendar step chosen. */\n\tstep: ChartDateStep;\n\t/** Category indexes that get a label (the first category in each bucket). */\n\tindexes: number[];\n\t/** Label text by category index. */\n\tlabels: Map<number, string>;\n}\n\n/**\n * Picks the finest calendar step whose labels fit along a category axis. Categories are\n * evenly spaced (`band` pixels each), so a label goes on the first category of each bucket,\n * and the step is the first on the ladder whose neighbouring labels are at least their own\n * width plus `gap` apart. Returns `null` when fewer than half the categories read as dates.\n */\nexport function chartDateLabels(categories: readonly string[], band: number, measure: (text: string) => number, gap = 10): ChartDateLabels | null {\n\tconst times = categories.map(parseChartDate);\n\tif (times.filter((t) => t !== null).length < Math.max(1, categories.length / 2)) return null;\n\t// Steps much finer than the data's own spacing would only relabel the same points.\n\tconst present = times.filter((t): t is number => t !== null).sort((x, y) => x - y);\n\tconst gaps = present.slice(1).map((t, i) => t - present[i]).filter((g) => g > 0).sort((x, y) => x - y);\n\tconst spacing = gaps.length ? gaps[Math.floor(gaps.length / 2)] : 0;\n\tconst DAY = 86400000;\n\tconst length = (step: ChartDateStep) => step.count * (step.unit === 'day' ? DAY : step.unit === 'week' ? 7 * DAY : step.unit === 'month' ? 30 * DAY : 365 * DAY);\n\tfor (const step of CHART_DATE_STEPS) {\n\t\tif (length(step) < spacing * 0.5 && step !== CHART_DATE_STEPS[CHART_DATE_STEPS.length - 1]) continue;\n\t\tconst indexes: number[] = [];\n\t\tconst labels = new Map<number, string>();\n\t\tlet last: number | null = null;\n\t\tlet lastTime: number | null = null;\n\t\ttimes.forEach((t, i) => {\n\t\t\tif (t === null) return;\n\t\t\tconst b = bucket(t, step);\n\t\t\tif (b === last) return;\n\t\t\tlast = b;\n\t\t\tindexes.push(i);\n\t\t\tlabels.set(i, formatChartDate(t, step, lastTime));\n\t\t\tlastTime = t;\n\t\t});\n\t\tlet fits = true;\n\t\tfor (let k = 1; k < indexes.length && fits; k++) {\n\t\t\tconst a = labels.get(indexes[k - 1])!;\n\t\t\tconst b = labels.get(indexes[k])!;\n\t\t\tif ((indexes[k] - indexes[k - 1]) * band < (measure(a) + measure(b)) / 2 + gap) fits = false;\n\t\t}\n\t\tif (fits || step === CHART_DATE_STEPS[CHART_DATE_STEPS.length - 1]) return { step, indexes, labels };\n\t}\n\treturn null;\n}\n","// Portions ported from gridcraft-main/crates/chart/src/render.rs (`histogram` binning, `quantile` and\n// `box_whisker` statistics, `squarify` treemap layout, `decimate`) (MIT OR Apache-2.0, © ArtCraft Team and\n// contributors). See THIRD_PARTY_NOTICES.md.\nimport type { ChartRect, ChartValue } from './types.js';\n\nexport interface ChartHistogramBin {\n\t/** Lower edge (exclusive, except for the first bin). */\n\tfrom: number;\n\t/** Upper edge (inclusive). */\n\tto: number;\n\tcount: number;\n}\n\n/**\n * Bins values into `bins` equal-width bins (default √n, from 1 to 100). Bins are\n * right-inclusive, the first closed on both sides, so a value on an edge belongs to the bin\n * that ends there. Gaps and non-finite values are ignored.\n */\nexport function chartHistogram(values: readonly ChartValue[], bins: number | null = null): ChartHistogramBin[] {\n\tconst vals = values.filter((v): v is number => v !== null && Number.isFinite(v));\n\tif (!vals.length) return [];\n\tlet lo = Infinity;\n\tlet hi = -Infinity;\n\tfor (const v of vals) {\n\t\tlo = Math.min(lo, v);\n\t\thi = Math.max(hi, v);\n\t}\n\tconst span = hi - lo;\n\tlet count = bins ?? Math.max(1, Math.min(100, Math.ceil(Math.sqrt(vals.length))));\n\tif (!(span > 0)) count = 1;\n\tconst width = count === 1 && !(span > 0) ? 1 : span / count;\n\tconst edges = Array.from({ length: count }, (_, b) => (b + 1 === count ? Math.max(hi, lo + b * width) : lo + (b + 1) * width));\n\tconst counts = Array<number>(count).fill(0);\n\tfor (const v of vals) {\n\t\t// First edge >= v (binary search).\n\t\tlet a = 0;\n\t\tlet z = count;\n\t\twhile (a < z) {\n\t\t\tconst mid = (a + z) >> 1;\n\t\t\tif (edges[mid] < v) a = mid + 1;\n\t\t\telse z = mid;\n\t\t}\n\t\tcounts[Math.min(a, count - 1)]++;\n\t}\n\treturn counts.map((c, b) => ({ from: clean(lo + b * width), to: clean(edges[b]), count: c }));\n}\n\nconst clean = (n: number) => (Math.abs(n) < 1e-12 ? 0 : Number(n.toPrecision(12)));\n\n/** The `q` quantile (0–1) of sorted values, interpolating linearly between ranks (`q·(n-1)`). */\nexport function chartQuantile(sorted: readonly number[], q: number): number {\n\tconst n = sorted.length;\n\tif (!n) return 0;\n\tconst pos = q * (n - 1);\n\tconst i = Math.floor(pos);\n\tconst a = sorted[i];\n\tconst b = sorted[i + 1] ?? a;\n\treturn a + (b - a) * (pos - i);\n}\n\nexport interface ChartBoxStats {\n\tmin: number;\n\tmax: number;\n\tq1: number;\n\tmedian: number;\n\tq3: number;\n\tmean: number;\n\t/** Whisker ends: the furthest values within 1.5 × IQR of the box. */\n\tlowerWhisker: number;\n\tupperWhisker: number;\n\t/** Values beyond the whiskers. */\n\toutliers: number[];\n\tcount: number;\n}\n\n/** Box-and-whisker statistics (Tukey fences at 1.5 × IQR); `null` without values. */\nexport function chartBoxStats(values: readonly ChartValue[]): ChartBoxStats | null {\n\tconst v = values.filter((x): x is number => x !== null && Number.isFinite(x)).sort((a, b) => a - b);\n\tif (!v.length) return null;\n\tconst q1 = chartQuantile(v, 0.25);\n\tconst median = chartQuantile(v, 0.5);\n\tconst q3 = chartQuantile(v, 0.75);\n\tconst iqr = q3 - q1;\n\tconst lo = q1 - 1.5 * iqr;\n\tconst hi = q3 + 1.5 * iqr;\n\treturn {\n\t\tmin: v[0],\n\t\tmax: v[v.length - 1],\n\t\tq1,\n\t\tmedian,\n\t\tq3,\n\t\tmean: v.reduce((t, x) => t + x, 0) / v.length,\n\t\tlowerWhisker: v.find((x) => x >= lo) ?? q1,\n\t\tupperWhisker: [...v].reverse().find((x) => x <= hi) ?? q3,\n\t\toutliers: v.filter((x) => x < lo || x > hi),\n\t\tcount: v.length\n\t};\n}\n\n/** Squarified treemap (Bruls et al.): positive `values` packed into `rect`, largest first. Returns one rect per input index (zero-size for values ≤ 0). */\nexport function chartSquarify(values: readonly number[], rect: ChartRect): ChartRect[] {\n\tconst out: ChartRect[] = values.map(() => ({ x: rect.x, y: rect.y, width: 0, height: 0 }));\n\tconst items = values\n\t\t.map((v, i) => [i, v] as [number, number])\n\t\t.filter(([, v]) => v > 0 && Number.isFinite(v))\n\t\t.sort((a, b) => b[1] - a[1]);\n\tconst total = items.reduce((t, [, v]) => t + v, 0);\n\tconst area = rect.width * rect.height;\n\tif (!(total > 0 && area > 0)) return out;\n\tconst scale = area / total;\n\tconst rem = { ...rect };\n\tlet row: [number, number][] = [];\n\tconst worst = (r: number[], side: number) => {\n\t\tconst s = r.reduce((t, v) => t + v, 0);\n\t\tif (s <= 0 || side <= 0) return Infinity;\n\t\tconst mn = Math.min(...r);\n\t\tconst mx = Math.max(...r);\n\t\treturn Math.max((side * side * mx) / (s * s), (s * s) / (side * side * mn));\n\t};\n\tconst layoutRow = (r: [number, number][]) => {\n\t\tconst s = r.reduce((t, [, a]) => t + a, 0);\n\t\tif (s <= 0) return;\n\t\tif (rem.width >= rem.height) {\n\t\t\tconst cw = s / Math.max(1e-6, rem.height);\n\t\t\tlet y = rem.y;\n\t\t\tfor (const [j, a] of r) {\n\t\t\t\tconst h = a / Math.max(1e-6, cw);\n\t\t\t\tout[j] = { x: rem.x, y, width: cw, height: h };\n\t\t\t\ty += h;\n\t\t\t}\n\t\t\trem.x += cw;\n\t\t\trem.width = Math.max(0, rem.width - cw);\n\t\t} else {\n\t\t\tconst rh = s / Math.max(1e-6, rem.width);\n\t\t\tlet x = rem.x;\n\t\t\tfor (const [j, a] of r) {\n\t\t\t\tconst w = a / Math.max(1e-6, rh);\n\t\t\t\tout[j] = { x, y: rem.y, width: w, height: rh };\n\t\t\t\tx += w;\n\t\t\t}\n\t\t\trem.y += rh;\n\t\t\trem.height = Math.max(0, rem.height - rh);\n\t\t}\n\t};\n\tlet i = 0;\n\twhile (i < items.length) {\n\t\tconst [j, v] = items[i];\n\t\tconst a = v * scale;\n\t\tconst side = Math.min(rem.width, rem.height);\n\t\tconst cur = row.map(([, x]) => x);\n\t\tif (!row.length || worst([...cur, a], side) <= worst(cur, side)) {\n\t\t\trow.push([j, a]);\n\t\t\ti++;\n\t\t} else {\n\t\t\tlayoutRow(row);\n\t\t\trow = [];\n\t\t}\n\t}\n\tif (row.length) layoutRow(row);\n\treturn out;\n}\n\n/**\n * Thins a long polyline (sorted by x) to the first, lowest, highest and last point of each\n * pixel column, which draws identically. Returns the input when it has `max` points or fewer.\n */\nexport function decimateChartPoints<T extends { x: number; y: number }>(points: readonly T[], max = 2000): T[] {\n\tif (points.length <= max) return [...points];\n\tconst out: T[] = [];\n\tlet i = 0;\n\twhile (i < points.length) {\n\t\tconst col = Math.floor(points[i].x);\n\t\tconst start = i;\n\t\tlet mn = i;\n\t\tlet mx = i;\n\t\tlet k = i + 1;\n\t\twhile (k < points.length && Math.floor(points[k].x) === col) {\n\t\t\tif (points[k].y < points[mn].y) mn = k;\n\t\t\tif (points[k].y > points[mx].y) mx = k;\n\t\t\tk++;\n\t\t}\n\t\tconst end = k - 1;\n\t\tfor (const idx of [...new Set([start, mn, mx, end])].sort((a, b) => a - b)) out.push(points[idx]);\n\t\ti = k;\n\t}\n\treturn out;\n}\n\nexport interface ChartSeriesSummary {\n\tid: string;\n\tname: string;\n\t/** Values present (not gaps). */\n\tcount: number;\n\tgaps: number;\n\tmin: number | null;\n\tmax: number | null;\n\tmean: number | null;\n\tsum: number | null;\n\t/** Category label of the minimum and maximum. */\n\tminAt: string | null;\n\tmaxAt: string | null;\n\t/** Direction of a least-squares line through the values in order. */\n\ttrend: 'rising' | 'falling' | 'flat' | null;\n\t/** Relative change from the first to the last value, e.g. 0.25 for +25%. */\n\tchange: number | null;\n}\n\nconst round = (n: number) => Number(n.toPrecision(6));\n\n/** Numbers about one series, for agents that check a chart without looking at it. */\nexport function summarizeChartSeries(series: { id: string; name: string; values: readonly ChartValue[] }, categories: readonly string[]): ChartSeriesSummary {\n\tconst present = series.values.map((v, i) => [i, v] as const).filter((p): p is readonly [number, number] => p[1] !== null && Number.isFinite(p[1]));\n\tconst base: ChartSeriesSummary = { id: series.id, name: series.name, count: present.length, gaps: series.values.length - present.length, min: null, max: null, mean: null, sum: null, minAt: null, maxAt: null, trend: null, change: null };\n\tif (!present.length) return base;\n\tlet lo = present[0];\n\tlet hi = present[0];\n\tlet sum = 0;\n\tfor (const p of present) {\n\t\tif (p[1] < lo[1]) lo = p;\n\t\tif (p[1] > hi[1]) hi = p;\n\t\tsum += p[1];\n\t}\n\tconst mean = sum / present.length;\n\tlet trend: ChartSeriesSummary['trend'] = null;\n\tif (present.length >= 2) {\n\t\tconst mx = present.reduce((t, p) => t + p[0], 0) / present.length;\n\t\tlet sxy = 0;\n\t\tlet sxx = 0;\n\t\tfor (const [i, v] of present) {\n\t\t\tsxy += (i - mx) * (v - mean);\n\t\t\tsxx += (i - mx) ** 2;\n\t\t}\n\t\tconst slope = sxx ? sxy / sxx : 0;\n\t\tconst spread = hi[1] - lo[1];\n\t\t// Flat when the fitted line moves less than 5% of the spread over the whole series.\n\t\tconst travel = Math.abs(slope * (present[present.length - 1][0] - present[0][0]));\n\t\ttrend = !spread || travel < spread * 0.05 ? 'flat' : slope > 0 ? 'rising' : 'falling';\n\t}\n\tconst first = present[0][1];\n\tconst last = present[present.length - 1][1];\n\treturn {\n\t\t...base,\n\t\tmin: round(lo[1]),\n\t\tmax: round(hi[1]),\n\t\tmean: round(mean),\n\t\tsum: round(sum),\n\t\tminAt: categories[lo[0]] ?? String(lo[0]),\n\t\tmaxAt: categories[hi[0]] ?? String(hi[0]),\n\t\ttrend,\n\t\tchange: present.length >= 2 && first !== 0 ? round((last - first) / Math.abs(first)) : null\n\t};\n}\n","// Portions ported from gridcraft-main/crates/chart/src/trend.rs (MIT OR Apache-2.0, © ArtCraft Team and\n// contributors). See THIRD_PARTY_NOTICES.md.\nimport type { ChartTrendline, ChartTrendlineType } from './types.js';\n\n/**\n * A fitted regression trendline. Exponential, logarithmic and power fits are linear fits of\n * transformed data (`ln y ~ x`, `y ~ ln x`, `ln y ~ ln x`), as spreadsheets document them;\n * points the transform cannot take (values ≤ 0) are skipped, and R² is for the transformed fit.\n */\nexport interface ChartTrendFit {\n\ttype: Exclude<ChartTrendlineType, 'moving-average'>;\n\t/** Coefficients `c0…cd` of `Y = Σ cₖ·Xᵏ` in the transformed variables. */\n\tcoefficients: number[];\n\t/** Coefficient of determination; `null` when undefined (all y equal). */\n\tr2: number | null;\n\t/** The equation as a label, e.g. `y = 0.5x² - 2x + 1` or `y = 3e^(0.2x)`. */\n\tequation: string;\n\t/** Number of points used. */\n\tpoints: number;\n\t/** The fitted y at `x`, or `null` outside the fit's domain (x ≤ 0 for log and power). */\n\tevaluate(x: number): number | null;\n}\n\nconst degree = (t: ChartTrendline): number => (t.type === 'polynomial' ? Math.max(2, Math.min(6, t.order ?? 2)) : 1);\nconst logX = (type: ChartTrendlineType) => type === 'logarithmic' || type === 'power';\nconst logY = (type: ChartTrendlineType) => type === 'exponential' || type === 'power';\n\n/**\n * Fits `trendline` to the points. Returns `null` for moving averages (see\n * `chartMovingAverage`) and degenerate data: too few usable points, all x equal, or a\n * singular system.\n */\nexport function fitChartTrendline(trendline: ChartTrendline, points: ReadonlyArray<readonly [number, number]>): ChartTrendFit | null {\n\tconst type = trendline.type;\n\tif (type === 'moving-average') return null;\n\tconst d = degree(trendline);\n\tconst data = points\n\t\t.filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y) && (!logX(type) || x > 0) && (!logY(type) || y > 0))\n\t\t.map(([x, y]) => [logX(type) ? Math.log(x) : x, logY(type) ? Math.log(y) : y] as const);\n\tif (data.length < 2 || data.length <= d) return null;\n\t// A fixed intercept applies to linear, exponential and polynomial fits; it fixes Y at x = 0.\n\tlet fixed: number | null = null;\n\tconst b = trendline.intercept;\n\tif (b !== undefined && b !== null && Number.isFinite(b)) {\n\t\tif (type === 'linear' || type === 'polynomial') fixed = b;\n\t\telse if (type === 'exponential' && b > 0) fixed = Math.log(b);\n\t}\n\tconst n = data.length;\n\tconst center = fixed !== null ? 0 : data.reduce((t, p) => t + p[0], 0) / n;\n\tconst scale = data.reduce((m, p) => Math.max(m, Math.abs(p[0] - center)), 0);\n\tif (!(Number.isFinite(scale) && scale > 0)) return null;\n\tconst first = fixed !== null ? 1 : 0;\n\tconst b0 = fixed ?? 0;\n\t// Normal equations over the unknown powers first..d of u = (x - center) / scale.\n\tconst m = d + 1 - first;\n\tconst ata = Array.from({ length: m }, () => Array<number>(m).fill(0));\n\tconst aty = Array<number>(m).fill(0);\n\tfor (const [x, y] of data) {\n\t\tconst u = (x - center) / scale;\n\t\tconst pows = Array.from({ length: m }, (_, k) => Math.pow(u, k + first));\n\t\tfor (let i = 0; i < m; i++) {\n\t\t\taty[i] += pows[i] * (y - b0);\n\t\t\tfor (let j = 0; j < m; j++) ata[i][j] += pows[i] * pows[j];\n\t\t}\n\t}\n\tconst sol = solve(ata, aty);\n\tif (!sol) return null;\n\tconst a = Array<number>(d + 1).fill(b0);\n\tsol.forEach((v, k) => (a[k + first] = v));\n\tconst coefficients = expand(a, center, scale);\n\tif (!coefficients) return null;\n\tconst poly = (x: number) => {\n\t\tconst u = (x - center) / scale;\n\t\treturn a.reduceRight((acc, c) => acc * u + c, 0);\n\t};\n\tconst mean = data.reduce((t, p) => t + p[1], 0) / n;\n\tlet ssRes = 0;\n\tlet ssTot = 0;\n\tfor (const [x, y] of data) {\n\t\tssRes += (y - poly(x)) ** 2;\n\t\t// A fixed intercept is LINEST(y - b, x, FALSE): the total sum of squares is not centred.\n\t\tssTot += fixed !== null ? (y - b0) ** 2 : (y - mean) ** 2;\n\t}\n\tconst r2 = ssTot > 0 && Number.isFinite(ssTot) && Number.isFinite(ssRes) ? 1 - ssRes / ssTot : null;\n\treturn {\n\t\ttype,\n\t\tcoefficients,\n\t\tr2,\n\t\tequation: equationText(type, coefficients),\n\t\tpoints: n,\n\t\tevaluate(x: number) {\n\t\t\tlet xx = x;\n\t\t\tif (logX(type)) {\n\t\t\t\tif (!(x > 0)) return null;\n\t\t\t\txx = Math.log(x);\n\t\t\t}\n\t\t\tconst p = poly(xx);\n\t\t\tconst y = logY(type) ? Math.exp(p) : p;\n\t\t\treturn Number.isFinite(y) ? y : null;\n\t\t}\n\t};\n}\n\n/** Gaussian elimination with partial pivoting; `null` when (nearly) singular. */\nfunction solve(a: number[][], b: number[]): number[] | null {\n\tconst n = b.length;\n\tconst big = a.flat().reduce((m, v) => Math.max(m, Math.abs(v)), 0);\n\tif (!(Number.isFinite(big) && big > 0)) return null;\n\tfor (let col = 0; col < n; col++) {\n\t\tlet piv = col;\n\t\tfor (let r = col + 1; r < n; r++) if (Math.abs(a[r][col]) > Math.abs(a[piv][col])) piv = r;\n\t\t[a[col], a[piv]] = [a[piv], a[col]];\n\t\t[b[col], b[piv]] = [b[piv], b[col]];\n\t\tconst p = a[col][col];\n\t\tif (!Number.isFinite(p) || Math.abs(p) <= big * 1e-13) return null;\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tconst f = a[r][col] / p;\n\t\t\tfor (let c = col; c < n; c++) a[r][c] -= f * a[col][c];\n\t\t\tb[r] -= f * b[col];\n\t\t}\n\t}\n\tconst x = Array<number>(n).fill(0);\n\tfor (let r = n - 1; r >= 0; r--) {\n\t\tlet s = 0;\n\t\tfor (let c = r + 1; c < n; c++) s += a[r][c] * x[c];\n\t\tx[r] = (b[r] - s) / a[r][r];\n\t}\n\treturn x.every(Number.isFinite) ? x : null;\n}\n\n/** Coefficients in X of `Σ aₖ·((X - c) / s)ᵏ` (binomial expansion). */\nfunction expand(a: number[], c: number, s: number): number[] | null {\n\tconst out = Array<number>(a.length).fill(0);\n\ta.forEach((ak, k) => {\n\t\tconst lead = ak / Math.pow(s, k);\n\t\tlet binom = 1;\n\t\tfor (let j = 0; j <= k; j++) {\n\t\t\tout[j] += lead * binom * Math.pow(-c, k - j);\n\t\t\tbinom = (binom * (k - j)) / (j + 1);\n\t\t}\n\t});\n\treturn out.every(Number.isFinite) ? out : null;\n}\n\nconst POWERS = ['', 'x', 'x²', 'x³', 'x⁴', 'x⁵', 'x⁶'];\n\nfunction equationText(type: ChartTrendFit['type'], coef: number[]): string {\n\tconst c0 = coef[0] ?? 0;\n\tconst c1 = coef[1] ?? 0;\n\tif (type === 'exponential') return `y = ${trendNumberText(Math.exp(c0))}e^(${trendNumberText(c1)}x)`;\n\tif (type === 'power') return `y = ${trendNumberText(Math.exp(c0))}x^${trendNumberText(c1)}`;\n\tif (type === 'logarithmic') return terms([[c1, 'ln(x)'], [c0, '']]);\n\treturn terms(coef.map((c, k) => [c, POWERS[k] ?? 'x'] as [number, string]).reverse());\n}\n\n/** `y = a·t1 ± b·t2 …`, skipping terms whose coefficient shows as 0 and unit coefficients on powers of x. */\nfunction terms(parts: [number, string][]): string {\n\tlet s = 'y = ';\n\tlet first = true;\n\tfor (const [c, t] of parts) {\n\t\tconst txt = trendNumberText(Math.abs(c));\n\t\tif (txt === '0') continue;\n\t\tconst neg = c < 0;\n\t\tif (first) s += neg ? '-' : '';\n\t\telse s += neg ? ' - ' : ' + ';\n\t\tif (txt !== '1' || !t) s += txt;\n\t\ts += t;\n\t\tfirst = false;\n\t}\n\treturn first ? `${s}0` : s;\n}\n\n/** A coefficient as trendline labels show it: up to four decimals, scientific when tiny or huge. */\nexport function trendNumberText(v: number): string {\n\tif (!Number.isFinite(v)) return '#NUM!';\n\tconst a = Math.abs(v);\n\tif (a === 0) return '0';\n\tif (a < 1e-4 || a >= 1e11) {\n\t\tconst [mant, exp] = v.toExponential(4).split('e');\n\t\tconst e = Number(exp);\n\t\treturn `${trimZeros(mant)}E${e < 0 ? '-' : '+'}${String(Math.abs(e)).padStart(2, '0')}`;\n\t}\n\tconst s = trimZeros(v.toFixed(4));\n\treturn s === '-0' ? '0' : s;\n}\n\nconst trimZeros = (s: string) => (s.includes('.') ? s.replace(/0+$/, '').replace(/\\.$/, '') : s);\n\n/**\n * Moving average of `period` consecutive points in plotted order: point `i` (from\n * `period - 1`) is `(xᵢ, mean(yᵢ₋ₚ₊₁ … yᵢ))`. Empty when there are fewer points than `period`.\n */\nexport function chartMovingAverage(points: ReadonlyArray<readonly [number, number]>, period: number): [number, number][] {\n\tconst p = Math.max(2, Math.min(1000, Math.round(period) || 2));\n\tconst pts = points.filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y));\n\tconst out: [number, number][] = [];\n\tlet sum = 0;\n\tpts.forEach(([x, y], i) => {\n\t\tsum += y;\n\t\tif (i >= p) sum -= pts[i - p][1];\n\t\tif (i >= p - 1) out.push([x, sum / p]);\n\t});\n\treturn out;\n}\n\n/** The legend name spreadsheets give a trendline, e.g. `Linear (Sales)`. */\nexport function chartTrendlineName(trendline: ChartTrendline, seriesName: string): string {\n\tif (trendline.name) return trendline.name;\n\tconst kind: Record<ChartTrendlineType, string> = {\n\t\tlinear: 'Linear',\n\t\texponential: 'Expon.',\n\t\tlogarithmic: 'Log.',\n\t\tpolynomial: 'Poly.',\n\t\tpower: 'Power',\n\t\t'moving-average': `${Math.max(2, trendline.period ?? 2)} per. Mov. Avg.`\n\t};\n\treturn `${kind[trendline.type]} (${seriesName})`;\n}\n\n/** Whether trendlines can be drawn for this chart type and stacking (unstacked cartesian and xy charts). */\nexport function chartSupportsTrendlines(type: string, stacking: string): boolean {\n\treturn (type === 'bar' || type === 'line' || type === 'area' || type === 'scatter' || type === 'bubble') && stacking === 'none';\n}\n","import { niceScale, type NiceScale } from './scale.js';\nimport type { ChartAxis, ChartMark, ChartMarker, ChartRect, ChartScene, ChartSelection, ChartSpec, ChartTheme, ChartValueScale, ChartWarning } from './types.js';\n\nexport type ChartTextMeasure = (text: string, size: number, weight?: number) => number;\n\nexport interface ChartLayoutOptions {\n\twidth: number;\n\theight: number;\n\ttheme?: Partial<ChartTheme>;\n\t/** Highlighted in the scene (selection outlines, `selected` flags). */\n\tselection?: ChartSelection | null;\n\t/** Text width in pixels (default: an estimate from the character count). */\n\tmeasureText?: ChartTextMeasure;\n\t/** Shown when there is nothing to draw (default \"No data\"). */\n\temptyMessage?: string;\n\t/**\n\t * Fixes the value axis to this range (over `yAxis.min` / `yAxis.max`). Canvases pass\n\t * `ChartPointDrag.valueDomain` during a drag so the axis does not rescale under the pointer.\n\t */\n\tvalueDomain?: { min: number; max: number } | null;\n\t/** Fixes the secondary value axis the same way (`ChartPointDrag.valueDomain2`). */\n\tvalueDomain2?: { min: number; max: number } | null;\n\t/** Fixes the numeric x axis of a scatter or bubble chart (`ChartPointDrag.xDomain`). */\n\txDomain?: { min: number; max: number } | null;\n\t/** Shows the value of this point next to it (a `drag-readout` text mark, kept inside the plot). */\n\treadout?: { seriesId: string; index: number } | null;\n}\n\n/** A DOM-free text width estimate (average glyph ≈ 0.56 em, bold ≈ 0.6 em). */\nexport const estimateChartTextWidth: ChartTextMeasure = (text, size, weight = 400) => text.length * size * (weight >= 600 ? 0.6 : 0.56);\n\n/** Whether two selections point at the same thing. */\nexport function sameChartSelection(a: ChartSelection | null | undefined, b: ChartSelection | null | undefined): boolean {\n\tif (!a || !b || a.kind !== b.kind) return false;\n\tswitch (a.kind) {\n\t\tcase 'axis':\n\t\t\treturn a.axis === (b as typeof a).axis;\n\t\tcase 'series':\n\t\t\treturn a.seriesId === (b as typeof a).seriesId;\n\t\tcase 'point':\n\t\tcase 'trendline':\n\t\t\treturn a.seriesId === (b as typeof a).seriesId && a.index === (b as typeof a).index;\n\t\tcase 'category':\n\t\t\treturn a.index === (b as typeof a).index;\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\n/**\n * Black or white text for a label drawn on `fill` (#rgb, #rrggbb or rgb()), by perceived\n * luminance (0.299 R + 0.587 G + 0.114 B). Unparseable colours (CSS variables) get white.\n */\nexport function contrastingTextColor(fill: string): string {\n\tlet rgb: number[] | null = null;\n\tconst hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(fill.trim());\n\tif (hex) {\n\t\tconst h = hex[1].length === 3 ? [...hex[1]].map((c) => c + c).join('') : hex[1];\n\t\trgb = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));\n\t} else {\n\t\tconst fn = /^rgba?\\(\\s*([\\d.]+)[\\s,]+([\\d.]+)[\\s,]+([\\d.]+)/i.exec(fill.trim());\n\t\tif (fn) rgb = fn.slice(1, 4).map(Number);\n\t}\n\tif (!rgb) return '#ffffff';\n\tconst luminance = (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) / 255;\n\treturn luminance > 0.5 ? '#0f172a' : '#ffffff';\n}\n\nexport const r2 = (n: number) => Math.round(n * 100) / 100;\n\n/** Shared state while one scene is laid out. */\nexport interface LayoutCtx {\n\tspec: ChartSpec;\n\toptions: ChartLayoutOptions;\n\ttheme: ChartTheme;\n\tmeasure: ChartTextMeasure;\n\tfs: number;\n\twidth: number;\n\theight: number;\n\tmarks: ChartMark[];\n\twarnings: ChartWarning[];\n\tselection: ChartSelection | null;\n\tisSelected(target: ChartSelection): boolean;\n\tseriesSelected(id: string): boolean;\n\toutline(key: string, box: ChartRect): void;\n\twarn(code: ChartWarning['code'], message: string): void;\n}\n\n/** What a family layout adds to the scene. */\nexport interface FamilyResult {\n\tplot: ChartRect;\n\tvalueScale?: ChartValueScale;\n\tvalueScale2?: ChartValueScale;\n\txScale?: ChartValueScale;\n\tpercent?: boolean;\n}\n\nexport type ChartSceneBase = Omit<ChartScene, 'marks' | 'warnings' | 'theme' | 'width' | 'height'>;\n\nexport interface Pt {\n\tc: number;\n\tv: number;\n}\n\n/** Path through points (in category/value pixel space) with the chosen curve; `map` turns them into x/y. */\nexport function curvePath(points: Pt[], curve: ChartSpec['curve'], map: (p: Pt) => [number, number], moveFirst = true): string {\n\tif (!points.length) return '';\n\tconst xy = points.map(map);\n\tlet d = `${moveFirst ? 'M' : 'L'}${r2(xy[0][0])},${r2(xy[0][1])}`;\n\tif (points.length === 1) return d;\n\tif (curve === 'step') {\n\t\tfor (let i = 1; i < points.length; i++) {\n\t\t\tconst mid = (points[i - 1].c + points[i].c) / 2;\n\t\t\tconst a = map({ c: mid, v: points[i - 1].v });\n\t\t\tconst b = map({ c: mid, v: points[i].v });\n\t\t\td += `L${r2(a[0])},${r2(a[1])}L${r2(b[0])},${r2(b[1])}L${r2(xy[i][0])},${r2(xy[i][1])}`;\n\t\t}\n\t\treturn d;\n\t}\n\tif (curve === 'smooth' && points.length > 2) {\n\t\t// Monotone cubic (Fritsch–Carlson): smooth, never overshoots the data.\n\t\tconst n = points.length;\n\t\tconst dc = points.slice(1).map((p, i) => p.c - points[i].c);\n\t\tconst slope = points.slice(1).map((p, i) => (dc[i] === 0 ? 0 : (p.v - points[i].v) / dc[i]));\n\t\tconst tangent = points.map((_, i) => {\n\t\t\tif (i === 0) return slope[0];\n\t\t\tif (i === n - 1) return slope[n - 2];\n\t\t\tconst a = slope[i - 1];\n\t\t\tconst b = slope[i];\n\t\t\tif (a * b <= 0) return 0;\n\t\t\tconst wa = 2 * dc[i] + dc[i - 1];\n\t\t\tconst wb = dc[i] + 2 * dc[i - 1];\n\t\t\treturn (wa + wb) / (wa / a + wb / b);\n\t\t});\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tconst h = dc[i - 1] / 3;\n\t\t\tconst p0 = points[i - 1];\n\t\t\tconst p1 = points[i];\n\t\t\tconst a = map({ c: p0.c + h, v: p0.v + tangent[i - 1] * h });\n\t\t\tconst b = map({ c: p1.c - h, v: p1.v - tangent[i] * h });\n\t\t\td += `C${r2(a[0])},${r2(a[1])} ${r2(b[0])},${r2(b[1])} ${r2(xy[i][0])},${r2(xy[i][1])}`;\n\t\t}\n\t\treturn d;\n\t}\n\tfor (let i = 1; i < xy.length; i++) d += `L${r2(xy[i][0])},${r2(xy[i][1])}`;\n\treturn d;\n}\n\nexport function arcPath(cx: number, cy: number, outer: number, inner: number, start: number, end: number): string {\n\tconst full = end - start >= Math.PI * 2 - 1e-9;\n\tif (full) end = start + Math.PI * 2 - 1e-4;\n\tconst p = (r: number, a: number) => `${r2(cx + r * Math.sin(a))},${r2(cy - r * Math.cos(a))}`;\n\tconst large = end - start > Math.PI ? 1 : 0;\n\tlet d = `M${p(outer, start)}A${r2(outer)},${r2(outer)} 0 ${large} 1 ${p(outer, end)}`;\n\tif (inner > 0) d += `L${p(inner, end)}A${r2(inner)},${r2(inner)} 0 ${large} 0 ${p(inner, start)}Z`;\n\telse d += `L${r2(cx)},${r2(cy)}Z`;\n\treturn d;\n}\n\nexport function truncate(text: string, maxWidth: number, size: number, measure: ChartTextMeasure): string {\n\tif (measure(text, size) <= maxWidth) return text;\n\tlet out = text;\n\twhile (out.length > 1 && measure(`${out}…`, size) > maxWidth) out = out.slice(0, -1);\n\treturn `${out}…`;\n}\n\n/** The outline of a point marker centred on (cx, cy) with \"radius\" r, as an SVG path. */\nexport function markerPath(shape: Exclude<ChartMarker, 'circle' | 'none'>, cx: number, cy: number, r: number): string {\n\tswitch (shape) {\n\t\tcase 'square':\n\t\t\treturn `M${r2(cx - r)},${r2(cy - r)}H${r2(cx + r)}V${r2(cy + r)}H${r2(cx - r)}Z`;\n\t\tcase 'diamond': {\n\t\t\tconst d = r * 1.3;\n\t\t\treturn `M${r2(cx)},${r2(cy - d)}L${r2(cx + d)},${r2(cy)}L${r2(cx)},${r2(cy + d)}L${r2(cx - d)},${r2(cy)}Z`;\n\t\t}\n\t\tcase 'triangle': {\n\t\t\tconst d = r * 1.3;\n\t\t\treturn `M${r2(cx)},${r2(cy - d)}L${r2(cx + d * 0.87)},${r2(cy + d * 0.5)}L${r2(cx - d * 0.87)},${r2(cy + d * 0.5)}Z`;\n\t\t}\n\t\tcase 'cross': {\n\t\t\tconst d = r;\n\t\t\treturn `M${r2(cx - d)},${r2(cy - d)}L${r2(cx + d)},${r2(cy + d)}M${r2(cx - d)},${r2(cy + d)}L${r2(cx + d)},${r2(cy - d)}`;\n\t\t}\n\t}\n}\n\n/** The tick count for an axis `length` pixels long (about one per 56 px, 2–10). */\nexport const tickCount = (length: number) => Math.max(2, Math.min(10, Math.round(length / 56)));\n\n/**\n * A value scale over [lo, hi] for an axis `length` pixels long: the axis' fixed ends and\n * step win, then `frozen` (a drag in progress) fixes both ends. `headroom` adds 5% above a\n * maximum that lands exactly on the top tick (lines and points would touch the frame).\n */\nexport function axisScale(lo: number, hi: number, length: number, axis: ChartAxis, frozen?: { min: number; max: number } | null, headroom = false): NiceScale {\n\tconst fixedMin = frozen && Number.isFinite(frozen.min) ? frozen.min : axis.min;\n\tconst fixedMax = frozen && Number.isFinite(frozen.max) ? frozen.max : axis.max;\n\tconst step = axis.step;\n\tif (step && step > 0 && Number.isFinite(lo) && Number.isFinite(hi)) {\n\t\tlet min = fixedMin ?? Math.floor(lo / step + 1e-9) * step;\n\t\tlet max = fixedMax ?? Math.ceil(hi / step - 1e-9) * step;\n\t\tif (!(max > min)) max = min + step;\n\t\tconst first = Math.ceil(min / step - 1e-9);\n\t\tconst last = Math.floor(max / step + 1e-9);\n\t\tif (last - first <= 200) {\n\t\t\tconst clean = (n: number) => (Math.abs(n) < 1e-12 ? 0 : Number(n.toPrecision(12)));\n\t\t\tmin = clean(min);\n\t\t\tmax = clean(max);\n\t\t\tconst ticks: number[] = [];\n\t\t\tfor (let i = first; i <= last; i++) ticks.push(clean(i * step));\n\t\t\treturn { min, max, step, ticks };\n\t\t}\n\t}\n\tlet scale = niceScale(lo, hi, tickCount(length), fixedMin, fixedMax);\n\tconst roomy = hi + (hi - lo) * 0.05;\n\tif (headroom && fixedMax === null && hi !== 0 && hi > lo && scale.max === hi && Number.isFinite(roomy)) scale = niceScale(lo, roomy, tickCount(length), fixedMin, fixedMax);\n\treturn scale;\n}\n\n/** Liang–Barsky: the part of segment a→b inside `rect`, or null. */\nexport function clipSegment(a: [number, number], b: [number, number], rect: ChartRect): [[number, number], [number, number]] | null {\n\tlet t0 = 0;\n\tlet t1 = 1;\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst checks: [number, number][] = [\n\t\t[-dx, a[0] - rect.x],\n\t\t[dx, rect.x + rect.width - a[0]],\n\t\t[-dy, a[1] - rect.y],\n\t\t[dy, rect.y + rect.height - a[1]]\n\t];\n\tfor (const [p, q] of checks) {\n\t\tif (p === 0) {\n\t\t\tif (q < 0) return null;\n\t\t\tcontinue;\n\t\t}\n\t\tconst r = q / p;\n\t\tif (p < 0) {\n\t\t\tif (r > t1) return null;\n\t\t\tif (r > t0) t0 = r;\n\t\t} else {\n\t\t\tif (r < t0) return null;\n\t\t\tif (r < t1) t1 = r;\n\t\t}\n\t}\n\treturn [\n\t\t[a[0] + t0 * dx, a[1] + t0 * dy],\n\t\t[a[0] + t1 * dx, a[1] + t1 * dy]\n\t];\n}\n\n/** A polyline clipped to `rect` as path data (separate runs where it leaves and re-enters). */\nexport function clippedPolyline(points: [number, number][], rect: ChartRect): string {\n\tlet d = '';\n\tlet open = false;\n\tlet last: [number, number] | null = null;\n\tfor (let i = 1; i < points.length; i++) {\n\t\tconst seg = clipSegment(points[i - 1], points[i], rect);\n\t\tif (!seg) {\n\t\t\topen = false;\n\t\t\tcontinue;\n\t\t}\n\t\tconst [p, q] = seg;\n\t\tif (!open || !last || Math.abs(last[0] - p[0]) > 0.01 || Math.abs(last[1] - p[1]) > 0.01) d += `M${r2(p[0])},${r2(p[1])}`;\n\t\td += `L${r2(q[0])},${r2(q[1])}`;\n\t\tlast = q;\n\t\topen = true;\n\t}\n\treturn d;\n}\n","// Trendline sampling and clipping follow gridcraft-main/crates/chart/src/render.rs (`draw_trendline`,\n// `clip_segment`) and the label rules its `on` / fit checks use; marker de-duplication and polyline decimation\n// follow its `draw_markers` and `decimate` (MIT OR Apache-2.0, © ArtCraft Team and contributors). See\n// THIRD_PARTY_NOTICES.md.\nimport { chartDateLabels } from './date.js';\nimport {\n\taxisScale,\n\tclippedPolyline,\n\tcontrastingTextColor,\n\tcurvePath,\n\tmarkerPath,\n\tr2,\n\ttruncate,\n\ttype FamilyResult,\n\ttype LayoutCtx,\n\ttype Pt\n} from './layout-shared.js';\nimport { formatChartNumber, linearMap, stepDecimals, type NiceScale } from './scale.js';\nimport { chartPointColor, chartSeriesColor, chartSeriesType } from './spec.js';\nimport { decimateChartPoints } from './stats.js';\nimport { chartMovingAverage, chartSupportsTrendlines, chartTrendlineName, fitChartTrendline, trendNumberText } from './trend.js';\nimport type { ChartAxis, ChartMark, ChartMarker, ChartNumberFormat, ChartRect, ChartSelection, ChartSeries, ChartSeriesType, ChartValueScale } from './types.js';\n\n/** Data labels are skipped on series with more points than this. */\nexport const MAX_CHART_DATA_LABELS = 200;\n/** Lines with more points than this are thinned per pixel column. */\nexport const MAX_CHART_LINE_POINTS = 2000;\n/** Markers beyond this many are thinned to one per 2px cell. */\nexport const MAX_CHART_MARKERS = 1000;\n\nexport interface ValueAxisInput {\n\tlo: number;\n\thi: number;\n\taxis: ChartAxis;\n\tformat: ChartNumberFormat;\n\tfrozen?: { min: number; max: number } | null;\n\theadroom?: boolean;\n\t/** Which selection the tick labels pick. */\n\tkey: 'y' | 'y2';\n}\n\nexport interface ScaleInfo {\n\tscale: NiceScale;\n\trange: [number, number];\n\t/** Value → pixel, clamped to the axis. */\n\tpx(v: number): number;\n\t/** Value → pixel, not clamped. */\n\traw(v: number): number;\n\t/** Pixel of 0 (or the nearest end). */\n\tzero: number;\n\tformat: ChartNumberFormat;\n\ttickText(t: number): string;\n}\n\nexport interface CategoryFrame {\n\tplot: ChartRect;\n\thorizontal: boolean;\n\tn: number;\n\tband: number;\n\tcatStart: number;\n\tcatLen: number;\n\tcatCenter(i: number): number;\n\tmap(p: Pt): [number, number];\n\tvalue: ScaleInfo;\n\tvalue2?: ScaleInfo;\n}\n\nexport interface CategoryFrameInput {\n\tlabels: readonly string[];\n\thorizontal: boolean;\n\tprimary: ValueAxisInput;\n\tsecondary?: ValueAxisInput;\n\t/** What clicking category label `i` selects (default: the category). */\n\tlabelTarget?: (i: number) => ChartSelection | undefined;\n\t/** Category axis settings (default `spec.xAxis`). */\n\tcategoryAxis?: ChartAxis;\n}\n\nfunction scaleInfo(scale: NiceScale, range: [number, number], format: ChartNumberFormat): ScaleInfo {\n\tconst domain: [number, number] = [scale.min, scale.max];\n\tconst raw = (v: number) => linearMap(v, domain, range);\n\tconst px = (v: number) => raw(Math.min(scale.max, Math.max(scale.min, v)));\n\treturn { scale, range, px, raw, zero: px(0), format, tickText: (t) => formatChartNumber(t, format, format.decimals ?? stepDecimals(scale.step)) };\n}\n\n/**\n * The axes of a category chart: category labels along one side (rotated, thinned or read as\n * dates as space allows), one or two value axes, grid lines and axis titles. Returns the plot\n * box and value ↔ pixel maps.\n */\nexport function categoryFrame(ctx: LayoutCtx, area: ChartRect, input: CategoryFrameInput): CategoryFrame {\n\tconst { spec, theme, measure, fs, marks } = ctx;\n\tconst { labels, horizontal, primary, secondary } = input;\n\tconst xAxis = input.categoryAxis ?? spec.xAxis;\n\tconst n = Math.max(1, labels.length);\n\tconst titleBand = fs * 1.3 + 6;\n\tconst labelTarget = input.labelTarget ?? ((i: number) => ({ kind: 'category', index: i }) as ChartSelection);\n\n\tconst estimate = (v: ValueAxisInput, length: number) => {\n\t\tconst s = axisScale(v.lo, v.hi, length, v.axis, v.frozen, v.headroom);\n\t\tconst info = scaleInfo(s, [0, 1], v.format);\n\t\treturn Math.max(0, ...s.ticks.map((t) => measure(info.tickText(t), fs)));\n\t};\n\tconst valueLen0 = horizontal ? area.width : area.height;\n\tconst valueLabelWidth = primary.axis.show ? estimate(primary, valueLen0) : 0;\n\tconst valueLabelWidth2 = secondary?.axis.show ? estimate(secondary, valueLen0) : 0;\n\tconst catLabelWidth = Math.max(0, ...labels.map((c) => measure(c, fs)));\n\n\tlet left: number;\n\tlet bottom: number;\n\tlet right = 8;\n\tlet top = horizontal ? 4 : fs / 2 + 2;\n\tlet rotate = 0;\n\tlet dateLabels: ReturnType<typeof chartDateLabels> = null;\n\tlet rotatedMax = 0;\n\tif (horizontal) {\n\t\tleft = (xAxis.show ? Math.min(catLabelWidth, area.width * 0.35) + 8 : 2) + (xAxis.title ? titleBand : 0);\n\t\tbottom = (primary.axis.show ? fs * 1.6 : 2) + (primary.axis.title ? titleBand : 0);\n\t\tright = Math.max(8, valueLabelWidth / 2);\n\t\tif (secondary) top = (secondary.axis.show ? fs * 1.6 : 4) + (secondary.axis.title ? titleBand : 0);\n\t} else {\n\t\tleft = (primary.axis.show ? valueLabelWidth + 8 : 2) + (primary.axis.title ? titleBand : 0);\n\t\tif (secondary) right = (secondary.axis.show ? valueLabelWidth2 + 8 : 8) + (secondary.axis.title ? titleBand : 0);\n\t\tconst band = (area.width - left - right) / n;\n\t\tif (xAxis.show && xAxis.kind === 'date') dateLabels = chartDateLabels(labels, band, (t) => measure(t, fs));\n\t\tif (xAxis.show && !dateLabels && catLabelWidth > band * 0.92) rotate = -40;\n\t\tconst sin = Math.sin(Math.PI / 4.5);\n\t\tconst catHeight = rotate ? Math.min(catLabelWidth * sin + fs, area.height * 0.4) : fs * 1.6;\n\t\tif (rotate) rotatedMax = (catHeight - fs) / sin;\n\t\tbottom = (xAxis.show ? catHeight : 2) + (xAxis.title ? titleBand : 0);\n\t}\n\tconst plot: ChartRect = {\n\t\tx: area.x + left,\n\t\ty: area.y + top,\n\t\twidth: Math.max(1, area.width - left - right),\n\t\theight: Math.max(1, area.height - bottom - top)\n\t};\n\tconst valueLen = horizontal ? plot.width : plot.height;\n\tconst range: [number, number] = horizontal ? [plot.x, plot.x + plot.width] : [plot.y + plot.height, plot.y];\n\tconst value = scaleInfo(axisScale(primary.lo, primary.hi, valueLen, primary.axis, primary.frozen, primary.headroom), range, primary.format);\n\tconst value2 = secondary ? scaleInfo(axisScale(secondary.lo, secondary.hi, valueLen, secondary.axis, secondary.frozen, secondary.headroom), range, secondary.format) : undefined;\n\n\tconst catStart = horizontal ? plot.y : plot.x;\n\tconst catLen = horizontal ? plot.height : plot.width;\n\tconst band = catLen / n;\n\tconst catCenter = (i: number) => catStart + band * (i + 0.5);\n\tconst map = (p: Pt): [number, number] => (horizontal ? [p.v, p.c] : [p.c, p.v]);\n\n\t// Grid lines\n\tconst gridAt = (info: ScaleInfo, key: string) =>\n\t\tinfo.scale.ticks.forEach((t, i) => {\n\t\t\tconst p = info.px(t);\n\t\t\tconst [x1, y1] = map({ c: catStart, v: p });\n\t\t\tconst [x2, y2] = map({ c: catStart + catLen, v: p });\n\t\t\tmarks.push({ kind: 'line', key: `grid-${key}-${i}`, role: 'grid', x1, y1, x2, y2, stroke: theme.grid, strokeWidth: 1 });\n\t\t});\n\tif (primary.axis.gridlines) gridAt(value, 'y');\n\tif (value2 && secondary!.axis.gridlines) gridAt(value2, 'y2');\n\tif (xAxis.gridlines) {\n\t\tfor (let i = 1; i < n; i++) {\n\t\t\tconst c = catStart + band * i;\n\t\t\tconst [x1, y1] = map({ c, v: range[0] });\n\t\t\tconst [x2, y2] = map({ c, v: range[1] });\n\t\t\tmarks.push({ kind: 'line', key: `grid-x-${i}`, role: 'grid', x1, y1, x2, y2, stroke: theme.grid, strokeWidth: 1 });\n\t\t}\n\t}\n\n\t// Value tick labels\n\tconst ticksFor = (info: ScaleInfo, v: ValueAxisInput, far: boolean) => {\n\t\tif (!v.axis.show) return;\n\t\tconst target: ChartSelection = { kind: 'axis', axis: v.key };\n\t\tinfo.scale.ticks.forEach((t, i) => {\n\t\t\tconst p = info.px(t);\n\t\t\tconst label = info.tickText(t);\n\t\t\tconst key = `tick-${v.key}-${i}`;\n\t\t\tif (horizontal) {\n\t\t\t\tif (far) marks.push({ kind: 'text', key, role: 'tick-label', x: p, y: plot.y - 6, text: label, anchor: 'middle', baseline: 'bottom', size: fs, fill: theme.mutedText, target });\n\t\t\t\telse marks.push({ kind: 'text', key, role: 'tick-label', x: p, y: plot.y + plot.height + 6, text: label, anchor: 'middle', baseline: 'top', size: fs, fill: theme.mutedText, target });\n\t\t\t} else if (far) marks.push({ kind: 'text', key, role: 'tick-label', x: plot.x + plot.width + 8, y: p, text: label, anchor: 'start', baseline: 'middle', size: fs, fill: theme.mutedText, target });\n\t\t\telse marks.push({ kind: 'text', key, role: 'tick-label', x: plot.x - 8, y: p, text: label, anchor: 'end', baseline: 'middle', size: fs, fill: theme.mutedText, target });\n\t\t});\n\t};\n\tticksFor(value, primary, false);\n\tif (value2) ticksFor(value2, secondary!, true);\n\n\t// Category axis line and labels\n\tconst xTarget: ChartSelection = { kind: 'axis', axis: 'x' };\n\tif (xAxis.show) {\n\t\tconst [x1, y1] = map({ c: catStart, v: value.zero });\n\t\tconst [x2, y2] = map({ c: catStart + catLen, v: value.zero });\n\t\tmarks.push({ kind: 'line', key: 'axis-x', role: 'axis', x1, y1, x2, y2, stroke: theme.axis, strokeWidth: 1, target: xTarget });\n\t\tconst every = dateLabels ? 1 : horizontal ? Math.max(1, Math.ceil((fs * 1.3) / band)) : rotate ? Math.max(1, Math.ceil((fs * 1.4) / band)) : 1;\n\t\tlet hidden = 0;\n\t\tlet truncated = 0;\n\t\tlabels.forEach((c, i) => {\n\t\t\tconst text0 = dateLabels ? dateLabels.labels.get(i) : i % every ? undefined : c;\n\t\t\tif (text0 === undefined) {\n\t\t\t\thidden++;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst target = labelTarget(i);\n\t\t\tconst selected = target ? ctx.isSelected(target) : false;\n\t\t\tconst fill = selected ? theme.selection : theme.mutedText;\n\t\t\tconst extra = target ? { target, selected } : {};\n\t\t\tif (horizontal) {\n\t\t\t\tconst maxW = left - (xAxis.title ? titleBand : 0) - 8;\n\t\t\t\tconst text = truncate(text0, maxW, fs, measure);\n\t\t\t\tif (text !== text0) truncated++;\n\t\t\t\tmarks.push({ kind: 'text', key: `tick-x-${i}`, role: 'tick-label', x: plot.x - 8, y: catCenter(i), text, anchor: 'end', baseline: 'middle', size: fs, fill, ...extra });\n\t\t\t} else if (rotate) {\n\t\t\t\t// Rotated labels run down and to the left: keep them inside the chart.\n\t\t\t\tconst room = (catCenter(i) - 2) / Math.cos(Math.PI / 4.5);\n\t\t\t\tconst text = truncate(text0, Math.max(fs, Math.min(rotatedMax, room)), fs, measure);\n\t\t\t\tif (text !== text0) truncated++;\n\t\t\t\tmarks.push({ kind: 'text', key: `tick-x-${i}`, role: 'tick-label', x: catCenter(i), y: plot.y + plot.height + 8, text, anchor: 'end', baseline: 'middle', size: fs, fill, rotate, ...extra });\n\t\t\t} else {\n\t\t\t\tconst text = dateLabels ? text0 : truncate(text0, Math.max(band - 4, fs * 2), fs, measure);\n\t\t\t\tif (text !== text0) truncated++;\n\t\t\t\tmarks.push({ kind: 'text', key: `tick-x-${i}`, role: 'tick-label', x: catCenter(i), y: plot.y + plot.height + 6, text, anchor: dateLabels ? 'start' : 'middle', baseline: 'top', size: fs, fill, ...extra });\n\t\t\t}\n\t\t});\n\t\tif (dateLabels) {\n\t\t\t// Date labels sit at the start of their bucket; mark it with a short tick.\n\t\t\tfor (const i of dateLabels.indexes) {\n\t\t\t\tconst x = catCenter(i);\n\t\t\t\tmarks.push({ kind: 'line', key: `tick-mark-x-${i}`, role: 'tick', x1: x, y1: plot.y + plot.height, x2: x, y2: plot.y + plot.height + 4, stroke: theme.axis, strokeWidth: 1 });\n\t\t\t}\n\t\t}\n\t\tif (hidden && !dateLabels) ctx.warn('labels-hidden', `${hidden} of ${labels.length} category labels are hidden so the rest do not overlap.`);\n\t\tif (truncated) ctx.warn('labels-truncated', `${truncated} category label${truncated === 1 ? ' was' : 's were'} shortened to fit.`);\n\t}\n\n\t// Axis titles: category title beside the category labels, value titles beside their ticks.\n\tconst yTarget: ChartSelection = { kind: 'axis', axis: 'y' };\n\tconst valueTitle = primary.axis.title;\n\tconst catTitle = xAxis.title;\n\tconst bottomTitle = horizontal ? valueTitle : catTitle;\n\tconst leftTitle = horizontal ? catTitle : valueTitle;\n\tif (bottomTitle)\n\t\tmarks.push({ kind: 'text', key: `axis-title-${horizontal ? 'y' : 'x'}`, role: 'axis-title', x: plot.x + plot.width / 2, y: area.y + area.height, text: bottomTitle, anchor: 'middle', baseline: 'bottom', size: fs + 1, weight: 500, fill: theme.text, target: horizontal ? yTarget : xTarget });\n\tif (leftTitle)\n\t\tmarks.push({ kind: 'text', key: `axis-title-${horizontal ? 'x' : 'y'}`, role: 'axis-title', x: area.x, y: plot.y + plot.height / 2, text: leftTitle, anchor: 'middle', baseline: 'top', size: fs + 1, weight: 500, fill: theme.text, rotate: -90, target: horizontal ? xTarget : yTarget });\n\tif (secondary?.axis.title) {\n\t\tconst target: ChartSelection = { kind: 'axis', axis: 'y2' };\n\t\tif (horizontal) marks.push({ kind: 'text', key: 'axis-title-y2', role: 'axis-title', x: plot.x + plot.width / 2, y: area.y, text: secondary.axis.title, anchor: 'middle', baseline: 'top', size: fs + 1, weight: 500, fill: theme.text, target });\n\t\telse marks.push({ kind: 'text', key: 'axis-title-y2', role: 'axis-title', x: area.x + area.width, y: plot.y + plot.height / 2, text: secondary.axis.title, anchor: 'middle', baseline: 'top', size: fs + 1, weight: 500, fill: theme.text, rotate: 90, target });\n\t}\n\t// The selected axis gets an outline around its labels.\n\tfor (const axis of ['x', 'y', 'y2'] as const) {\n\t\tif (!ctx.isSelected({ kind: 'axis', axis })) continue;\n\t\tif (axis === 'y2' && !secondary) continue;\n\t\tlet box: ChartRect;\n\t\tif (axis === 'y2') box = horizontal ? { x: plot.x - 4, y: area.y, width: plot.width + 8, height: plot.y - area.y - 2 } : { x: plot.x + plot.width + 2, y: plot.y - fs / 2, width: area.x + area.width - plot.x - plot.width - 2, height: plot.height + fs };\n\t\telse {\n\t\t\tconst onLeft = (axis === 'y') !== horizontal;\n\t\t\tbox = onLeft\n\t\t\t\t? { x: area.x, y: plot.y - fs / 2, width: left - 2, height: plot.height + fs }\n\t\t\t\t: { x: plot.x - 4, y: plot.y + plot.height + 2, width: plot.width + 8, height: area.y + area.height - plot.y - plot.height - 2 };\n\t\t}\n\t\tctx.outline(`axis-${axis}-selection`, box);\n\t}\n\treturn { plot, horizontal, n, band, catStart, catLen, catCenter, map, value, value2 };\n}\n\nexport const toValueScale = (info: ScaleInfo, axis: 'x' | 'y'): ChartValueScale => ({ axis, domain: [info.scale.min, info.scale.max], range: info.range, ticks: info.scale.ticks });\n\ninterface Stack {\n\t/** Per category: [bottom, top] of this series' segment, or null for a gap. */\n\tsegments: ([number, number] | null)[];\n}\n\nconst order = (t: ChartSeriesType) => (t === 'area' ? 0 : t === 'bar' ? 1 : t === 'line' ? 2 : 3);\n\n/** A point marker: a circle mark, or a path for other shapes. */\nexport function pointMark(base: { key: string; target?: ChartSelection; selected?: boolean; opacity?: number }, shape: ChartMarker | 'hit', cx: number, cy: number, r: number, fill: string, stroke?: string, strokeWidth?: number): ChartMark {\n\tif (shape === 'circle' || shape === 'hit' || shape === 'none') return { kind: 'circle', role: 'point', ...base, cx, cy, r, fill, ...(stroke ? { stroke, strokeWidth } : {}) };\n\tconst closed = shape !== 'cross';\n\treturn { kind: 'path', role: 'point', ...base, d: markerPath(shape, cx, cy, r), fill: closed ? fill : 'none', stroke: stroke ?? fill, strokeWidth: strokeWidth ?? 2 };\n}\n\ninterface TrendLabel {\n\ttext: string;\n\tcolor: string;\n\ttarget: ChartSelection;\n}\n\n/**\n * Draws the trendlines of one series: `points` in data units, `toPx` maps them to the scene,\n * `xRange` is the fitted span (extended by forward/backward).\n */\nfunction drawTrendlines(ctx: LayoutCtx, plot: ChartRect, series: ChartSeries, color: string, points: [number, number][], toPx: (x: number, y: number) => [number, number], labels: TrendLabel[]) {\n\t(series.trendlines ?? []).forEach((t, ti) => {\n\t\tconst target: ChartSelection = { kind: 'trendline', seriesId: series.id, index: ti };\n\t\tconst selected = ctx.isSelected(target);\n\t\tconst stroke = t.color ?? color;\n\t\tlet px: [number, number][] = [];\n\t\tif (t.type === 'moving-average') px = chartMovingAverage(points, t.period ?? 2).map(([x, y]) => toPx(x, y));\n\t\telse {\n\t\t\tconst fit = fitChartTrendline(t, points);\n\t\t\tif (!fit) {\n\t\t\t\tctx.warn('values-skipped', `The ${t.type} trendline on \"${series.name}\" could not be fitted (too few usable points).`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst xs = points.map((p) => p[0]);\n\t\t\tconst lo = Math.min(...xs) - (t.backward ?? 0);\n\t\t\tconst hi = Math.max(...xs) + (t.forward ?? 0);\n\t\t\tconst steps = t.type === 'linear' ? 1 : 200;\n\t\t\tfor (let k = 0; k <= steps; k++) {\n\t\t\t\tconst x = lo + ((hi - lo) * k) / steps;\n\t\t\t\tconst y = fit.evaluate(x);\n\t\t\t\tif (y !== null) px.push(toPx(x, y));\n\t\t\t}\n\t\t\tif (t.showEquation) labels.push({ text: fit.equation, color: stroke, target });\n\t\t\tif (t.showR2) labels.push({ text: fit.r2 === null ? 'R² = #N/A' : `R² = ${trendNumberText(fit.r2)}`, color: stroke, target });\n\t\t}\n\t\tconst d = clippedPolyline(px, plot);\n\t\tif (!d) return;\n\t\tctx.marks.push({ kind: 'path', key: `trendline-${series.id}-${ti}`, role: 'trendline', d, fill: 'none', stroke, strokeWidth: selected ? 3 : 1.5, dash: '6 4', target, selected });\n\t});\n}\n\nfunction drawTrendLabels(ctx: LayoutCtx, plot: ChartRect, labels: TrendLabel[]) {\n\tlabels.forEach((l, i) =>\n\t\tctx.marks.push({ kind: 'text', key: `trendline-label-${i}`, role: 'trendline-label', x: plot.x + plot.width - 4, y: plot.y + 4 + i * (ctx.fs + 3), text: l.text, anchor: 'end', baseline: 'top', size: ctx.fs - 1, fill: l.color, target: l.target })\n\t);\n}\n\n/** Where a bar's value label goes, or null when it does not fit. */\nfunction barLabel(ctx: LayoutCtx, text: string, rect: ChartRect, horizontal: boolean, positive: boolean, stacked: boolean, fill: string, plot: ChartRect): { x: number; y: number; anchor: 'start' | 'middle' | 'end'; baseline: 'top' | 'middle' | 'bottom'; fill: string } | null {\n\tconst { measure, fs, spec, theme } = ctx;\n\tconst size = fs - 1;\n\tconst tw = measure(text, size);\n\tconst th = size + 2;\n\tconst along = horizontal ? rect.width : rect.height;\n\tconst across = horizontal ? rect.height : rect.width;\n\tconst need = horizontal ? tw + 6 : th + 2;\n\tconst fitsInside = along >= need && across >= (horizontal ? th : Math.min(tw, across + 1));\n\tlet position = spec.labelPosition;\n\tif (position === 'auto') position = stacked ? 'center' : 'outside';\n\tconst cx = rect.x + rect.width / 2;\n\tconst cy = rect.y + rect.height / 2;\n\tconst inner = contrastingTextColor(fill);\n\tconst centre = () => ({ x: cx, y: cy, anchor: 'middle' as const, baseline: 'middle' as const, fill: inner });\n\tconst insideEnd = () =>\n\t\thorizontal\n\t\t\t? { x: positive ? rect.x + rect.width - 4 : rect.x + 4, y: cy, anchor: (positive ? 'end' : 'start') as 'end' | 'start', baseline: 'middle' as const, fill: inner }\n\t\t\t: { x: cx, y: positive ? rect.y + 3 : rect.y + rect.height - 3, anchor: 'middle' as const, baseline: (positive ? 'top' : 'bottom') as 'top' | 'bottom', fill: inner };\n\tconst outside = () =>\n\t\thorizontal\n\t\t\t? { x: positive ? rect.x + rect.width + 4 : rect.x - 4, y: cy, anchor: (positive ? 'start' : 'end') as 'start' | 'end', baseline: 'middle' as const, fill: theme.text }\n\t\t\t: { x: cx, y: positive ? rect.y - 4 : rect.y + rect.height + 4, anchor: 'middle' as const, baseline: (positive ? 'bottom' : 'top') as 'bottom' | 'top', fill: theme.text };\n\tconst outsideFits = () => {\n\t\tif (horizontal) return positive ? rect.x + rect.width + 4 + tw <= plot.x + plot.width + 8 : rect.x - 4 - tw >= plot.x - 8;\n\t\treturn positive ? rect.y - 4 - th >= plot.y - fs : rect.y + rect.height + 4 + th <= plot.y + plot.height + fs;\n\t};\n\tif (position === 'center') return fitsInside ? centre() : null;\n\tif (position === 'inside') return fitsInside ? insideEnd() : stacked ? null : outside();\n\t// outside\n\tif (stacked) return fitsInside ? centre() : null;\n\tif (outsideFits()) return outside();\n\treturn fitsInside ? insideEnd() : null;\n}\n\n/** Bar, line, area and scatter series over categories (a combo chart when they mix). */\nexport function layoutCartesian(ctx: LayoutCtx, area: ChartRect, visible: ChartSeries[]): FamilyResult {\n\tconst { spec, theme, marks, measure, fs } = ctx;\n\tconst horizontal = spec.orientation === 'horizontal';\n\tconst n = spec.categories.length;\n\tconst types = new Map<string, ChartSeriesType>(visible.map((s) => [s.id, chartSeriesType(spec, s)]));\n\tconst stacked = spec.stacking !== 'none';\n\tconst percent = spec.stacking === 'percent';\n\tconst onSecondary = (s: ChartSeries) => s.axis === 'secondary';\n\tconst useSecondary = visible.some(onSecondary);\n\n\t// Stack bars together and areas together, per axis (lines and scatter are never stacked).\n\tconst stacks = new Map<string, Stack>();\n\tif (stacked) {\n\t\tfor (const kind of ['bar', 'area'] as const) {\n\t\t\tfor (const secondary of [false, true]) {\n\t\t\t\tconst group = visible.filter((s) => types.get(s.id) === kind && onSecondary(s) === secondary);\n\t\t\t\tif (!group.length) continue;\n\t\t\t\tconst totals = Array.from({ length: n }, (_, i) => group.reduce((t, s) => t + Math.abs(s.values[i] ?? 0), 0));\n\t\t\t\tconst pos = Array(n).fill(0);\n\t\t\t\tconst neg = Array(n).fill(0);\n\t\t\t\tfor (const s of group) {\n\t\t\t\t\tconst segments = s.values.map((raw, i) => {\n\t\t\t\t\t\tif (raw === null && kind === 'bar') return null;\n\t\t\t\t\t\tlet v = raw ?? 0;\n\t\t\t\t\t\tif (percent) v = totals[i] ? v / totals[i] : 0;\n\t\t\t\t\t\tconst base = v >= 0 ? pos[i] : neg[i];\n\t\t\t\t\t\tconst seg: [number, number] = [base, base + v];\n\t\t\t\t\t\tif (v >= 0) pos[i] += v;\n\t\t\t\t\t\telse neg[i] += v;\n\t\t\t\t\t\treturn seg;\n\t\t\t\t\t});\n\t\t\t\t\tstacks.set(s.id, { segments });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tconst range = (secondary: boolean) => {\n\t\tlet lo = Infinity;\n\t\tlet hi = -Infinity;\n\t\tconst see = (v: number) => {\n\t\t\tlo = Math.min(lo, v);\n\t\t\thi = Math.max(hi, v);\n\t\t};\n\t\tconst group = visible.filter((s) => onSecondary(s) === secondary);\n\t\tfor (const s of group) {\n\t\t\tconst stack = stacks.get(s.id);\n\t\t\tif (stack) stack.segments.forEach((seg) => seg && (see(seg[0]), see(seg[1])));\n\t\t\telse s.values.forEach((v) => v !== null && Number.isFinite(v) && see(v));\n\t\t}\n\t\tif (!Number.isFinite(lo)) {\n\t\t\tlo = 0;\n\t\t\thi = 1;\n\t\t}\n\t\tif (group.some((s) => types.get(s.id) === 'bar' || types.get(s.id) === 'area')) {\n\t\t\tlo = Math.min(lo, 0);\n\t\t\thi = Math.max(hi, 0);\n\t\t}\n\t\tconst lineLike = group.some((s) => types.get(s.id) === 'line' || types.get(s.id) === 'scatter');\n\t\treturn { lo, hi, lineLike };\n\t};\n\tconst pctFormat = (f: ChartNumberFormat): ChartNumberFormat => (percent && !f.style && !f.code ? { ...f, style: 'percent' } : f);\n\tconst p = range(false);\n\tconst s2 = useSecondary ? range(true) : null;\n\tconst frame = categoryFrame(ctx, area, {\n\t\tlabels: spec.categories,\n\t\thorizontal,\n\t\tprimary: { lo: p.lo, hi: p.hi, axis: spec.yAxis, format: pctFormat(spec.yAxis.format), frozen: ctx.options.valueDomain, headroom: p.lineLike, key: 'y' },\n\t\tsecondary: s2 ? { lo: s2.lo, hi: s2.hi, axis: spec.yAxis2, format: pctFormat(spec.yAxis2.format), frozen: ctx.options.valueDomain2, headroom: s2.lineLike, key: 'y2' } : undefined\n\t});\n\tconst { plot, band, catCenter, map, catStart } = frame;\n\tconst infoOf = (s: ChartSeries) => (onSecondary(s) && frame.value2 ? frame.value2 : frame.value);\n\n\t// Bars: groups take (1 - gapWidth) of each category; bars in a group overlap by `overlap`.\n\tconst bars = visible.filter((s) => types.get(s.id) === 'bar');\n\tconst barAxes = [...new Set(bars.map((s) => onSecondary(s)))];\n\tconst slots = stacked ? barAxes.length : bars.length;\n\tconst groupWidth = band * (1 - spec.gapWidth);\n\tconst o = Math.max(-1, Math.min(0.99, spec.overlap));\n\tconst barWidth = slots ? groupWidth / (slots - (slots - 1) * o) : 0;\n\tconst slotOf = (s: ChartSeries) => (stacked ? barAxes.indexOf(onSecondary(s)) : bars.indexOf(s));\n\tconst labelMarks: ChartMark[] = [];\n\tconst trendLabels: TrendLabel[] = [];\n\tlet hiddenLabels = 0;\n\tconst trendsAllowed = chartSupportsTrendlines(spec.type, spec.stacking);\n\n\tconst drawOrder = [...visible].sort((a, b) => order(types.get(a.id)!) - order(types.get(b.id)!));\n\tfor (const s of drawOrder) {\n\t\tconst si = spec.series.indexOf(s);\n\t\tconst color = chartSeriesColor(spec, si);\n\t\tconst type = types.get(s.id)!;\n\t\tconst stack = stacks.get(s.id);\n\t\tconst selSeries = ctx.seriesSelected(s.id);\n\t\tconst seriesTarget: ChartSelection = { kind: 'series', seriesId: s.id };\n\t\tconst info = infoOf(s);\n\t\tconst valuePx = info.px;\n\t\tconst labelsOn = (s.dataLabels ?? spec.dataLabels) && s.values.length <= MAX_CHART_DATA_LABELS;\n\t\tif ((s.dataLabels ?? spec.dataLabels) && !labelsOn) ctx.warn('data-labels-hidden', `Data labels are off for \"${s.name}\": it has more than ${MAX_CHART_DATA_LABELS} points.`);\n\t\tconst labelFormat = s.format ?? info.format;\n\t\tconst dataLabel = (v: number) => formatChartNumber(v, labelFormat, labelFormat.decimals ?? undefined);\n\n\t\tif (type === 'bar') {\n\t\t\tconst slot = slotOf(s);\n\t\t\ts.values.forEach((raw, i) => {\n\t\t\t\tconst seg = stack ? stack.segments[i] : raw === null ? null : ([0, raw] as [number, number]);\n\t\t\t\tif (!seg || raw === null || !Number.isFinite(raw)) return;\n\t\t\t\tconst a = valuePx(seg[0]);\n\t\t\t\tconst b = valuePx(seg[1]);\n\t\t\t\tconst c0 = catCenter(i) - groupWidth / 2 + slot * barWidth * (1 - o);\n\t\t\t\tconst cw = barWidth;\n\t\t\t\tconst target: ChartSelection = { kind: 'point', seriesId: s.id, index: i };\n\t\t\t\tconst selected = ctx.isSelected(target);\n\t\t\t\tconst [x, y] = map({ c: c0, v: Math.min(a, b) });\n\t\t\t\tconst rect = horizontal ? { x: Math.min(a, b), y: c0, width: Math.abs(b - a), height: cw } : { x, y, width: cw, height: Math.abs(b - a) };\n\t\t\t\tconst fill = chartPointColor(spec, si, i);\n\t\t\t\tmarks.push({\n\t\t\t\t\tkind: 'rect',\n\t\t\t\t\tkey: `bar-${s.id}-${i}`,\n\t\t\t\t\trole: 'bar',\n\t\t\t\t\t...rect,\n\t\t\t\t\tfill,\n\t\t\t\t\tradius: Math.min(2, cw / 4),\n\t\t\t\t\ttarget,\n\t\t\t\t\tselected: selected || selSeries,\n\t\t\t\t\t...(selSeries ? { stroke: theme.selection, strokeWidth: 1.5 } : {})\n\t\t\t\t});\n\t\t\t\tif (selected) ctx.outline(`bar-${s.id}-${i}-selection`, { x: rect.x - 2, y: rect.y - 2, width: rect.width + 4, height: rect.height + 4 });\n\t\t\t\tif (labelsOn) {\n\t\t\t\t\tconst v = percent ? seg[1] - seg[0] : raw;\n\t\t\t\t\tconst text = dataLabel(v);\n\t\t\t\t\tconst at = barLabel(ctx, text, rect, horizontal, seg[1] >= seg[0], stacked, fill, plot);\n\t\t\t\t\tif (!at) {\n\t\t\t\t\t\thiddenLabels++;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlabelMarks.push({ kind: 'text', key: `label-${s.id}-${i}`, role: 'data-label', ...at, text, size: fs - 1, target });\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\t// Line, area and scatter share the point positions.\n\t\t\tconst curve = s.curve ?? spec.curve;\n\t\t\tconst pointValue = (i: number): number | null => {\n\t\t\t\tconst v = stack ? (stack.segments[i]?.[1] ?? null) : s.values[i];\n\t\t\t\treturn v !== null && Number.isFinite(v) ? v : null;\n\t\t\t};\n\t\t\tconst runs: Pt[][] = [];\n\t\t\tlet run: Pt[] = [];\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tconst v = pointValue(i);\n\t\t\t\tif (v === null) {\n\t\t\t\t\tif (run.length) runs.push(run);\n\t\t\t\t\trun = [];\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\trun.push({ c: catCenter(i), v: valuePx(v) });\n\t\t\t}\n\t\t\tif (run.length) runs.push(run);\n\t\t\tconst thin = (r: Pt[]) => {\n\t\t\t\tif (r.length <= MAX_CHART_LINE_POINTS) return r;\n\t\t\t\tconst pts = decimateChartPoints(r.map((p) => ({ x: p.c, y: p.v, p })), MAX_CHART_LINE_POINTS).map((q) => q.p);\n\t\t\t\tctx.warn('points-decimated', `\"${s.name}\" has ${r.length} points; its line is drawn with ${pts.length} (one column of pixels each).`);\n\t\t\t\treturn pts;\n\t\t\t};\n\t\t\tconst drawn = runs.map(thin);\n\n\t\t\tif (type === 'area') {\n\t\t\t\t// Stacked areas fill down to the series below; others down to zero.\n\t\t\t\tconst parts = drawn.map((r) => {\n\t\t\t\t\tconst baseline = stack\n\t\t\t\t\t\t? r.map((pt) => ({ c: pt.c, v: valuePx(stack.segments[Math.round((pt.c - catStart) / band - 0.5)]?.[0] ?? 0) })).reverse()\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t{ c: r[r.length - 1].c, v: info.zero },\n\t\t\t\t\t\t\t\t{ c: r[0].c, v: info.zero }\n\t\t\t\t\t\t\t];\n\t\t\t\t\treturn `${curvePath(r, curve, map)}${stack ? curvePath(baseline, curve, map, false) : baseline.map((pt) => `L${map(pt).map(r2).join(',')}`).join('')}Z`;\n\t\t\t\t});\n\t\t\t\tmarks.push({ kind: 'path', key: `area-${s.id}`, role: 'area', d: parts.join(''), fill: color, opacity: 0.22, target: seriesTarget, selected: selSeries });\n\t\t\t}\n\t\t\tif (type === 'line' || type === 'area') {\n\t\t\t\tmarks.push({ kind: 'path', key: `line-${s.id}`, role: 'line', d: drawn.map((r) => curvePath(r, curve, map)).join(''), fill: 'none', stroke: color, strokeWidth: selSeries ? 3.5 : 2, target: seriesTarget, selected: selSeries });\n\t\t\t}\n\t\t\tconst marker: ChartMarker = s.marker ?? (type === 'scatter' || spec.points ? 'circle' : 'none');\n\t\t\tconst showDots = marker !== 'none';\n\t\t\tconst thinMarkers = n > MAX_CHART_MARKERS;\n\t\t\tconst cells = new Set<string>();\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tconst v = pointValue(i);\n\t\t\t\tif (v === null || s.values[i] === null) continue;\n\t\t\t\tconst [cx, cy] = map({ c: catCenter(i), v: valuePx(v) });\n\t\t\t\tif (thinMarkers) {\n\t\t\t\t\tconst cell = `${Math.round(cx / 2)},${Math.round(cy / 2)}`;\n\t\t\t\t\tif (cells.has(cell)) continue;\n\t\t\t\t\tcells.add(cell);\n\t\t\t\t}\n\t\t\t\tconst target: ChartSelection = { kind: 'point', seriesId: s.id, index: i };\n\t\t\t\tconst selected = ctx.isSelected(target);\n\t\t\t\tconst r = type === 'scatter' ? 4.5 : 3.5;\n\t\t\t\tconst pointColor = chartPointColor(spec, si, i);\n\t\t\t\tconst fill = showDots ? (type === 'scatter' ? pointColor : theme.surface) : 'transparent';\n\t\t\t\t// Without markers the point still gets a transparent target so it can be picked and dragged.\n\t\t\t\tmarks.push(\n\t\t\t\t\tpointMark({ key: `point-${s.id}-${i}`, target, selected: selected || selSeries, opacity: type === 'scatter' ? 0.85 : undefined }, showDots ? marker : 'hit', cx, cy, showDots ? r : 6, fill, showDots ? pointColor : undefined, 2)\n\t\t\t\t);\n\t\t\t\tif (selected) marks.push({ kind: 'circle', key: `point-${s.id}-${i}-selection`, role: 'selection', cx, cy, r: r + 3.5, fill: 'none', stroke: theme.selection, strokeWidth: 1.5 });\n\t\t\t\tif (labelsOn) {\n\t\t\t\t\tconst raw = s.values[i]!;\n\t\t\t\t\tconst shown = percent && stack ? stack.segments[i]![1] - stack.segments[i]![0] : raw;\n\t\t\t\t\tlabelMarks.push({\n\t\t\t\t\t\tkind: 'text',\n\t\t\t\t\t\tkey: `label-${s.id}-${i}`,\n\t\t\t\t\t\trole: 'data-label',\n\t\t\t\t\t\tx: horizontal ? cx + 8 : cx,\n\t\t\t\t\t\ty: horizontal ? cy : cy - 8,\n\t\t\t\t\t\ttext: dataLabel(shown),\n\t\t\t\t\t\tanchor: horizontal ? 'start' : 'middle',\n\t\t\t\t\t\tbaseline: horizontal ? 'middle' : 'bottom',\n\t\t\t\t\t\tsize: fs - 1,\n\t\t\t\t\t\tfill: theme.text,\n\t\t\t\t\t\ttarget\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (trendsAllowed && s.trendlines?.length) {\n\t\t\t// Category charts fit against x = 1, 2, 3, … (as spreadsheets do).\n\t\t\tconst points: [number, number][] = [];\n\t\t\ts.values.forEach((v, i) => v !== null && Number.isFinite(v) && points.push([i + 1, v]));\n\t\t\tconst toPx = (x: number, y: number) => map({ c: catStart + band * (x - 0.5), v: info.raw(y) });\n\t\t\tdrawTrendlines(ctx, plot, s, color, points, toPx, trendLabels);\n\t\t}\n\t}\n\tmarks.push(...labelMarks);\n\tdrawTrendLabels(ctx, plot, trendLabels);\n\tif (hiddenLabels) ctx.warn('data-labels-hidden', `${hiddenLabels} data label${hiddenLabels === 1 ? '' : 's'} did not fit and ${hiddenLabels === 1 ? 'is' : 'are'} hidden.`);\n\treturn {\n\t\tplot,\n\t\tvalueScale: toValueScale(frame.value, horizontal ? 'x' : 'y'),\n\t\t...(frame.value2 ? { valueScale2: toValueScale(frame.value2, horizontal ? 'x' : 'y') } : {}),\n\t\tpercent\n\t};\n}\n\n/** Scatter (with x values) and bubble charts: numeric x against numeric y. */\nexport function layoutXy(ctx: LayoutCtx, area: ChartRect, visible: ChartSeries[]): FamilyResult {\n\tconst { spec, theme, marks, measure, fs } = ctx;\n\tconst bubble = spec.type === 'bubble';\n\tconst pointsOf = (s: ChartSeries) =>\n\t\ts.values\n\t\t\t.map((y, i) => ({ i, x: s.x?.[i] ?? (bubble || !s.x ? i + 1 : null), y, size: s.sizes?.[i] ?? null }))\n\t\t\t.filter((p): p is { i: number; x: number; y: number; size: number | null } => p.x !== null && p.y !== null && Number.isFinite(p.x) && Number.isFinite(p.y));\n\tconst all = visible.map((s) => ({ s, pts: pointsOf(s) }));\n\tlet xlo = Infinity;\n\tlet xhi = -Infinity;\n\tlet ylo = Infinity;\n\tlet yhi = -Infinity;\n\tlet maxSize = 0;\n\tfor (const { s, pts } of all) {\n\t\tfor (const p of pts) {\n\t\t\txlo = Math.min(xlo, p.x);\n\t\t\txhi = Math.max(xhi, p.x);\n\t\t\tylo = Math.min(ylo, p.y);\n\t\t\tyhi = Math.max(yhi, p.y);\n\t\t\tif (p.size !== null && p.size > maxSize) maxSize = p.size;\n\t\t}\n\t\t// Forecasts widen the x axis.\n\t\tfor (const t of s.trendlines ?? []) {\n\t\t\tif (!pts.length) continue;\n\t\t\txlo = Math.min(xlo, Math.min(...pts.map((p) => p.x)) - (t.backward ?? 0));\n\t\t\txhi = Math.max(xhi, Math.max(...pts.map((p) => p.x)) + (t.forward ?? 0));\n\t\t}\n\t}\n\tif (!Number.isFinite(xlo)) [xlo, xhi, ylo, yhi] = [0, 1, 0, 1];\n\tconst titleBand = fs * 1.3 + 6;\n\tconst yAxis = spec.yAxis;\n\tconst xAxis = spec.xAxis;\n\tconst yEst = axisScale(ylo, yhi, area.height, yAxis, ctx.options.valueDomain, true);\n\tconst yText = (t: number, step: number) => formatChartNumber(t, yAxis.format, yAxis.format.decimals ?? stepDecimals(step));\n\tconst left = (yAxis.show ? Math.max(0, ...yEst.ticks.map((t) => measure(yText(t, yEst.step), fs))) + 8 : 2) + (yAxis.title ? titleBand : 0);\n\tconst bottom = (xAxis.show ? fs * 1.6 : 2) + (xAxis.title ? titleBand : 0);\n\tconst plot: ChartRect = { x: area.x + left, y: area.y + fs / 2 + 2, width: Math.max(1, area.width - left - 12), height: Math.max(1, area.height - bottom - fs / 2 - 2) };\n\tconst maxR = bubble ? Math.max(4, Math.min(plot.width, plot.height) * 0.08) : 0;\n\t// Bubbles get room so they are not cut by the frame.\n\tconst inset = bubble ? maxR : 0;\n\tconst yScale = axisScale(ylo, yhi, plot.height, yAxis, ctx.options.valueDomain, true);\n\tconst xScale = axisScale(xlo, xhi, plot.width, xAxis, ctx.options.xDomain, true);\n\tconst xRange: [number, number] = [plot.x + inset, plot.x + plot.width - inset];\n\tconst yRange: [number, number] = [plot.y + plot.height - inset, plot.y + inset];\n\tconst xRaw = (x: number) => linearMap(x, [xScale.min, xScale.max], xRange);\n\tconst yRaw = (y: number) => linearMap(y, [yScale.min, yScale.max], yRange);\n\tconst xPx = (x: number) => xRaw(Math.min(xScale.max, Math.max(xScale.min, x)));\n\tconst yPx = (y: number) => yRaw(Math.min(yScale.max, Math.max(yScale.min, y)));\n\tconst xTarget: ChartSelection = { kind: 'axis', axis: 'x' };\n\tconst yTarget: ChartSelection = { kind: 'axis', axis: 'y' };\n\n\tif (yAxis.gridlines) yScale.ticks.forEach((t, i) => marks.push({ kind: 'line', key: `grid-y-${i}`, role: 'grid', x1: plot.x, y1: yPx(t), x2: plot.x + plot.width, y2: yPx(t), stroke: theme.grid, strokeWidth: 1 }));\n\tif (xAxis.gridlines) xScale.ticks.forEach((t, i) => marks.push({ kind: 'line', key: `grid-x-${i}`, role: 'grid', x1: xPx(t), y1: plot.y, x2: xPx(t), y2: plot.y + plot.height, stroke: theme.grid, strokeWidth: 1 }));\n\tif (yAxis.show) yScale.ticks.forEach((t, i) => marks.push({ kind: 'text', key: `tick-y-${i}`, role: 'tick-label', x: plot.x - 8, y: yPx(t), text: yText(t, yScale.step), anchor: 'end', baseline: 'middle', size: fs, fill: theme.mutedText, target: yTarget }));\n\tif (xAxis.show) {\n\t\tconst y0 = yScale.min <= 0 && yScale.max >= 0 ? yPx(0) : plot.y + plot.height;\n\t\tmarks.push({ kind: 'line', key: 'axis-x', role: 'axis', x1: plot.x, y1: y0, x2: plot.x + plot.width, y2: y0, stroke: theme.axis, strokeWidth: 1, target: xTarget });\n\t\tconst texts = xScale.ticks.map((t) => formatChartNumber(t, xAxis.format, xAxis.format.decimals ?? stepDecimals(xScale.step)));\n\t\tconst widest = Math.max(0, ...texts.map((t) => measure(t, fs)));\n\t\tconst spacing = xScale.ticks.length > 1 ? Math.abs(xPx(xScale.ticks[1]) - xPx(xScale.ticks[0])) : Infinity;\n\t\tconst every = Math.max(1, Math.ceil((widest + 8) / spacing));\n\t\txScale.ticks.forEach((t, i) => {\n\t\t\tif (i % every) return;\n\t\t\tmarks.push({ kind: 'text', key: `tick-x-${i}`, role: 'tick-label', x: xPx(t), y: plot.y + plot.height + 6, text: texts[i], anchor: 'middle', baseline: 'top', size: fs, fill: theme.mutedText, target: xTarget });\n\t\t});\n\t}\n\tif (xAxis.title) marks.push({ kind: 'text', key: 'axis-title-x', role: 'axis-title', x: plot.x + plot.width / 2, y: area.y + area.height, text: xAxis.title, anchor: 'middle', baseline: 'bottom', size: fs + 1, weight: 500, fill: theme.text, target: xTarget });\n\tif (yAxis.title) marks.push({ kind: 'text', key: 'axis-title-y', role: 'axis-title', x: area.x, y: plot.y + plot.height / 2, text: yAxis.title, anchor: 'middle', baseline: 'top', size: fs + 1, weight: 500, fill: theme.text, rotate: -90, target: yTarget });\n\tfor (const axis of ['x', 'y'] as const) {\n\t\tif (!ctx.isSelected({ kind: 'axis', axis })) continue;\n\t\tctx.outline(`axis-${axis}-selection`, axis === 'y' ? { x: area.x, y: plot.y - fs / 2, width: left - 2, height: plot.height + fs } : { x: plot.x - 4, y: plot.y + plot.height + 2, width: plot.width + 8, height: area.y + area.height - plot.y - plot.height - 2 });\n\t}\n\n\tconst labelMarks: ChartMark[] = [];\n\tconst trendLabels: TrendLabel[] = [];\n\t// Bigger bubbles first, so small ones stay clickable on top.\n\tfor (const { s, pts } of all) {\n\t\tconst si = spec.series.indexOf(s);\n\t\tconst color = chartSeriesColor(spec, si);\n\t\tconst type = chartSeriesType(spec, s);\n\t\tconst selSeries = ctx.seriesSelected(s.id);\n\t\tconst seriesTarget: ChartSelection = { kind: 'series', seriesId: s.id };\n\t\tif (type === 'line' || type === 'area') {\n\t\t\tconst xy = pts.map((p) => ({ x: xPx(p.x), y: yPx(p.y) }));\n\t\t\tconst thinned = xy.length > MAX_CHART_LINE_POINTS ? decimateChartPoints(xy, MAX_CHART_LINE_POINTS) : xy;\n\t\t\tif (thinned.length < xy.length) ctx.warn('points-decimated', `\"${s.name}\" has ${xy.length} points; its line is drawn with ${thinned.length}.`);\n\t\t\tconst d = curvePath(thinned.map((p) => ({ c: p.x, v: p.y })), s.curve ?? spec.curve, (p) => [p.c, p.v]);\n\t\t\tif (d) marks.push({ kind: 'path', key: `line-${s.id}`, role: 'line', d, fill: 'none', stroke: color, strokeWidth: selSeries ? 3.5 : 2, target: seriesTarget, selected: selSeries });\n\t\t}\n\t\tconst marker: ChartMarker = bubble ? 'circle' : (s.marker ?? (type === 'scatter' || spec.points ? 'circle' : 'none'));\n\t\tconst ordered = bubble ? [...pts].sort((a, b) => (b.size ?? 0) - (a.size ?? 0)) : pts;\n\t\tconst labelsOn = (s.dataLabels ?? spec.dataLabels) && pts.length <= MAX_CHART_DATA_LABELS;\n\t\tconst labelFormat = s.format ?? yAxis.format;\n\t\tconst cells = new Set<string>();\n\t\tfor (const p of ordered) {\n\t\t\tconst cx = xPx(p.x);\n\t\t\tconst cy = yPx(p.y);\n\t\t\tif (pts.length > MAX_CHART_MARKERS) {\n\t\t\t\tconst cell = `${Math.round(cx / 2)},${Math.round(cy / 2)}`;\n\t\t\t\tif (cells.has(cell)) continue;\n\t\t\t\tcells.add(cell);\n\t\t\t}\n\t\t\tconst target: ChartSelection = { kind: 'point', seriesId: s.id, index: p.i };\n\t\t\tconst selected = ctx.isSelected(target);\n\t\t\tconst pointColor = chartPointColor(spec, si, p.i);\n\t\t\tconst r = bubble ? (maxSize > 0 && p.size !== null && p.size > 0 ? Math.max(2, Math.sqrt(p.size / maxSize) * maxR) : 2) : 4.5;\n\t\t\tif (bubble) marks.push({ kind: 'circle', key: `point-${s.id}-${p.i}`, role: 'point', cx, cy, r, fill: pointColor, stroke: pointColor, strokeWidth: 1, opacity: 0.6, target, selected: selected || selSeries });\n\t\t\telse marks.push(pointMark({ key: `point-${s.id}-${p.i}`, target, selected: selected || selSeries, opacity: 0.85 }, marker === 'none' ? 'hit' : marker, cx, cy, marker === 'none' ? 6 : r, marker === 'none' ? 'transparent' : pointColor, marker === 'none' ? undefined : pointColor, 2));\n\t\t\tif (selected) marks.push({ kind: 'circle', key: `point-${s.id}-${p.i}-selection`, role: 'selection', cx, cy, r: r + 3.5, fill: 'none', stroke: theme.selection, strokeWidth: 1.5 });\n\t\t\tif (labelsOn) labelMarks.push({ kind: 'text', key: `label-${s.id}-${p.i}`, role: 'data-label', x: cx, y: cy - r - 4, text: formatChartNumber(p.y, labelFormat), anchor: 'middle', baseline: 'bottom', size: fs - 1, fill: theme.text, target });\n\t\t}\n\t\tif (s.trendlines?.length) drawTrendlines(ctx, plot, s, color, pts.map((p) => [p.x, p.y]), (x, y) => [xRaw(x), yRaw(y)], trendLabels);\n\t}\n\tmarks.push(...labelMarks);\n\tdrawTrendLabels(ctx, plot, trendLabels);\n\treturn {\n\t\tplot,\n\t\tvalueScale: { axis: 'y', domain: [yScale.min, yScale.max], range: yRange, ticks: yScale.ticks },\n\t\txScale: { axis: 'x', domain: [xScale.min, xScale.max], range: xRange, ticks: xScale.ticks }\n\t};\n}\n\n/** Legend entries for trendlines (dashed lines after their series). */\nexport function trendlineLegendItems(spec: { series: ChartSeries[]; type: string; stacking: string }, color: (i: number) => string) {\n\tif (!chartSupportsTrendlines(spec.type, spec.stacking)) return [];\n\treturn spec.series.flatMap((s, si) =>\n\t\ts.hidden ? [] : (s.trendlines ?? []).map((t, ti) => ({ label: chartTrendlineName(t, s.name), color: t.color ?? color(si), target: { kind: 'trendline', seriesId: s.id, index: ti } as ChartSelection, after: s.id }))\n\t);\n}\n","// Waterfall, funnel, radar, histogram, box-and-whisker and treemap layouts follow\n// gridcraft-main/crates/chart/src/render.rs (`waterfall`, `funnel`, `radar`, `histogram`, `box_whisker`,\n// `treemap`) (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { categoryFrame, toValueScale } from './layout-cartesian.js';\nimport { arcPath, axisScale, contrastingTextColor, r2, truncate, type FamilyResult, type LayoutCtx } from './layout-shared.js';\nimport { formatChartNumber, linearMap, stepDecimals } from './scale.js';\nimport { chartSeriesColor, chartSliceColor } from './spec.js';\nimport { chartBoxStats, chartHistogram, chartSquarify } from './stats.js';\nimport type { ChartMark, ChartRect, ChartSelection, ChartSeries } from './types.js';\n\nconst sliceColor = (ctx: LayoutCtx, series: ChartSeries, i: number) => series.pointColors?.[i] || chartSliceColor(ctx.spec, i);\n\n/** Pie and donut: the first visible series, one slice per category. */\nexport function layoutPie(ctx: LayoutCtx, area: ChartRect, series: ChartSeries): FamilyResult {\n\tconst { spec, theme, marks, fs, selection } = ctx;\n\tconst values = spec.categories.map((_, i) => {\n\t\tconst v = series.values[i];\n\t\treturn v !== null && Number.isFinite(v) ? Math.max(0, v) : 0;\n\t});\n\tconst total = values.reduce((a, b) => a + b, 0);\n\tconst labelsOn = series.dataLabels ?? spec.dataLabels;\n\tconst labelRoom = labelsOn ? fs * 2.2 : 4;\n\tconst outer = Math.max(4, Math.min(area.width, area.height) / 2 - labelRoom);\n\tconst inner = spec.type === 'donut' ? outer * spec.innerRadius : 0;\n\tconst cx = area.x + area.width / 2;\n\tconst cy = area.y + area.height / 2;\n\tconst plot = { x: cx - outer, y: cy - outer, width: outer * 2, height: outer * 2 };\n\tif (total <= 0) {\n\t\tmarks.push({ kind: 'text', key: 'empty', role: 'empty', x: cx, y: cy, text: 'No positive values', anchor: 'middle', baseline: 'middle', size: fs + 1, fill: theme.mutedText });\n\t\treturn { plot };\n\t}\n\tlet angle = 0;\n\tconst format = series.format ?? spec.yAxis.format;\n\tlet hidden = 0;\n\tvalues.forEach((v, i) => {\n\t\tif (v <= 0) return;\n\t\tconst sweep = (v / total) * Math.PI * 2;\n\t\tconst start = angle;\n\t\tconst end = angle + sweep;\n\t\tangle = end;\n\t\tconst target: ChartSelection = { kind: 'point', seriesId: series.id, index: i };\n\t\tconst selected = ctx.isSelected(target) || ctx.isSelected({ kind: 'category', index: i });\n\t\tconst seriesSel = selection?.kind === 'series' && selection.seriesId === series.id;\n\t\t// The selected slice pops out a little.\n\t\tconst mid = (start + end) / 2;\n\t\tconst off = selected ? 6 : 0;\n\t\tconst ox = cx + off * Math.sin(mid);\n\t\tconst oy = cy - off * Math.cos(mid);\n\t\tmarks.push({\n\t\t\tkind: 'path',\n\t\t\tkey: `slice-${i}`,\n\t\t\trole: 'slice',\n\t\t\td: arcPath(ox, oy, outer, inner, start, end),\n\t\t\tfill: sliceColor(ctx, series, i),\n\t\t\tstroke: selected || seriesSel ? theme.selection : theme.surface,\n\t\t\tstrokeWidth: selected || seriesSel ? 2 : 1,\n\t\t\ttarget,\n\t\t\tselected: selected || seriesSel\n\t\t});\n\t\tif (!labelsOn) return;\n\t\tif (sweep <= 0.12) {\n\t\t\thidden++;\n\t\t\treturn;\n\t\t}\n\t\tconst share = v / total;\n\t\tconst text = format.style || format.code ? formatChartNumber(v, format) : `${Math.round(share * 100)}%`;\n\t\tconst lr = outer + fs * 1.1;\n\t\tconst lx = ox + lr * Math.sin(mid);\n\t\tconst ly = oy - lr * Math.cos(mid);\n\t\tconst anchor = Math.abs(Math.sin(mid)) < 0.2 ? 'middle' : Math.sin(mid) > 0 ? 'start' : 'end';\n\t\tmarks.push({ kind: 'text', key: `label-slice-${i}`, role: 'data-label', x: lx, y: ly, text, anchor, baseline: 'middle', size: fs, fill: theme.text, target });\n\t});\n\tif (hidden) ctx.warn('data-labels-hidden', `${hidden} slice label${hidden === 1 ? ' is' : 's are'} hidden: the slices are too thin.`);\n\tif (spec.type === 'donut' && inner > fs * 2) {\n\t\tmarks.push({ kind: 'text', key: 'donut-total', role: 'data-label', x: cx, y: cy, text: formatChartNumber(total, format), anchor: 'middle', baseline: 'middle', size: Math.min(theme.titleSize + 4, inner / 2), weight: 600, fill: theme.text, target: { kind: 'series', seriesId: series.id } });\n\t}\n\treturn { plot };\n}\n\n/** Radar: one spoke per category, one polygon per series. */\nexport function layoutRadar(ctx: LayoutCtx, area: ChartRect, visible: ChartSeries[]): FamilyResult {\n\tconst { spec, theme, marks, fs, measure } = ctx;\n\tconst n = spec.categories.length;\n\tconst labelW = Math.min(area.width * 0.25, Math.max(0, ...spec.categories.map((c) => measure(c, fs))));\n\tconst radius = Math.max(8, Math.min(area.width / 2 - labelW - 8, area.height / 2 - fs * 1.6));\n\tconst cx = area.x + area.width / 2;\n\tconst cy = area.y + area.height / 2;\n\tlet lo = 0;\n\tlet hi = -Infinity;\n\tfor (const s of visible) for (const v of s.values) if (v !== null && Number.isFinite(v)) (lo = Math.min(lo, v)), (hi = Math.max(hi, v));\n\tif (!Number.isFinite(hi)) hi = 1;\n\tconst scale = axisScale(lo, hi, radius, spec.yAxis, ctx.options.valueDomain);\n\tconst rOf = (v: number) => linearMap(Math.min(scale.max, Math.max(scale.min, v)), [scale.min, scale.max], [0, radius]);\n\tconst angle = (i: number) => (i / n) * Math.PI * 2;\n\tconst at = (i: number, r: number): [number, number] => [cx + r * Math.sin(angle(i)), cy - r * Math.cos(angle(i))];\n\tconst yTarget: ChartSelection = { kind: 'axis', axis: 'y' };\n\t// Rings and spokes\n\tif (spec.yAxis.gridlines)\n\t\tscale.ticks.forEach((t, k) => {\n\t\t\tconst r = rOf(t);\n\t\t\tif (r <= 0) return;\n\t\t\tconst d = Array.from({ length: n }, (_, i) => at(i, r)).map(([x, y], i) => `${i ? 'L' : 'M'}${r2(x)},${r2(y)}`).join('') + 'Z';\n\t\t\tmarks.push({ kind: 'path', key: `grid-ring-${k}`, role: 'grid', d, fill: 'none', stroke: theme.grid, strokeWidth: 1 });\n\t\t});\n\tfor (let i = 0; i < n; i++) {\n\t\tconst [x, y] = at(i, radius);\n\t\tmarks.push({ kind: 'line', key: `spoke-${i}`, role: 'axis', x1: cx, y1: cy, x2: x, y2: y, stroke: theme.grid, strokeWidth: 1, target: { kind: 'axis', axis: 'x' } });\n\t\tif (spec.xAxis.show) {\n\t\t\tconst [lx, ly] = at(i, radius + 8);\n\t\t\tconst s = Math.sin(angle(i));\n\t\t\tconst c = Math.cos(angle(i));\n\t\t\tconst target: ChartSelection = { kind: 'category', index: i };\n\t\t\tconst selected = ctx.isSelected(target);\n\t\t\tmarks.push({ kind: 'text', key: `tick-x-${i}`, role: 'tick-label', x: lx, y: ly, text: truncate(spec.categories[i], labelW, fs, measure), anchor: Math.abs(s) < 0.2 ? 'middle' : s > 0 ? 'start' : 'end', baseline: Math.abs(c) < 0.2 ? 'middle' : c > 0 ? 'bottom' : 'top', size: fs, fill: selected ? theme.selection : theme.mutedText, target, selected });\n\t\t}\n\t}\n\tif (spec.yAxis.show)\n\t\tscale.ticks.forEach((t, k) => {\n\t\t\tconst r = rOf(t);\n\t\t\tmarks.push({ kind: 'text', key: `tick-y-${k}`, role: 'tick-label', x: cx + 4, y: cy - r, text: formatChartNumber(t, spec.yAxis.format, spec.yAxis.format.decimals ?? stepDecimals(scale.step)), anchor: 'start', baseline: 'bottom', size: fs - 1, fill: theme.mutedText, target: yTarget });\n\t\t});\n\tfor (const s of visible) {\n\t\tconst si = spec.series.indexOf(s);\n\t\tconst color = chartSeriesColor(spec, si);\n\t\tconst selSeries = ctx.seriesSelected(s.id);\n\t\tconst pts = s.values.map((v, i) => (v !== null && Number.isFinite(v) ? at(i, rOf(v)) : null));\n\t\tconst present = pts.filter((p): p is [number, number] => p !== null);\n\t\tif (!present.length) continue;\n\t\tconst d = present.map(([x, y], i) => `${i ? 'L' : 'M'}${r2(x)},${r2(y)}`).join('') + 'Z';\n\t\tmarks.push({ kind: 'path', key: `area-${s.id}`, role: 'area', d, fill: color, opacity: s.type === 'line' ? 0 : 0.15, target: { kind: 'series', seriesId: s.id }, selected: selSeries });\n\t\tmarks.push({ kind: 'path', key: `line-${s.id}`, role: 'line', d, fill: 'none', stroke: color, strokeWidth: selSeries ? 3.5 : 2, target: { kind: 'series', seriesId: s.id }, selected: selSeries });\n\t\tpts.forEach((p, i) => {\n\t\t\tif (!p) return;\n\t\t\tconst target: ChartSelection = { kind: 'point', seriesId: s.id, index: i };\n\t\t\tconst selected = ctx.isSelected(target);\n\t\t\tmarks.push({ kind: 'circle', key: `point-${s.id}-${i}`, role: 'point', cx: p[0], cy: p[1], r: spec.points ? 3.5 : 6, fill: spec.points ? theme.surface : 'transparent', ...(spec.points ? { stroke: color, strokeWidth: 2 } : {}), target, selected: selected || selSeries });\n\t\t\tif (selected) marks.push({ kind: 'circle', key: `point-${s.id}-${i}-selection`, role: 'selection', cx: p[0], cy: p[1], r: 7, fill: 'none', stroke: theme.selection, strokeWidth: 1.5 });\n\t\t\tif (s.dataLabels ?? spec.dataLabels) marks.push({ kind: 'text', key: `label-${s.id}-${i}`, role: 'data-label', x: p[0], y: p[1] - 6, text: formatChartNumber(s.values[i], s.format ?? spec.yAxis.format), anchor: 'middle', baseline: 'bottom', size: fs - 1, fill: theme.text, target });\n\t\t});\n\t}\n\treturn { plot: { x: cx - radius, y: cy - radius, width: radius * 2, height: radius * 2 } };\n}\n\n/** Waterfall: the first series as running increases (positive colour) and decreases (negative colour). */\nexport function layoutWaterfall(ctx: LayoutCtx, area: ChartRect, series: ChartSeries): FamilyResult {\n\tconst { spec, theme, marks, fs } = ctx;\n\tconst isTotal = (label: string) => /\\b(sub)?total\\b/i.test(label);\n\tconst steps: { label: string; index: number | null; from: number; to: number; total: boolean }[] = [];\n\tlet running = 0;\n\tspec.categories.forEach((label, i) => {\n\t\tconst v = series.values[i];\n\t\tif (isTotal(label)) {\n\t\t\tsteps.push({ label, index: i, from: 0, to: running, total: true });\n\t\t\treturn;\n\t\t}\n\t\tconst delta = v !== null && Number.isFinite(v) ? v : 0;\n\t\tsteps.push({ label, index: i, from: running, to: running + delta, total: false });\n\t\trunning += delta;\n\t});\n\tif (spec.showTotal && !(steps.length && steps[steps.length - 1].total)) steps.push({ label: 'Total', index: null, from: 0, to: running, total: true });\n\tlet lo = 0;\n\tlet hi = 0;\n\tfor (const s of steps) {\n\t\tlo = Math.min(lo, s.from, s.to);\n\t\thi = Math.max(hi, s.from, s.to);\n\t}\n\tconst horizontal = spec.orientation === 'horizontal';\n\tconst frame = categoryFrame(ctx, area, {\n\t\tlabels: steps.map((s) => s.label),\n\t\thorizontal,\n\t\tprimary: { lo, hi, axis: spec.yAxis, format: spec.yAxis.format, frozen: ctx.options.valueDomain, key: 'y' },\n\t\tlabelTarget: (k) => (steps[k].index !== null ? { kind: 'category', index: steps[k].index! } : undefined)\n\t});\n\tconst { band, catCenter, map, value } = frame;\n\tconst w = band * (1 - spec.gapWidth);\n\tconst color = chartSeriesColor(spec, spec.series.indexOf(series));\n\tconst format = series.format ?? spec.yAxis.format;\n\tconst labelsOn = series.dataLabels ?? spec.dataLabels;\n\tlet prevEnd: number | null = null;\n\tsteps.forEach((s, k) => {\n\t\tconst a = value.px(s.from);\n\t\tconst b = value.px(s.to);\n\t\tconst c0 = catCenter(k) - w / 2;\n\t\tconst [x, y] = map({ c: c0, v: Math.min(a, b) });\n\t\tconst rect = horizontal ? { x: Math.min(a, b), y: c0, width: Math.max(1, Math.abs(b - a)), height: w } : { x, y, width: w, height: Math.max(1, Math.abs(b - a)) };\n\t\tconst fill = s.total ? color : s.to >= s.from ? theme.positive : theme.negative;\n\t\tconst target: ChartSelection = s.index !== null ? { kind: 'point', seriesId: series.id, index: s.index } : { kind: 'series', seriesId: series.id };\n\t\tconst selected = ctx.isSelected(target);\n\t\tmarks.push({ kind: 'rect', key: `bar-${series.id}-${s.index ?? 'total'}`, role: 'bar', ...rect, fill, radius: Math.min(2, w / 4), target, selected });\n\t\tif (selected) ctx.outline(`bar-${series.id}-${s.index ?? 'total'}-selection`, { x: rect.x - 2, y: rect.y - 2, width: rect.width + 4, height: rect.height + 4 });\n\t\t// Dashed connector from the previous bar's end to this bar's start.\n\t\tif (prevEnd !== null) {\n\t\t\tconst [x1, y1] = map({ c: catCenter(k - 1) + w / 2, v: value.px(prevEnd) });\n\t\t\tconst [x2, y2] = map({ c: c0, v: value.px(prevEnd) });\n\t\t\tmarks.push({ kind: 'line', key: `connector-${k}`, role: 'connector', x1, y1, x2, y2, stroke: theme.axis, strokeWidth: 1, dash: '3 3' });\n\t\t}\n\t\tprevEnd = s.to;\n\t\tif (labelsOn) {\n\t\t\tconst text = formatChartNumber(s.total ? s.to : s.to - s.from, format);\n\t\t\tconst up = s.to >= s.from;\n\t\t\tconst [lx, ly] = map({ c: catCenter(k), v: (horizontal ? Math.max(a, b) + 4 : up ? Math.min(a, b) - 4 : Math.max(a, b) + 4) });\n\t\t\tmarks.push({ kind: 'text', key: `label-${series.id}-${s.index ?? 'total'}`, role: 'data-label', x: lx, y: ly, text, anchor: horizontal ? 'start' : 'middle', baseline: horizontal ? 'middle' : up ? 'bottom' : 'top', size: fs - 1, fill: theme.text, target });\n\t\t}\n\t});\n\treturn { plot: frame.plot, valueScale: toValueScale(value, horizontal ? 'x' : 'y') };\n}\n\n/** Histogram: every value of the visible series, binned; one bar per series in each bin. */\nexport function layoutHistogram(ctx: LayoutCtx, area: ChartRect, visible: ChartSeries[]): FamilyResult {\n\tconst { spec, marks, fs, theme } = ctx;\n\tconst pooled = visible.flatMap((s) => s.values);\n\tconst bins = chartHistogram(pooled, spec.bins);\n\tif (!bins.length) return { plot: area };\n\tconst edgeFormat = spec.xAxis.format;\n\tconst edges = (b: (typeof bins)[number], k: number) => `${k === 0 ? '[' : '('}${formatChartNumber(b.from, edgeFormat)}, ${formatChartNumber(b.to, edgeFormat)}]`;\n\t// Count per series per bin, with the same edges.\n\tconst counts = visible.map((s) => {\n\t\tconst c = bins.map(() => 0);\n\t\tfor (const v of s.values) {\n\t\t\tif (v === null || !Number.isFinite(v)) continue;\n\t\t\tlet k = bins.findIndex((b) => v <= b.to);\n\t\t\tif (k < 0) k = bins.length - 1;\n\t\t\tc[k]++;\n\t\t}\n\t\treturn c;\n\t});\n\tconst maxCount = Math.max(1, ...counts.flat());\n\tconst frame = categoryFrame(ctx, area, {\n\t\tlabels: bins.map(edges),\n\t\thorizontal: false,\n\t\tprimary: { lo: 0, hi: maxCount, axis: { ...spec.yAxis, format: spec.yAxis.format.code || spec.yAxis.format.style ? spec.yAxis.format : { decimals: 0 } }, format: spec.yAxis.format.code || spec.yAxis.format.style ? spec.yAxis.format : { decimals: 0 }, frozen: null, key: 'y' },\n\t\tlabelTarget: () => undefined\n\t});\n\tconst { band, catCenter, value, plot } = frame;\n\tconst k = visible.length;\n\tconst gap = k > 1 ? band * spec.gapWidth * 0.5 : 0;\n\tconst w = (band - gap) / k;\n\tvisible.forEach((s, si) => {\n\t\tconst color = chartSeriesColor(spec, spec.series.indexOf(s));\n\t\tconst target: ChartSelection = { kind: 'series', seriesId: s.id };\n\t\tconst selected = ctx.seriesSelected(s.id);\n\t\tcounts[si].forEach((c, b) => {\n\t\t\tif (!c) return;\n\t\t\tconst top = value.px(c);\n\t\t\tconst x = catCenter(b) - band / 2 + gap / 2 + si * w;\n\t\t\tmarks.push({ kind: 'rect', key: `bar-${s.id}-${b}`, role: 'bar', x, y: top, width: w, height: value.zero - top, fill: color, stroke: theme.surface, strokeWidth: 0.75, opacity: k > 1 ? 0.85 : undefined, target, selected });\n\t\t\tif (s.dataLabels ?? spec.dataLabels) marks.push({ kind: 'text', key: `label-${s.id}-${b}`, role: 'data-label', x: x + w / 2, y: top - 3, text: String(c), anchor: 'middle', baseline: 'bottom', size: fs - 1, fill: theme.text, target });\n\t\t});\n\t});\n\treturn { plot };\n}\n\n/** Box and whiskers: one box per visible series (quartiles, median, mean ×, whiskers at 1.5 × IQR, outliers). */\nexport function layoutBox(ctx: LayoutCtx, area: ChartRect, visible: ChartSeries[]): FamilyResult {\n\tconst { spec, marks, theme, fs } = ctx;\n\tconst stats = visible.map((s) => chartBoxStats(s.values));\n\tlet lo = Infinity;\n\tlet hi = -Infinity;\n\tfor (const st of stats) if (st) (lo = Math.min(lo, st.min)), (hi = Math.max(hi, st.max));\n\tif (!Number.isFinite(lo)) [lo, hi] = [0, 1];\n\tconst frame = categoryFrame(ctx, area, {\n\t\tlabels: visible.map((s) => s.name),\n\t\thorizontal: false,\n\t\tprimary: { lo, hi, axis: spec.yAxis, format: spec.yAxis.format, frozen: ctx.options.valueDomain, headroom: true, key: 'y' },\n\t\tlabelTarget: (i) => ({ kind: 'series', seriesId: visible[i].id })\n\t});\n\tconst { band, catCenter, value, plot } = frame;\n\tconst bw = Math.min(80, band * (1 - spec.gapWidth) * 0.6);\n\tvisible.forEach((s, i) => {\n\t\tconst st = stats[i];\n\t\tif (!st) return;\n\t\tconst color = chartSeriesColor(spec, spec.series.indexOf(s));\n\t\tconst target: ChartSelection = { kind: 'series', seriesId: s.id };\n\t\tconst selected = ctx.seriesSelected(s.id);\n\t\tconst c = catCenter(i);\n\t\tconst y = value.px;\n\t\tconst line = (key: string, x1: number, y1: number, x2: number, y2: number, width = 1.25, stroke = color) => marks.push({ kind: 'line', key, role: 'whisker', x1, y1, x2, y2, stroke, strokeWidth: width, target });\n\t\tline(`whisker-hi-${s.id}`, c, y(st.upperWhisker), c, y(st.q3));\n\t\tline(`whisker-lo-${s.id}`, c, y(st.q1), c, y(st.lowerWhisker));\n\t\tline(`cap-hi-${s.id}`, c - bw / 4, y(st.upperWhisker), c + bw / 4, y(st.upperWhisker));\n\t\tline(`cap-lo-${s.id}`, c - bw / 4, y(st.lowerWhisker), c + bw / 4, y(st.lowerWhisker));\n\t\tconst top = y(st.q3);\n\t\tconst bottom = y(st.q1);\n\t\tmarks.push({ kind: 'rect', key: `box-${s.id}`, role: 'box', x: c - bw / 2, y: top, width: bw, height: Math.max(0.5, bottom - top), fill: color, opacity: 0.3, stroke: selected ? theme.selection : color, strokeWidth: selected ? 2.5 : 1.5, target, selected });\n\t\tline(`median-${s.id}`, c - bw / 2, y(st.median), c + bw / 2, y(st.median), 2.5);\n\t\tconst my = y(st.mean);\n\t\tmarks.push({ kind: 'path', key: `mean-${s.id}`, role: 'whisker', d: `M${r2(c - 3)},${r2(my - 3)}L${r2(c + 3)},${r2(my + 3)}M${r2(c - 3)},${r2(my + 3)}L${r2(c + 3)},${r2(my - 3)}`, stroke: color, strokeWidth: 1.25, fill: 'none', target });\n\t\tst.outliers.slice(0, 500).forEach((o, k) => marks.push({ kind: 'circle', key: `outlier-${s.id}-${k}`, role: 'outlier', cx: c, cy: y(o), r: 2.5, fill: 'none', stroke: color, strokeWidth: 1, target }));\n\t\tif (s.dataLabels ?? spec.dataLabels) marks.push({ kind: 'text', key: `label-${s.id}-median`, role: 'data-label', x: c + bw / 2 + 4, y: y(st.median), text: formatChartNumber(st.median, s.format ?? spec.yAxis.format), anchor: 'start', baseline: 'middle', size: fs - 1, fill: theme.text, target });\n\t});\n\treturn { plot, valueScale: toValueScale(value, 'y') };\n}\n\n/** Funnel: the first series, one centred bar per category, widths proportional to the values. */\nexport function layoutFunnel(ctx: LayoutCtx, area: ChartRect, series: ChartSeries): FamilyResult {\n\tconst { spec, marks, theme, fs, measure } = ctx;\n\tconst n = spec.categories.length;\n\tconst labelW = spec.xAxis.show ? Math.min(area.width * 0.3, Math.max(0, ...spec.categories.map((c) => measure(c, fs)))) + 10 : 0;\n\tconst plot: ChartRect = { x: area.x + labelW, y: area.y, width: Math.max(1, area.width - labelW), height: area.height };\n\tconst max = Math.max(0, ...series.values.map((v) => (v !== null && Number.isFinite(v) ? Math.abs(v) : 0)));\n\tconst band = plot.height / Math.max(1, n);\n\tconst h = band * (1 - Math.min(0.5, spec.gapWidth * 0.5));\n\tconst format = series.format ?? spec.yAxis.format;\n\tconst labelsOn = series.dataLabels ?? true;\n\tconst cx = plot.x + plot.width / 2;\n\tspec.categories.forEach((label, i) => {\n\t\tconst v = series.values[i];\n\t\tconst cy = plot.y + band * (i + 0.5);\n\t\tconst target: ChartSelection = { kind: 'point', seriesId: series.id, index: i };\n\t\tconst selected = ctx.isSelected(target);\n\t\tif (spec.xAxis.show) {\n\t\t\tconst catTarget: ChartSelection = { kind: 'category', index: i };\n\t\t\tmarks.push({ kind: 'text', key: `tick-x-${i}`, role: 'tick-label', x: plot.x - 8, y: cy, text: truncate(label, labelW - 10, fs, measure), anchor: 'end', baseline: 'middle', size: fs, fill: ctx.isSelected(catTarget) ? theme.selection : theme.mutedText, target: catTarget });\n\t\t}\n\t\tif (v === null || !Number.isFinite(v) || max <= 0) return;\n\t\tconst w = Math.max(1, (Math.abs(v) / max) * plot.width);\n\t\tconst fill = sliceColor(ctx, series, i);\n\t\tmarks.push({ kind: 'rect', key: `bar-${series.id}-${i}`, role: 'bar', x: cx - w / 2, y: cy - h / 2, width: w, height: h, fill, radius: 2, target, selected });\n\t\tif (selected) ctx.outline(`bar-${series.id}-${i}-selection`, { x: cx - w / 2 - 2, y: cy - h / 2 - 2, width: w + 4, height: h + 4 });\n\t\tif (labelsOn) {\n\t\t\tconst text = formatChartNumber(v, format);\n\t\t\tconst fits = measure(text, fs) + 8 <= w && fs + 2 <= h;\n\t\t\tmarks.push({ kind: 'text', key: `label-${series.id}-${i}`, role: 'data-label', x: fits ? cx : cx + w / 2 + 4, y: cy, text, anchor: fits ? 'middle' : 'start', baseline: 'middle', size: fs, fill: fits ? contrastingTextColor(fill) : theme.text, target });\n\t\t}\n\t});\n\treturn { plot };\n}\n\n/** Treemap: the first series' positive values as nested rectangles (squarified), labelled where they fit. */\nexport function layoutTreemap(ctx: LayoutCtx, area: ChartRect, series: ChartSeries): FamilyResult {\n\tconst { spec, marks, theme, fs, measure } = ctx;\n\tconst values = spec.categories.map((_, i) => {\n\t\tconst v = series.values[i];\n\t\treturn v !== null && Number.isFinite(v) ? v : 0;\n\t});\n\tconst rects = chartSquarify(values, area);\n\tconst format = series.format ?? spec.yAxis.format;\n\tconst labelsOn = series.dataLabels ?? true;\n\tlet unlabelled = 0;\n\trects.forEach((r, i) => {\n\t\tif (r.width <= 0 || r.height <= 0) return;\n\t\tconst target: ChartSelection = { kind: 'point', seriesId: series.id, index: i };\n\t\tconst selected = ctx.isSelected(target) || ctx.isSelected({ kind: 'category', index: i });\n\t\tconst fill = sliceColor(ctx, series, i);\n\t\tmarks.push({ kind: 'rect', key: `cell-${i}`, role: 'cell', ...r, fill, stroke: selected ? theme.selection : theme.surface, strokeWidth: selected ? 2.5 : 1.5, target, selected });\n\t\tif (!labelsOn) return;\n\t\tconst room = r.width - 8;\n\t\tif (room < fs * 2 || r.height < fs * 1.5) {\n\t\t\tunlabelled++;\n\t\t\treturn;\n\t\t}\n\t\tconst color = contrastingTextColor(fill);\n\t\tmarks.push({ kind: 'text', key: `label-cell-${i}`, role: 'data-label', x: r.x + 4, y: r.y + 4, text: truncate(spec.categories[i], room, fs, measure), anchor: 'start', baseline: 'top', size: fs, weight: 600, fill: color, target });\n\t\tif (r.height >= fs * 3) marks.push({ kind: 'text', key: `label-value-${i}`, role: 'data-label', x: r.x + 4, y: r.y + 6 + fs * 1.2, text: truncate(formatChartNumber(values[i], format), room, fs - 1, measure), anchor: 'start', baseline: 'top', size: fs - 1, fill: color, target });\n\t});\n\tif (unlabelled) ctx.warn('data-labels-hidden', `${unlabelled} treemap cell${unlabelled === 1 ? ' is' : 's are'} too small for a label.`);\n\treturn { plot: area };\n}\n\nexport type { ChartMark };\n","// The legend height cap and the final non-finite pass follow gridcraft-main/crates/chart/src/render.rs\n// (`legend`, `finalize`) (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { layoutCartesian, layoutXy, trendlineLegendItems } from './layout-cartesian.js';\nimport { layoutBox, layoutFunnel, layoutHistogram, layoutPie, layoutRadar, layoutTreemap, layoutWaterfall } from './layout-families.js';\nimport { estimateChartTextWidth, sameChartSelection, type ChartLayoutOptions, type FamilyResult, type LayoutCtx } from './layout-shared.js';\nimport { formatChartNumber, linearMap } from './scale.js';\nimport { chartColorsByCategory, chartFamily, chartSeriesColor, chartSeriesType, chartSliceColor, DEFAULT_CHART_THEME } from './spec.js';\nimport type { ChartMark, ChartRect, ChartScene, ChartSelection, ChartSpec, ChartTheme, ChartWarning } from './types.js';\n\nexport { contrastingTextColor, estimateChartTextWidth, sameChartSelection, type ChartLayoutOptions, type ChartTextMeasure } from './layout-shared.js';\n\ninterface LegendItem {\n\tlabel: string;\n\tcolor: string;\n\ttarget: ChartSelection;\n\tfaded: boolean;\n\tselected: boolean;\n\tshape: 'square' | 'line' | 'dash';\n}\n\nfunction legendItems(spec: ChartSpec, ctx: LayoutCtx): LegendItem[] {\n\tconst family = chartFamily(spec);\n\t// Funnel bars are labelled along the side already.\n\tif (spec.type === 'funnel') return [];\n\tif (chartColorsByCategory(spec.type)) {\n\t\tconst first = spec.series.find((s) => !s.hidden);\n\t\treturn spec.categories.map((c, i) => ({\n\t\t\tlabel: c,\n\t\t\tcolor: first?.pointColors?.[i] || chartSliceColor(spec, i),\n\t\t\ttarget: { kind: 'category', index: i },\n\t\t\tfaded: false,\n\t\t\tselected: ctx.isSelected({ kind: 'category', index: i }),\n\t\t\tshape: 'square'\n\t\t}));\n\t}\n\tif (family === 'waterfall') {\n\t\tconst first = spec.series.find((s) => !s.hidden);\n\t\tif (!first) return [];\n\t\tconst target: ChartSelection = { kind: 'series', seriesId: first.id };\n\t\treturn [\n\t\t\t{ label: 'Increase', color: ctx.theme.positive, target, faded: false, selected: false, shape: 'square' },\n\t\t\t{ label: 'Decrease', color: ctx.theme.negative, target, faded: false, selected: false, shape: 'square' },\n\t\t\t{ label: 'Total', color: chartSeriesColor(spec, spec.series.indexOf(first)), target, faded: false, selected: false, shape: 'square' }\n\t\t];\n\t}\n\tif (family === 'box') return [];\n\tconst trends = trendlineLegendItems(spec, (i) => chartSeriesColor(spec, i));\n\tconst items: LegendItem[] = [];\n\tspec.series.forEach((s, i) => {\n\t\tconst type = chartSeriesType(spec, s);\n\t\titems.push({\n\t\t\tlabel: s.name,\n\t\t\tcolor: chartSeriesColor(spec, i),\n\t\t\ttarget: { kind: 'series', seriesId: s.id },\n\t\t\tfaded: !!s.hidden,\n\t\t\tselected: ctx.seriesSelected(s.id),\n\t\t\tshape: family === 'cartesian' || family === 'xy' || family === 'radar' ? (type === 'line' ? 'line' : 'square') : 'square'\n\t\t});\n\t\tfor (const t of trends.filter((t) => t.after === s.id)) items.push({ label: t.label, color: t.color, target: t.target, faded: false, selected: ctx.isSelected(t.target), shape: 'dash' });\n\t});\n\treturn items;\n}\n\n/**\n * Lays a chart out as drawing primitives (rects, paths, circles, lines and text) in a\n * `width × height` box. Pure and DOM-free: the React and Svelte canvases render the marks\n * as SVG, `chartSceneToSvg` writes them as a string, and anything else (canvas, PDF) can\n * draw them too. Clickable marks carry the `target` they select; what had to be left out\n * (hidden labels, thinned lines) is listed in `warnings`.\n */\nexport function layoutChart(spec: ChartSpec, options: ChartLayoutOptions): ChartScene {\n\tconst width = Math.max(1, Number.isFinite(options.width) ? options.width : 1);\n\tconst height = Math.max(1, Number.isFinite(options.height) ? options.height : 1);\n\tconst theme: ChartTheme = { ...DEFAULT_CHART_THEME, ...options.theme };\n\tconst selection = options.selection ?? null;\n\tconst marks: ChartMark[] = [];\n\tconst warnings: ChartWarning[] = [];\n\tconst ctx: LayoutCtx = {\n\t\tspec,\n\t\toptions,\n\t\ttheme,\n\t\tmeasure: options.measureText ?? estimateChartTextWidth,\n\t\tfs: theme.fontSize,\n\t\twidth,\n\t\theight,\n\t\tmarks,\n\t\twarnings,\n\t\tselection,\n\t\tisSelected: (target) => sameChartSelection(selection, target),\n\t\tseriesSelected: (id) => selection?.kind === 'series' && selection.seriesId === id,\n\t\toutline: (key, box) => marks.push({ kind: 'rect', key, role: 'selection', ...box, fill: 'none', stroke: theme.selection, strokeWidth: 1, radius: 3 }),\n\t\twarn: (code, message) => {\n\t\t\tif (!warnings.some((w) => w.code === code && w.message === message)) warnings.push({ code, message });\n\t\t}\n\t};\n\tconst pad = 12;\n\tconst fs = theme.fontSize;\n\n\tmarks.push({ kind: 'rect', key: 'background', role: 'background', x: 0, y: 0, width, height, fill: theme.background, target: { kind: 'chart' } });\n\n\t// Titles ----------------------------------------------------------------\n\tlet top = pad;\n\tconst titleMark = (kind: 'title' | 'subtitle', label: string, size: number, weight: number, fill: string) => {\n\t\tconst target: ChartSelection = { kind };\n\t\tconst selected = ctx.isSelected(target);\n\t\tmarks.push({ kind: 'text', key: kind, role: kind, x: width / 2, y: top, text: label, anchor: 'middle', baseline: 'top', size, weight, fill, target, selected });\n\t\tif (selected) {\n\t\t\tconst w = ctx.measure(label, size, weight);\n\t\t\tctx.outline(`${kind}-selection`, { x: width / 2 - w / 2 - 4, y: top - 3, width: w + 8, height: size * 1.25 + 6 });\n\t\t}\n\t\ttop += size * 1.35;\n\t};\n\tif (spec.title) titleMark('title', spec.title, theme.titleSize, 600, theme.text);\n\tif (spec.subtitle) titleMark('subtitle', spec.subtitle, fs + 1, 400, theme.mutedText);\n\tif (spec.title || spec.subtitle) top += 6;\n\n\tconst family = chartFamily(spec);\n\tconst visible = spec.series.filter((s) => !s.hidden);\n\n\t// Legend ----------------------------------------------------------------\n\tconst items = legendItems(spec, ctx);\n\tlet area: ChartRect = { x: pad, y: top, width: width - pad * 2, height: height - top - pad };\n\tconst seriesLegend = family === 'cartesian' || family === 'xy' || family === 'radar' || family === 'histogram';\n\tconst hasTrend = items.some((i) => i.shape === 'dash');\n\tconst showLegend = spec.legend.show && items.length > 0 && (!seriesLegend || spec.series.length > 1 || spec.series.some((s) => s.hidden) || hasTrend);\n\tif (showLegend) area = layoutLegend(items, spec.legend.position, area, ctx, ctx.isSelected({ kind: 'legend' }));\n\n\tconst finish = (result: FamilyResult): ChartScene => {\n\t\tif (options.readout) addReadout(ctx, options.readout, result.plot);\n\t\tconst kept = finalizeMarks(marks, width, height);\n\t\tif (kept.length < marks.length) ctx.warn('values-skipped', `${marks.length - kept.length} mark${marks.length - kept.length === 1 ? ' was' : 's were'} left out: their values are not finite numbers.`);\n\t\treturn {\n\t\t\twidth,\n\t\t\theight,\n\t\t\tplot: result.plot,\n\t\t\tmarks: kept,\n\t\t\tpercent: result.percent ?? false,\n\t\t\ttheme,\n\t\t\twarnings,\n\t\t\t...(result.valueScale ? { valueScale: result.valueScale } : {}),\n\t\t\t...(result.valueScale2 ? { valueScale2: result.valueScale2 } : {}),\n\t\t\t...(result.xScale ? { xScale: result.xScale } : {})\n\t\t};\n\t};\n\tconst empty = (message: string) => {\n\t\tmarks.push({ kind: 'text', key: 'empty', role: 'empty', x: area.x + area.width / 2, y: area.y + area.height / 2, text: message, anchor: 'middle', baseline: 'middle', size: fs + 1, fill: theme.mutedText });\n\t\treturn finish({ plot: { x: area.x, y: area.y, width: 0, height: 0 } });\n\t};\n\tconst hasData = visible.some((s) => s.values.some((v) => v !== null && Number.isFinite(v)));\n\tconst needsCategories = family !== 'histogram' && family !== 'box' && family !== 'xy';\n\tif ((needsCategories && !spec.categories.length) || !visible.length || !hasData) return empty(options.emptyMessage ?? 'No data');\n\n\tswitch (family) {\n\t\tcase 'pie':\n\t\t\treturn finish(layoutPie(ctx, area, visible[0]));\n\t\tcase 'radar':\n\t\t\tif (spec.categories.length < 3) {\n\t\t\t\tctx.warn('type-fallback', 'A radar chart needs at least 3 categories; it is drawn as a line chart until then.');\n\t\t\t\treturn finish(layoutCartesian(ctx, area, visible));\n\t\t\t}\n\t\t\treturn finish(layoutRadar(ctx, area, visible));\n\t\tcase 'waterfall':\n\t\t\treturn finish(layoutWaterfall(ctx, area, visible[0]));\n\t\tcase 'histogram':\n\t\t\treturn finish(layoutHistogram(ctx, area, visible));\n\t\tcase 'box':\n\t\t\treturn finish(layoutBox(ctx, area, visible));\n\t\tcase 'funnel':\n\t\t\treturn finish(layoutFunnel(ctx, area, visible[0]));\n\t\tcase 'treemap':\n\t\t\treturn finish(layoutTreemap(ctx, area, visible[0]));\n\t\tcase 'xy':\n\t\t\treturn finish(layoutXy(ctx, area, visible));\n\t\tdefault:\n\t\t\treturn finish(layoutCartesian(ctx, area, visible));\n\t}\n}\n\nfunction layoutLegend(items: LegendItem[], position: ChartSpec['legend']['position'], area: ChartRect, ctx: LayoutCtx, legendSelected: boolean): ChartRect {\n\tconst { theme, measure, marks } = ctx;\n\tconst fs = theme.fontSize;\n\tconst swatch = 10;\n\tconst rowH = fs * 1.7;\n\tconst itemW = (item: LegendItem) => swatch + 6 + measure(item.label, fs) + 14;\n\tconst placed: { item: LegendItem; x: number; y: number }[] = [];\n\tlet box: ChartRect;\n\tlet rest: ChartRect;\n\tif (position === 'left' || position === 'right') {\n\t\tconst w = Math.min(area.width * 0.35, Math.max(...items.map(itemW)));\n\t\tconst fit = Math.max(1, Math.floor((area.height + 0.5) / rowH));\n\t\tconst shown = items.slice(0, fit);\n\t\tconst h = Math.min(shown.length * rowH, area.height);\n\t\tconst x = position === 'left' ? area.x : area.x + area.width - w;\n\t\tconst y = area.y + (area.height - h) / 2;\n\t\tshown.forEach((item, i) => placed.push({ item, x, y: y + i * rowH + rowH / 2 }));\n\t\tif (shown.length < items.length) ctx.warn('legend-truncated', `The legend shows ${shown.length} of ${items.length} entries; the chart is too short for the rest.`);\n\t\tbox = { x, y, width: w, height: h };\n\t\trest = position === 'left' ? { ...area, x: area.x + w + 8, width: area.width - w - 8 } : { ...area, width: area.width - w - 8 };\n\t} else {\n\t\t// Wrap into rows, each centred; at most 30% of the chart height.\n\t\tconst rows: LegendItem[][] = [[]];\n\t\tlet used = 0;\n\t\tfor (const item of items) {\n\t\t\tconst w = itemW(item);\n\t\t\tif (used + w > area.width && rows[rows.length - 1].length) {\n\t\t\t\trows.push([]);\n\t\t\t\tused = 0;\n\t\t\t}\n\t\t\trows[rows.length - 1].push(item);\n\t\t\tused += w;\n\t\t}\n\t\tconst maxRows = Math.max(1, Math.floor((ctx.height * 0.3) / rowH));\n\t\tconst shown = rows.slice(0, maxRows);\n\t\tconst hiddenCount = rows.slice(maxRows).reduce((t, r) => t + r.length, 0);\n\t\tif (hiddenCount) ctx.warn('legend-truncated', `The legend shows ${items.length - hiddenCount} of ${items.length} entries; the rest do not fit.`);\n\t\tconst h = shown.length * rowH;\n\t\tconst y0 = position === 'top' ? area.y : area.y + area.height - h;\n\t\tshown.forEach((row, r) => {\n\t\t\tconst total = row.reduce((t, item) => t + itemW(item), 0) - 14;\n\t\t\tlet x = area.x + (area.width - total) / 2;\n\t\t\tfor (const item of row) {\n\t\t\t\tplaced.push({ item, x, y: y0 + r * rowH + rowH / 2 });\n\t\t\t\tx += itemW(item);\n\t\t\t}\n\t\t});\n\t\tbox = { x: area.x, y: y0, width: area.width, height: h };\n\t\trest = position === 'top' ? { ...area, y: area.y + h + 6, height: area.height - h - 6 } : { ...area, height: area.height - h - 6 };\n\t}\n\tplaced.forEach(({ item, x, y }, i) => {\n\t\tconst opacity = item.faded ? 0.4 : undefined;\n\t\tif (item.shape === 'line' || item.shape === 'dash')\n\t\t\tmarks.push({ kind: 'line', key: `legend-swatch-${i}`, role: 'legend-swatch', x1: x, y1: y, x2: x + swatch, y2: y, stroke: item.color, strokeWidth: item.shape === 'dash' ? 1.5 : 2.5, ...(item.shape === 'dash' ? { dash: '3 2' } : {}), opacity, target: item.target, selected: item.selected });\n\t\telse marks.push({ kind: 'rect', key: `legend-swatch-${i}`, role: 'legend-swatch', x, y: y - swatch / 2, width: swatch, height: swatch, radius: 2, fill: item.color, opacity, target: item.target, selected: item.selected });\n\t\tmarks.push({\n\t\t\tkind: 'text',\n\t\t\tkey: `legend-label-${i}`,\n\t\t\trole: 'legend-label',\n\t\t\tx: x + swatch + 6,\n\t\t\ty,\n\t\t\ttext: item.label,\n\t\t\tanchor: 'start',\n\t\t\tbaseline: 'middle',\n\t\t\tsize: fs,\n\t\t\tfill: item.selected ? theme.selection : theme.text,\n\t\t\tweight: item.selected ? 600 : undefined,\n\t\t\topacity,\n\t\t\ttarget: item.target,\n\t\t\tselected: item.selected\n\t\t});\n\t});\n\tif (legendSelected) marks.push({ kind: 'rect', key: 'legend-selection', role: 'selection', x: box.x - 4, y: box.y - 2, width: box.width + 8, height: box.height + 4, fill: 'none', stroke: theme.selection, strokeWidth: 1, radius: 3 });\n\treturn rest;\n}\n\n/** Writes the value of a point next to it while it is dragged, kept inside the plot. */\nfunction addReadout(ctx: LayoutCtx, readout: { seriesId: string; index: number }, plot: ChartRect) {\n\tconst { spec, marks, theme, fs, measure } = ctx;\n\tconst series = spec.series.find((s) => s.id === readout.seriesId);\n\tconst value = series?.values[readout.index];\n\tif (!series || value === null || value === undefined) return;\n\tconst mark = marks.find((m) => (m.role === 'point' || m.role === 'bar') && m.target?.kind === 'point' && m.target.seriesId === readout.seriesId && m.target.index === readout.index);\n\tif (!mark) return;\n\tlet ax: number;\n\tlet ay: number;\n\tif (mark.kind === 'rect') {\n\t\tax = mark.x + mark.width / 2;\n\t\tay = mark.y;\n\t} else if (mark.kind === 'circle') {\n\t\tax = mark.cx;\n\t\tay = mark.cy - mark.r;\n\t} else return;\n\tconst axis = series.axis === 'secondary' ? spec.yAxis2 : spec.yAxis;\n\tconst x = series.x?.[readout.index];\n\tconst text =\n\t\tx !== null && x !== undefined && chartFamily(spec) === 'xy'\n\t\t\t? `${formatChartNumber(x, spec.xAxis.format)}, ${formatChartNumber(value, axis.format)}`\n\t\t\t: `${spec.categories[readout.index] ?? ''}: ${formatChartNumber(value, series.format ?? axis.format)}`;\n\tconst w = measure(text, fs, 600) + 10;\n\tconst h = fs + 8;\n\tconst bx = Math.max(plot.x, Math.min(plot.x + plot.width - w, ax - w / 2));\n\tconst by = Math.max(plot.y, Math.min(plot.y + plot.height - h, ay - h - 6));\n\tmarks.push({ kind: 'rect', key: 'drag-readout-box', role: 'drag-readout', x: bx, y: by, width: w, height: h, fill: theme.text, radius: 3, opacity: 0.9 });\n\tmarks.push({ kind: 'text', key: 'drag-readout', role: 'drag-readout', x: bx + w / 2, y: by + h / 2, text, anchor: 'middle', baseline: 'middle', size: fs, weight: 600, fill: theme.surface });\n}\n\nconst finite = (...n: (number | undefined)[]) => n.every((v) => v === undefined || Number.isFinite(v));\n\n/** Drops marks with non-finite coordinates (junk data never reaches a renderer) and clamps the rest near the box. */\nfunction finalizeMarks(marks: ChartMark[], width: number, height: number): ChartMark[] {\n\tconst lim = (v: number, size: number) => Math.max(-size * 4, Math.min(size * 5, v));\n\tconst out: ChartMark[] = [];\n\tfor (const m of marks) {\n\t\tswitch (m.kind) {\n\t\t\tcase 'rect':\n\t\t\t\tif (!finite(m.x, m.y, m.width, m.height)) continue;\n\t\t\t\tout.push({ ...m, x: lim(m.x, width), y: lim(m.y, height), width: Math.max(0, Math.min(m.width, width * 9)), height: Math.max(0, Math.min(m.height, height * 9)) });\n\t\t\t\tbreak;\n\t\t\tcase 'circle':\n\t\t\t\tif (!finite(m.cx, m.cy, m.r)) continue;\n\t\t\t\tout.push({ ...m, cx: lim(m.cx, width), cy: lim(m.cy, height) });\n\t\t\t\tbreak;\n\t\t\tcase 'line':\n\t\t\t\tif (!finite(m.x1, m.y1, m.x2, m.y2)) continue;\n\t\t\t\tout.push({ ...m, x1: lim(m.x1, width), y1: lim(m.y1, height), x2: lim(m.x2, width), y2: lim(m.y2, height) });\n\t\t\t\tbreak;\n\t\t\tcase 'text':\n\t\t\t\tif (!finite(m.x, m.y, m.size)) continue;\n\t\t\t\tout.push(m);\n\t\t\t\tbreak;\n\t\t\tcase 'path':\n\t\t\t\tif (/NaN|Infinity/.test(m.d)) continue;\n\t\t\t\tout.push(m);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * The data value at a scene point along the value axis (for dragging a bar or point), or\n * `undefined` when the scene has no value scale or is percent-stacked. `secondary` reads the\n * secondary axis.\n */\nexport function chartValueAtPoint(scene: ChartScene, point: { x: number; y: number }, secondary = false): number | undefined {\n\tconst scale = secondary ? (scene.valueScale2 ?? scene.valueScale) : scene.valueScale;\n\tif (!scale || scene.percent) return undefined;\n\tconst px = scale.axis === 'y' ? point.y : point.x;\n\treturn linearMap(px, scale.range, scale.domain);\n}\n\n/** The x value at a scene point on a scatter or bubble chart, or `undefined` without a numeric x axis. */\nexport function chartXAtPoint(scene: ChartScene, point: { x: number; y: number }): number | undefined {\n\tconst scale = scene.xScale;\n\tif (!scale) return undefined;\n\treturn linearMap(point.x, scale.range, scale.domain);\n}\n\n/** The value a drag should store: snapped to a tenth of the tick step (or `step`) and kept finite. */\nexport function snapChartValue(scene: ChartScene, value: number, step?: number, ticks: readonly number[] = scene.valueScale?.ticks ?? []): number {\n\tconst unit = step ?? (ticks.length > 1 ? (ticks[1] - ticks[0]) / 10 : 1);\n\tif (!(unit > 0)) return value;\n\tconst snapped = Math.round(value / unit) * unit;\n\treturn Number(snapped.toPrecision(12));\n}\n","// Numeric summaries for agents that check visuals without looking follow\n// filmcraft-main/crates/scopes/src/summary.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See\n// THIRD_PARTY_NOTICES.md.\nimport { checkChartColors, type ChartColorCheck } from './color.js';\nimport { layoutChart } from './layout.js';\nimport type { ChartLayoutOptions } from './layout-shared.js';\nimport { formatChartNumber } from './scale.js';\nimport { chartColorsByCategory, chartFamily, chartSeriesColor, chartSliceColor, CHART_TYPE_LABELS } from './spec.js';\nimport { summarizeChartSeries, type ChartSeriesSummary } from './stats.js';\nimport type { ChartScene, ChartSpec, ChartWarning } from './types.js';\n\nexport interface ChartSummary {\n\ttype: ChartSpec['type'];\n\ttitle: string;\n\tcategories: number;\n\tseries: ChartSeriesSummary[];\n\t/** The value axis as drawn: range and ticks (absent for pies and treemaps). */\n\tvalueAxis?: { min: number; max: number; ticks: number[] };\n\tsecondaryAxis?: { min: number; max: number; ticks: number[] };\n\txAxis?: { min: number; max: number; ticks: number[] };\n\t/** What the layout left out at this size (hidden labels, thinned lines, …). */\n\twarnings: ChartWarning[];\n\t/** Whether the series colours can be told apart (also with colour-blindness). */\n\tcolors: Pick<ChartColorCheck, 'ok' | 'issues'>;\n\t/** A plain-language description (the SVG `<desc>`). */\n\tdescription: string;\n}\n\n/**\n * Numbers about a chart for agents and screen readers: per-series min / max / mean / trend,\n * the axes as drawn, layout warnings at `size`, a colour check and a one-paragraph\n * description. Lets an agent verify a chart without rendering it.\n */\nexport function summarizeChart(spec: ChartSpec, size: Pick<ChartLayoutOptions, 'width' | 'height' | 'measureText'> = { width: 640, height: 400 }, scene: ChartScene = layoutChart(spec, { ...size, selection: null })): ChartSummary {\n\tconst visible = spec.series.filter((s) => !s.hidden);\n\tconst series = visible.map((s) => summarizeChartSeries(s, spec.categories));\n\tconst colors = chartColorsByCategory(spec.type) ? spec.categories.map((_, i) => visible[0]?.pointColors?.[i] || chartSliceColor(spec, i)) : visible.map((s) => chartSeriesColor(spec, spec.series.indexOf(s)));\n\tconst check = checkChartColors(colors, { surface: scene.theme.surface.startsWith('var(') ? '#ffffff' : scene.theme.surface });\n\tconst axis = (s: ChartScene['valueScale']) => (s ? { min: s.domain[0], max: s.domain[1], ticks: [...s.ticks] } : undefined);\n\treturn {\n\t\ttype: spec.type,\n\t\ttitle: spec.title,\n\t\tcategories: spec.categories.length,\n\t\tseries,\n\t\t...(scene.valueScale ? { valueAxis: axis(scene.valueScale) } : {}),\n\t\t...(scene.valueScale2 ? { secondaryAxis: axis(scene.valueScale2) } : {}),\n\t\t...(scene.xScale ? { xAxis: axis(scene.xScale) } : {}),\n\t\twarnings: scene.warnings,\n\t\tcolors: { ok: check.ok, issues: check.issues },\n\t\tdescription: describeChart(spec, series)\n\t};\n}\n\n/** A plain-language description of a chart: type, what it compares, ranges and notable extremes. */\nexport function describeChart(spec: ChartSpec, series = spec.series.filter((s) => !s.hidden).map((s) => summarizeChartSeries(s, spec.categories))): string {\n\tconst kind = CHART_TYPE_LABELS[spec.type].toLowerCase();\n\tconst parts: string[] = [];\n\tconst family = chartFamily(spec);\n\tconst format = spec.yAxis.format;\n\tconst fmt = (v: number | null) => (v === null ? 'blank' : formatChartNumber(v, format));\n\tconst head = spec.title ? `${spec.title}: a ${kind} chart` : `A ${kind} chart`;\n\tif (!series.length || series.every((s) => s.count === 0)) return `${head} with no data.`;\n\tif (family === 'pie' || family === 'funnel' || family === 'treemap') {\n\t\tconst s = series[0];\n\t\tconst total = s.sum ?? 0;\n\t\tconst share = (v: number | null) => (total && v !== null ? ` (${Math.round((v / total) * 100)}%)` : '');\n\t\tparts.push(`${head} of ${s.name} across ${spec.categories.length} categories, totalling ${fmt(s.sum)}.`);\n\t\tparts.push(`The largest is ${s.maxAt} at ${fmt(s.max)}${share(s.max)}; the smallest is ${s.minAt} at ${fmt(s.min)}${share(s.min)}.`);\n\t\treturn parts.join(' ');\n\t}\n\tif (family === 'waterfall') {\n\t\tconst s = spec.series.find((x) => !x.hidden)!;\n\t\tconst steps = s.values.filter((v, i) => v !== null && Number.isFinite(v) && !/\\b(sub)?total\\b/i.test(spec.categories[i] ?? '')) as number[];\n\t\tconst total = steps.reduce((t, v) => t + v, 0);\n\t\tconst up = steps.filter((v) => v > 0).length;\n\t\tconst down = steps.filter((v) => v < 0).length;\n\t\treturn `${head} of ${s.name}: ${up} increase${up === 1 ? '' : 's'} and ${down} decrease${down === 1 ? '' : 's'} over ${spec.categories.length} steps, ending at a total of ${fmt(total)}.`;\n\t}\n\tif (family === 'histogram' || family === 'box') {\n\t\tparts.push(`${head} of ${series.map((s) => s.name).join(', ')}.`);\n\t\tfor (const s of series) parts.push(`${s.name}: ${s.count} values from ${fmt(s.min)} to ${fmt(s.max)}, mean ${fmt(s.mean)}.`);\n\t\treturn parts.join(' ');\n\t}\n\tconst what = family === 'xy' ? `${series.length} series of points` : `${series.length} series over ${spec.categories.length} categories${spec.categories.length ? ` (${spec.categories[0]} to ${spec.categories[spec.categories.length - 1]})` : ''}`;\n\tparts.push(`${head} showing ${what}.`);\n\tfor (const s of series.slice(0, 8)) {\n\t\tif (!s.count) {\n\t\t\tparts.push(`${s.name} has no values.`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst pct = s.change !== null ? Math.round(Math.abs(s.change) * 100) : 0;\n\t\tconst trend = s.trend && s.trend !== 'flat' ? `, ${s.trend}${pct ? `, ${s.change! > 0 ? 'up' : 'down'} ${pct}% from first to last` : ''}` : s.trend === 'flat' ? ', roughly flat' : '';\n\t\tparts.push(`${s.name} ranges from ${fmt(s.min)} (${s.minAt}) to ${fmt(s.max)} (${s.maxAt})${trend}.`);\n\t}\n\tif (series.length > 8) parts.push(`${series.length - 8} more series are not described.`);\n\treturn parts.join(' ');\n}\n","// `<title>` and `<desc>` on exported SVG follow vectorcraft-main/crates/svg/src/export.rs (MIT OR Apache-2.0,\n// © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { layoutChart, type ChartLayoutOptions } from './layout.js';\nimport { describeChart } from './summary.js';\nimport type { ChartMark, ChartScene, ChartSpec, ChartTextMark } from './types.js';\n\n/** SVG `dominant-baseline` for a text mark's baseline (shared by every renderer). */\nexport function chartTextBaseline(baseline: ChartTextMark['baseline']): 'hanging' | 'central' | 'text-after-edge' {\n\treturn baseline === 'top' ? 'hanging' : baseline === 'middle' ? 'central' : 'text-after-edge';\n}\n\n/** SVG `transform` for a rotated text mark, if any. */\nexport function chartTextTransform(mark: ChartTextMark): string | undefined {\n\treturn mark.rotate ? `rotate(${mark.rotate} ${mark.x} ${mark.y})` : undefined;\n}\n\nconst escape = (text: string) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n\nfunction attrs(values: Record<string, string | number | undefined>): string {\n\treturn Object.entries(values)\n\t\t.filter(([, v]) => v !== undefined && v !== '')\n\t\t.map(([k, v]) => ` ${k}=\"${escape(String(v))}\"`)\n\t\t.join('');\n}\n\nfunction markToSvg(mark: ChartMark, fontFamily: string): string {\n\tconst common = { opacity: mark.opacity, 'data-role': mark.role };\n\tswitch (mark.kind) {\n\t\tcase 'rect':\n\t\t\treturn `<rect${attrs({ x: mark.x, y: mark.y, width: mark.width, height: mark.height, rx: mark.radius, fill: mark.fill, stroke: mark.stroke, 'stroke-width': mark.strokeWidth, ...common })}/>`;\n\t\tcase 'path':\n\t\t\treturn `<path${attrs({ d: mark.d, fill: mark.fill ?? 'none', stroke: mark.stroke, 'stroke-width': mark.strokeWidth, 'stroke-dasharray': mark.dash, 'stroke-linejoin': 'round', 'stroke-linecap': 'round', ...common })}/>`;\n\t\tcase 'circle':\n\t\t\treturn `<circle${attrs({ cx: mark.cx, cy: mark.cy, r: mark.r, fill: mark.fill, stroke: mark.stroke, 'stroke-width': mark.strokeWidth, ...common })}/>`;\n\t\tcase 'line':\n\t\t\treturn `<line${attrs({ x1: mark.x1, y1: mark.y1, x2: mark.x2, y2: mark.y2, stroke: mark.stroke, 'stroke-width': mark.strokeWidth, 'stroke-dasharray': mark.dash, ...common })}/>`;\n\t\tcase 'text':\n\t\t\treturn `<text${attrs({\n\t\t\t\tx: mark.x,\n\t\t\t\ty: mark.y,\n\t\t\t\t'text-anchor': mark.anchor,\n\t\t\t\t'dominant-baseline': chartTextBaseline(mark.baseline),\n\t\t\t\t'font-size': mark.size,\n\t\t\t\t'font-weight': mark.weight,\n\t\t\t\t'font-family': fontFamily,\n\t\t\t\tfill: mark.fill,\n\t\t\t\ttransform: chartTextTransform(mark),\n\t\t\t\t...common\n\t\t\t})}>${escape(mark.text)}</text>`;\n\t}\n}\n\nexport interface ChartSvgOptions {\n\t/** Leave out selection outlines (default `true`: exports show the chart only). */\n\thideSelection?: boolean;\n\t/** Accessible title (default: the chart title). */\n\tariaLabel?: string;\n\t/** A longer description written as `<desc>` (`chartToSvg` defaults to `describeChart`). */\n\tdescription?: string;\n}\n\n/** Writes a laid-out scene as a standalone SVG document string. */\nexport function chartSceneToSvg(scene: ChartScene, options: ChartSvgOptions = {}): string {\n\tconst hide = options.hideSelection ?? true;\n\tconst font = scene.theme.fontFamily;\n\tconst body = scene.marks\n\t\t.filter((m) => !(hide && m.role === 'selection'))\n\t\t.map((m) => markToSvg(m, font))\n\t\t.join('');\n\tconst label = options.ariaLabel;\n\tconst desc = options.description;\n\tconst labelled = [label ? 'chart-title' : '', desc ? 'chart-desc' : ''].filter(Boolean).join(' ');\n\tconst head = `${label ? `<title id=\"chart-title\">${escape(label)}</title>` : ''}${desc ? `<desc id=\"chart-desc\">${escape(desc)}</desc>` : ''}`;\n\treturn `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${scene.width}\" height=\"${scene.height}\" viewBox=\"0 0 ${scene.width} ${scene.height}\" role=\"img\"${label ? ` aria-label=\"${escape(label)}\"` : ''}${labelled ? ` aria-labelledby=\"${labelled}\"` : ''}>${head}${body}</svg>`;\n}\n\n/** Lays out and writes a chart as SVG, e.g. for export or server rendering. */\nexport function chartToSvg(spec: ChartSpec, options: Omit<ChartLayoutOptions, 'selection'> & ChartSvgOptions): string {\n\tconst scene = layoutChart(spec, { ...options, selection: null });\n\treturn chartSceneToSvg(scene, { ...options, ariaLabel: options.ariaLabel ?? (spec.title || undefined), description: options.description ?? describeChart(spec) });\n}\n","// Ported from gridcraft-main/crates/chart/src/sparkline.rs (MIT OR Apache-2.0, © ArtCraft Team and\n// contributors). See THIRD_PARTY_NOTICES.md.\nimport { r2 } from './layout-shared.js';\nimport { chartSceneToSvg } from './svg.js';\nimport { DEFAULT_CHART_THEME } from './spec.js';\nimport type { ChartMark, ChartScene, ChartValue } from './types.js';\n\nexport type ChartSparklineKind = 'line' | 'column' | 'win-loss';\n\nexport interface ChartSparklineOptions {\n\tkind?: ChartSparklineKind;\n\twidth: number;\n\theight: number;\n\t/** Line, positive column and win colour (default the first palette colour). */\n\tcolor?: string;\n\t/** Negative column and loss colour (default red). */\n\tnegativeColor?: string;\n\t/** Dots on every line point (thinned past 500). */\n\tmarkers?: boolean;\n\t/** Highlight the highest and lowest point of a line (or column). */\n\thighLow?: boolean;\n\t/** Fixed value range (default: the data, including 0 for columns). */\n\tmin?: number;\n\tmax?: number;\n}\n\nconst MAX_POINTS = 100_000;\n\n/**\n * Lays out a word-sized chart (a sparkline) as marks: a line broken at gaps, columns\n * (negatives in `negativeColor`) or win/loss bars of equal height. Long lines are thinned past\n * 4000 points. Returns a scene with no axes, legend or targets.\n */\nexport function layoutSparkline(values: readonly ChartValue[], options: ChartSparklineOptions): ChartScene {\n\tconst kind = options.kind ?? 'line';\n\tconst w = Number.isFinite(options.width) ? Math.max(1, options.width) : 1;\n\tconst h = Number.isFinite(options.height) ? Math.max(1, options.height) : 1;\n\tconst color = options.color ?? '#4269d0';\n\tconst negative = options.negativeColor ?? '#e5484d';\n\tconst theme = { ...DEFAULT_CHART_THEME, background: 'transparent' };\n\tconst marks: ChartMark[] = [];\n\tconst scene: ChartScene = { width: w, height: h, plot: { x: 0, y: 0, width: w, height: h }, marks, percent: false, theme, warnings: [] };\n\tconst vals = values.slice(0, MAX_POINTS).map((v) => (v !== null && Number.isFinite(v) ? Math.max(-1e300, Math.min(1e300, v)) : null));\n\tconst n = vals.length;\n\tif (!n) return scene;\n\tconst pad = Math.max(0.5, Math.min(2, h * 0.1));\n\tconst x0 = pad;\n\tconst y0 = pad;\n\tconst iw = Math.max(0.5, w - 2 * pad);\n\tconst ih = Math.max(0.5, h - 2 * pad);\n\tlet lo = Infinity;\n\tlet hi = -Infinity;\n\tfor (const v of vals) if (v !== null) (lo = Math.min(lo, v)), (hi = Math.max(hi, v));\n\tif (!Number.isFinite(lo)) return scene;\n\tif (options.min !== undefined && Number.isFinite(options.min)) lo = options.min;\n\tif (options.max !== undefined && Number.isFinite(options.max)) hi = options.max;\n\tlet hiAt = -1;\n\tlet loAt = -1;\n\tvals.forEach((v, i) => {\n\t\tif (v === null) return;\n\t\tif (hiAt < 0 || v > vals[hiAt]!) hiAt = i;\n\t\tif (loAt < 0 || v < vals[loAt]!) loAt = i;\n\t});\n\tif (kind === 'line') {\n\t\tconst span = hi - lo;\n\t\tconst fy = (v: number) => y0 + ih - (span > 0 ? (v - lo) / span : 0.5) * ih;\n\t\tconst fx = (j: number) => (n > 1 ? x0 + (j / (n - 1)) * iw : x0 + iw / 2);\n\t\tlet d = '';\n\t\tlet run: [number, number][] = [];\n\t\tconst flush = () => {\n\t\t\tif (run.length >= 2) {\n\t\t\t\tconst pts = run.length > 4000 ? run.filter((_, i) => i % (Math.floor(run.length / 2000) + 1) === 0) : run;\n\t\t\t\td += pts.map(([x, y], i) => `${i ? 'L' : 'M'}${r2(x)},${r2(y)}`).join('');\n\t\t\t}\n\t\t\trun = [];\n\t\t};\n\t\tvals.forEach((v, j) => (v === null ? flush() : run.push([fx(j), fy(v)])));\n\t\tflush();\n\t\tif (d) marks.push({ kind: 'path', key: 'sparkline', role: 'line', d, fill: 'none', stroke: color, strokeWidth: 1.25 });\n\t\tconst r = Math.max(1, Math.min(3, h * 0.08));\n\t\tif (options.markers || n === 1) {\n\t\t\tconst step = Math.max(1, Math.floor(n / 500));\n\t\t\tvals.forEach((v, j) => {\n\t\t\t\tif (v !== null && j % step === 0) marks.push({ kind: 'circle', key: `point-${j}`, role: 'point', cx: fx(j), cy: fy(v), r, fill: color });\n\t\t\t});\n\t\t}\n\t\tif (options.highLow && n > 1) {\n\t\t\tif (hiAt >= 0) marks.push({ kind: 'circle', key: 'high', role: 'point', cx: fx(hiAt), cy: fy(vals[hiAt]!), r: r + 0.5, fill: color });\n\t\t\tif (loAt >= 0 && loAt !== hiAt) marks.push({ kind: 'circle', key: 'low', role: 'point', cx: fx(loAt), cy: fy(vals[loAt]!), r: r + 0.5, fill: negative });\n\t\t}\n\t\treturn scene;\n\t}\n\tconst slot = iw / n;\n\tconst bw = Math.max(0.25, slot * 0.8);\n\tconst win = kind === 'win-loss';\n\tconst lo0 = win ? -1 : Math.min(lo, 0);\n\tconst hi0 = win ? 1 : Math.max(hi, 0);\n\tconst span = hi0 - lo0;\n\tconst fy = (v: number) => (span > 0 ? y0 + ih - ((v - lo0) / span) * ih : y0 + ih);\n\tconst base = fy(0);\n\tvals.forEach((raw, j) => {\n\t\tif (raw === null) return;\n\t\tconst v = win ? Math.sign(raw) : raw;\n\t\tif (win && v === 0) return;\n\t\tconst top = fy(v);\n\t\tconst highlight = options.highLow && !win && (j === hiAt || j === loAt);\n\t\tmarks.push({ kind: 'rect', key: `bar-${j}`, role: 'bar', x: x0 + j * slot + (slot - bw) / 2, y: Math.min(top, base), width: bw, height: Math.max(0.5, Math.abs(top - base)), fill: v < 0 ? negative : color, opacity: options.highLow && !win && !highlight ? 0.6 : undefined });\n\t});\n\treturn scene;\n}\n\n/** A sparkline as a standalone SVG string (e.g. for an inline image in rich text). */\nexport function sparklineToSvg(values: readonly ChartValue[], options: ChartSparklineOptions & { ariaLabel?: string }): string {\n\treturn chartSceneToSvg(layoutSparkline(values, options), { ariaLabel: options.ariaLabel });\n}\n","// Quick layouts and colour schemes, as GridCraft's `chart.quickLayout` and `chart.changeColors` offer them\n// (gridcraft-main/crates/engine/src/cmd/extra.rs; MIT OR Apache-2.0, © ArtCraft Team and contributors).\n// See THIRD_PARTY_NOTICES.md.\nimport { shadeChartColor } from './color.js';\nimport { DEFAULT_CHART_PALETTE } from './spec.js';\nimport type { ChartAxis, ChartLegend, ChartSpec } from './types.js';\n\n/** A partial change several fields at once (what `ChartController.update` takes). */\nexport type ChartPresetPatch = Partial<Omit<ChartSpec, 'version' | 'xAxis' | 'yAxis' | 'yAxis2' | 'legend' | 'series' | 'categories'>> & {\n\txAxis?: Partial<ChartAxis>;\n\tyAxis?: Partial<ChartAxis>;\n\tyAxis2?: Partial<ChartAxis>;\n\tlegend?: Partial<ChartLegend>;\n};\n\nexport interface ChartLayoutPreset {\n\tid: string;\n\tlabel: string;\n\tdescription: string;\n\tpatch: ChartPresetPatch;\n}\n\n/** Quick layouts: legend, labels and grid lines set together. */\nexport const CHART_LAYOUT_PRESETS: readonly ChartLayoutPreset[] = [\n\t{ id: 'standard', label: 'Standard', description: 'Legend at the bottom, value grid lines, no data labels.', patch: { legend: { show: true, position: 'bottom' }, dataLabels: false, xAxis: { gridlines: false, show: true }, yAxis: { gridlines: true, show: true } } },\n\t{ id: 'minimal', label: 'Minimal', description: 'No legend, grid lines or axis titles; the data speaks.', patch: { legend: { show: false }, dataLabels: false, xAxis: { gridlines: false, title: '' }, yAxis: { gridlines: false, title: '' } } },\n\t{ id: 'labelled', label: 'Labelled', description: 'Values written on the marks, no value axis or grid lines.', patch: { dataLabels: true, labelPosition: 'auto', yAxis: { show: false, gridlines: false }, xAxis: { gridlines: false } } },\n\t{ id: 'legend-right', label: 'Legend on the right', description: 'Legend beside the plot, value grid lines.', patch: { legend: { show: true, position: 'right' }, yAxis: { gridlines: true } } },\n\t{ id: 'presentation', label: 'Presentation', description: 'Legend on top, data labels, light grid.', patch: { legend: { show: true, position: 'top' }, dataLabels: true, yAxis: { gridlines: true }, xAxis: { gridlines: false } } },\n\t{ id: 'analysis', label: 'Analysis', description: 'Grid lines on both axes, point markers, legend at the bottom.', patch: { legend: { show: true, position: 'bottom' }, points: true, dataLabels: false, xAxis: { gridlines: true }, yAxis: { gridlines: true } } }\n];\n\nexport interface ChartColorScheme {\n\tid: string;\n\tlabel: string;\n\tdescription: string;\n\tpalette: readonly string[];\n}\n\n/** Shades of one hue, dark to light (for monochrome schemes). */\nexport function monochromeChartPalette(base: string, count = 6): string[] {\n\tconst steps = count <= 1 ? [0] : Array.from({ length: count }, (_, i) => -0.45 + (1.05 * i) / (count - 1));\n\treturn steps.map((t) => shadeChartColor(base, t));\n}\n\n/** Named palettes. `default` and `okabe-ito` are colour-blind friendly. */\nexport const CHART_COLOR_SCHEMES: readonly ChartColorScheme[] = [\n\t{ id: 'default', label: 'Default', description: 'Ten distinct colours, readable on light and dark backgrounds.', palette: DEFAULT_CHART_PALETTE },\n\t{ id: 'okabe-ito', label: 'Okabe–Ito', description: 'Eight colours chosen to stay distinct with colour-blindness.', palette: ['#e69f00', '#56b4e9', '#009e73', '#f0e442', '#0072b2', '#d55e00', '#cc79a7', '#000000'] },\n\t{ id: 'office', label: 'Office', description: 'The six accent colours of the default Office theme.', palette: ['#4472c4', '#ed7d31', '#a5a5a5', '#ffc000', '#5b9bd5', '#70ad47'] },\n\t{ id: 'warm', label: 'Warm', description: 'Reds, oranges and yellows.', palette: ['#b2182b', '#d6604d', '#f4a582', '#e08214', '#fdb863', '#8c510a'] },\n\t{ id: 'cool', label: 'Cool', description: 'Blues, teals and purples.', palette: ['#2166ac', '#4393c3', '#35978f', '#80cdc1', '#762a83', '#9970ab'] },\n\t{ id: 'monochrome-blue', label: 'Monochrome blue', description: 'Shades of one blue.', palette: monochromeChartPalette('#4269d0') },\n\t{ id: 'monochrome-green', label: 'Monochrome green', description: 'Shades of one green.', palette: monochromeChartPalette('#3ca951') },\n\t{ id: 'monochrome-orange', label: 'Monochrome orange', description: 'Shades of one orange.', palette: monochromeChartPalette('#e8710a') },\n\t{ id: 'monochrome-gray', label: 'Monochrome grey', description: 'Shades of grey.', palette: monochromeChartPalette('#6b7280') }\n];\n\n/** The change a named layout and / or colour scheme makes, or a sentence saying which names exist. */\nexport function chartPresetPatch(options: { layout?: string; colors?: string }): { ok: true; patch: ChartPresetPatch } | { ok: false; message: string } {\n\tconst patch: ChartPresetPatch = {};\n\tif (options.layout !== undefined) {\n\t\tconst preset = CHART_LAYOUT_PRESETS.find((p) => p.id === options.layout);\n\t\tif (!preset) return { ok: false, message: `There is no layout \"${options.layout}\"; expected one of ${CHART_LAYOUT_PRESETS.map((p) => `\"${p.id}\"`).join(', ')}.` };\n\t\tObject.assign(patch, preset.patch);\n\t}\n\tif (options.colors !== undefined) {\n\t\tconst scheme = CHART_COLOR_SCHEMES.find((p) => p.id === options.colors);\n\t\tif (!scheme) return { ok: false, message: `There is no colour scheme \"${options.colors}\"; expected one of ${CHART_COLOR_SCHEMES.map((p) => `\"${p.id}\"`).join(', ')}.` };\n\t\tpatch.palette = [...scheme.palette];\n\t}\n\tif (options.layout === undefined && options.colors === undefined) return { ok: false, message: 'Name a layout, a colour scheme or both.' };\n\treturn { ok: true, patch };\n}\n","// Ported from gridcraft-main/crates/engine/src/cmd/insert.rs (`series_from_range`, `scatter_x_from_first`,\n// `recommend_charts`) (MIT OR Apache-2.0, © ArtCraft Team and contributors), extended for the chart types\n// this editor adds. See THIRD_PARTY_NOTICES.md.\nimport { parseChartDate } from './date.js';\nimport { chartDataFromTable, parseChartValue } from './spec.js';\nimport type { ChartIssue, ChartSeries, ChartStacking, ChartType } from './types.js';\n\nexport interface ChartTableShape {\n\t/** The first row holds series names (some text, every value cell text or blank). */\n\theaderRow: boolean;\n\t/** The first column holds category labels (all text, or a blank top-left cell above a header row). */\n\tlabelColumn: boolean;\n\t/** Series run along rows (the block is much wider than tall). */\n\tbyRows: boolean;\n\tseries: number;\n\t/** Points per series. */\n\tpoints: number;\n\tanyNumber: boolean;\n\tnonNegative: boolean;\n\tmixedSigns: boolean;\n\t/** The category labels read as dates. */\n\tdates: boolean;\n}\n\nconst blank = (c: unknown) => c === null || c === undefined || String(c).trim() === '';\nconst isText = (c: unknown) => blank(c) || parseChartValue(c) === undefined;\n\n/**\n * Reads the shape of a block of cells the way spreadsheets do: a header row when the first\n * row is text, a label column when the first column is text (or the top-left cell is blank\n * above a header row, the convention for years and x values), and series along the longer side.\n */\nexport function analyzeChartTable(rows: ReadonlyArray<ReadonlyArray<unknown>>): ChartTableShape {\n\tconst grid = rows.filter((r) => r.some((c) => !blank(c)));\n\tconst height = grid.length;\n\tconst width = Math.max(0, ...grid.map((r) => r.length));\n\tconst cell = (r: number, c: number) => grid[r]?.[c];\n\tconst headerRow = height > 1 && grid[0].some((c) => !blank(c) && isText(c)) && Array.from({ length: width - 1 }, (_, i) => i + 1).every((c) => isText(cell(0, c)));\n\tconst blankCorner = headerRow && blank(cell(0, 0));\n\tconst labelColumn = width > 1 && (blankCorner || Array.from({ length: height - (headerRow ? 1 : 0) }, (_, i) => i + (headerRow ? 1 : 0)).every((r) => isText(cell(r, 0))));\n\tconst byRows = width > height + 1;\n\tconst dataRows = height - (headerRow ? 1 : 0);\n\tconst dataCols = width - (labelColumn ? 1 : 0);\n\tlet anyNumber = false;\n\tlet nonNegative = true;\n\tlet anyNegative = false;\n\tlet anyPositive = false;\n\tfor (let r = headerRow ? 1 : 0; r < height; r++)\n\t\tfor (let c = labelColumn ? 1 : 0; c < width; c++) {\n\t\t\tconst v = parseChartValue(cell(r, c));\n\t\t\tif (typeof v !== 'number') continue;\n\t\t\tanyNumber = true;\n\t\t\tif (v < 0) {\n\t\t\t\tnonNegative = false;\n\t\t\t\tanyNegative = true;\n\t\t\t} else if (v > 0) anyPositive = true;\n\t\t}\n\tconst labels = byRows ? grid[0]?.slice(labelColumn ? 1 : 0) ?? [] : grid.slice(headerRow ? 1 : 0).map((r) => r[0]);\n\tconst dates = (byRows ? headerRow : labelColumn) && labels.length > 1 && labels.filter((l) => !blank(l) && parseChartDate(String(l)) !== null).length >= labels.length * 0.8;\n\treturn {\n\t\theaderRow,\n\t\tlabelColumn,\n\t\tbyRows,\n\t\tseries: Math.max(0, byRows ? dataRows : dataCols),\n\t\tpoints: Math.max(0, byRows ? dataCols : dataRows),\n\t\tanyNumber,\n\t\tnonNegative,\n\t\tmixedSigns: anyNegative && anyPositive,\n\t\tdates\n\t};\n}\n\nexport interface ChartRecommendation {\n\ttype: ChartType;\n\tstacking?: ChartStacking;\n\tlabel: string;\n\t/** Why it suits the data, as a sentence. */\n\treason: string;\n}\n\n/**\n * Chart types that suit the shape of a block of cells, best first. A heuristic from the shape\n * (series count, points per series, text or date categories, negative values), not a copy of\n * any spreadsheet's ranking.\n */\nexport function recommendChartTypes(rows: ReadonlyArray<ReadonlyArray<unknown>>): ChartRecommendation[] {\n\tconst shape = analyzeChartTable(rows);\n\tif (!shape.anyNumber || !shape.series) return [];\n\treturn recommendForShape(shape);\n}\n\nexport function recommendForShape(shape: Omit<ChartTableShape, 'headerRow' | 'byRows'> & Partial<ChartTableShape>): ChartRecommendation[] {\n\tconst out: ChartRecommendation[] = [];\n\tconst add = (type: ChartType, label: string, reason: string, stacking?: ChartStacking) => out.push({ type, label, reason, ...(stacking ? { stacking } : {}) });\n\tif (shape.series === 2 && !shape.labelColumn && !shape.byRows) {\n\t\tadd('scatter', 'Scatter', 'Two numeric columns without labels: the first is x, the second y.');\n\t\tadd('line', 'Line', 'Shows the second column in order.');\n\t\tadd('bar', 'Column', 'Compares the values side by side.');\n\t\treturn out;\n\t}\n\tif (shape.series === 1 && !shape.labelColumn && shape.points > 20) {\n\t\tadd('histogram', 'Histogram', 'Many unlabelled values: shows how they are distributed.');\n\t\tadd('box', 'Box plot', 'Summarises the spread: quartiles, median and outliers.');\n\t\tadd('line', 'Line', 'Shows the values in order.');\n\t\treturn out;\n\t}\n\tif (shape.dates) {\n\t\tadd('line', 'Line', 'The categories are dates: a line shows change over time.');\n\t\tadd('area', 'Area', 'Shows change over time with volume.');\n\t\tadd('bar', 'Column', 'Compares each period.');\n\t\tif (shape.series > 1) add('area', 'Stacked area', 'Shows how the parts add up over time.', 'stacked');\n\t\treturn out;\n\t}\n\tif (shape.series === 1) {\n\t\tif (shape.points > 12) {\n\t\t\tadd('line', 'Line', 'One long series: a line shows its shape.');\n\t\t\tadd('bar', 'Column', 'Compares every value.');\n\t\t\tadd('area', 'Area', 'Emphasises the volume under the series.');\n\t\t} else {\n\t\t\tadd('bar', 'Column', 'One short series: columns compare the values.');\n\t\t\tif (shape.mixedSigns) add('waterfall', 'Waterfall', 'Positive and negative values: shows how they add up to a total.');\n\t\t\tadd('bar', 'Bar', 'Horizontal bars fit long category names.');\n\t\t\tif (shape.nonNegative && shape.points >= 2) {\n\t\t\t\tadd('pie', 'Pie', 'Shares of a whole (all values are positive).');\n\t\t\t\tadd('donut', 'Donut', 'Shares of a whole with the total in the middle.');\n\t\t\t\tif (shape.points >= 5) add('treemap', 'Treemap', 'Compares many shares by area.');\n\t\t\t\tadd('funnel', 'Funnel', 'Shows stages that narrow down.');\n\t\t\t}\n\t\t\tadd('line', 'Line', 'Shows the values in order.');\n\t\t}\n\t\treturn out;\n\t}\n\tif (shape.points > 12) {\n\t\tadd('line', 'Line', 'Several long series: lines keep them readable.');\n\t\tadd('bar', 'Column', 'Compares the series at each category.');\n\t\tadd('area', 'Area', 'Emphasises volume.');\n\t\tadd('bar', 'Stacked column', 'Shows how the series add up.', 'stacked');\n\t} else {\n\t\tadd('bar', 'Column', 'Several series: clustered columns compare them per category.');\n\t\tadd('bar', 'Bar', 'Horizontal bars fit long category names.');\n\t\tadd('bar', 'Stacked column', 'Shows how the series add up.', 'stacked');\n\t\tadd('line', 'Line', 'Shows the series in order.');\n\t\tif (shape.points >= 3 && shape.series <= 6) add('radar', 'Radar', 'Compares several measures across the series.');\n\t}\n\treturn out;\n}\n\nexport interface ChartFromTable {\n\ttype: ChartType;\n\tstacking: ChartStacking;\n\tcategories: string[];\n\tseries: ChartSeries[];\n\tissues: ChartIssue[];\n\tshape: ChartTableShape;\n}\n\n/**\n * Builds chart data from a block of cells (CSV, a clipboard grid or a spreadsheet range) using\n * the spreadsheet conventions of `analyzeChartTable`. `type: 'auto'` (the default) takes the\n * first recommendation. A scatter chart of a block without labels takes the first column as\n * the x values of the others.\n */\nexport function chartFromTable(rows: ReadonlyArray<ReadonlyArray<unknown>>, options: { type?: ChartType | 'auto' } = {}): ChartFromTable {\n\tconst shape = analyzeChartTable(rows);\n\tconst rec = (options.type ?? 'auto') === 'auto' ? recommendForShape(shape)[0] : undefined;\n\tconst type = rec?.type ?? (options.type === 'auto' || !options.type ? 'bar' : options.type);\n\tconst stacking = rec?.stacking ?? 'none';\n\tconst grid = rows.filter((r) => r.some((c) => !blank(c))).map((r) => [...r]);\n\t// Without a header row, invent one so chartDataFromTable reads every row as data.\n\tconst width = Math.max(0, ...grid.map((r) => r.length));\n\tlet table = grid;\n\tif (!shape.labelColumn) table = table.map((r, i) => [shape.headerRow && i === 0 ? '' : String(i + (shape.headerRow ? 0 : 1)), ...r]);\n\tif (!shape.headerRow) table = [['', ...Array.from({ length: width }, (_, i) => `Series ${i + 1}`)], ...table];\n\tconst xFromFirst = type === 'scatter' && !shape.labelColumn && !shape.byRows && shape.series > 1;\n\tif (xFromFirst) {\n\t\t// The first data column becomes x: move it into the label column.\n\t\ttable = table.map((r) => [r[1], ...r.slice(2)]);\n\t}\n\tconst data = chartDataFromTable(table, { seriesIn: shape.byRows ? 'rows' : 'columns', header: true, xFromFirstColumn: xFromFirst });\n\treturn { type, stacking, categories: data.categories, series: data.series, issues: data.issues, shape };\n}\n","import { HistoryManager } from '../history/HistoryManager.js';\nimport type { Command, HistoryMark } from '../history/types.js';\nimport { parseCsv, parseTsv } from '../spreadsheet/csv.js';\nimport { sameChartSelection } from './layout.js';\nimport { chartPresetPatch } from './presets.js';\nimport { chartFamily } from './spec.js';\nimport { chartMovingAverage, chartSupportsTrendlines, fitChartTrendline, type ChartTrendFit } from './trend.js';\nimport {\n\tchartDataFromTable,\n\tnormalizeChartTrendline,\n\tcloneChartSeries,\n\tcloneChartSpec,\n\tnormalizeChartSpec,\n\tparseChartValue,\n\tuniqueChartSeriesId,\n\ttype ChartTableOptions\n} from './spec.js';\nimport type {\n\tChartAxis,\n\tChartIssue,\n\tChartCurve,\n\tChartLegend,\n\tChartMarker,\n\tChartNumberFormat,\n\tChartSelection,\n\tChartSeries,\n\tChartSeriesType,\n\tChartSpec,\n\tChartTrendline,\n\tChartType,\n\tChartValue\n} from './types.js';\n\n/** Structural equality of JSON-like values (specs are plain data; key order does not matter). */\nfunction sameChartJson(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return Number.isNaN(a) && Number.isNaN(b);\n\tif (Array.isArray(a) !== Array.isArray(b)) return false;\n\tif (Array.isArray(a)) {\n\t\tconst bb = b as unknown[];\n\t\treturn a.length === bb.length && a.every((v, i) => sameChartJson(v, bb[i]));\n\t}\n\tconst ao = a as Record<string, unknown>;\n\tconst bo = b as Record<string, unknown>;\n\tconst keys = Object.keys(ao).filter((k) => ao[k] !== undefined);\n\tif (keys.length !== Object.keys(bo).filter((k) => bo[k] !== undefined).length) return false;\n\treturn keys.every((k) => Object.prototype.hasOwnProperty.call(bo, k) && sameChartJson(ao[k], bo[k]));\n}\n\nexport interface ChartControllerOptions {\n\t/** Starting chart (any partial or saved spec; problems are reported in `state.issues`). */\n\tspec?: Partial<ChartSpec> | unknown;\n\t/** History to record into, e.g. one shared with the rest of the app (default: a new one). */\n\thistory?: HistoryManager;\n\t/** Called after the spec changes (edit, undo, redo, load). */\n\tonChange?: (spec: Readonly<ChartSpec>) => void;\n}\n\n/** A snapshot of the controller. The same object is returned until something changes. */\nexport interface ChartState {\n\tspec: Readonly<ChartSpec>;\n\tselection: ChartSelection | null;\n\t/** The series the selection belongs to (a series, one of its points or one of its trendlines). */\n\tselectedSeries: ChartSeries | null;\n\t/** The category the selection belongs to (a category or a point). */\n\tselectedIndex: number | null;\n\t/** Problems from the last load or rejected edit, as sentences. */\n\tissues: readonly ChartIssue[];\n\t/** The gesture in progress (e.g. a bar drag), if any. */\n\tgesture: string | null;\n\tcanUndo: boolean;\n\tcanRedo: boolean;\n\tundoLabel: string;\n\tredoLabel: string;\n\t/** Bumped on every change. */\n\trevision: number;\n}\n\nexport type ChartActionResult = { ok: true } | { ok: false; message: string; issues?: ChartIssue[] };\n\n/** Top-level fields with partial axes and legend. */\nexport type ChartSpecPatch = Partial<Omit<ChartSpec, 'version' | 'xAxis' | 'yAxis' | 'yAxis2' | 'legend'>> & {\n\txAxis?: Partial<ChartAxis>;\n\tyAxis?: Partial<ChartAxis>;\n\tyAxis2?: Partial<ChartAxis>;\n\tlegend?: Partial<ChartLegend>;\n};\n\nexport interface ChartSeriesInput {\n\tid?: string;\n\tname?: string;\n\tvalues?: readonly unknown[];\n\tcolor?: string;\n\ttype?: ChartSeriesType;\n\thidden?: boolean;\n\taxis?: 'primary' | 'secondary';\n\tx?: readonly unknown[];\n\tsizes?: readonly unknown[];\n\tpointColors?: readonly (string | null)[];\n\tmarker?: ChartMarker;\n\tcurve?: ChartCurve;\n\tdataLabels?: boolean;\n\tformat?: ChartNumberFormat;\n\ttrendlines?: readonly ChartTrendline[];\n}\n\n/** Changes to one series; `null` resets a field to the chart's default. */\nexport interface ChartSeriesPatch {\n\tname?: string;\n\t/** `null` goes back to the palette colour. */\n\tcolor?: string | null;\n\t/** `null` follows the chart type. */\n\ttype?: ChartSeriesType | null;\n\thidden?: boolean;\n\taxis?: 'primary' | 'secondary' | null;\n\tx?: readonly unknown[] | null;\n\tsizes?: readonly unknown[] | null;\n\tpointColors?: readonly (string | null)[] | null;\n\tmarker?: ChartMarker | null;\n\tcurve?: ChartCurve | null;\n\tdataLabels?: boolean | null;\n\tformat?: ChartNumberFormat | null;\n}\n\nexport interface ChartEditOptions {\n\t/** Undo step label. */\n\tlabel?: string;\n}\n\nconst fail = (message: string, issues?: ChartIssue[]): ChartActionResult => ({ ok: false, message, ...(issues ? { issues } : {}) });\n\n/**\n * Headless state for a chart editor: a validated `ChartSpec`, a selection, and undoable\n * edits to data (values, series, categories, pasted grids, CSV) and presentation (type,\n * titles, axes, legend, stacking, …). Drags merge into one undo step (`beginGesture`).\n * `getState()` returns the same object until something changes, so it works with\n * `useSyncExternalStore` and Svelte runes alike.\n */\nexport class ChartController {\n\treadonly history: HistoryManager;\n\tprivate spec: ChartSpec;\n\tprivate selection: ChartSelection | null = null;\n\tprivate issues: ChartIssue[] = [];\n\tprivate gestureKey: string | null = null;\n\tprivate gestureCount = 0;\n\tprivate gestureStart: { spec: ChartSpec; mark: HistoryMark } | null = null;\n\tprivate revision = 0;\n\tprivate applying = false;\n\tprivate readonly onChange?: ChartControllerOptions['onChange'];\n\tprivate readonly listeners = new Set<(state: ChartState) => void>();\n\tprivate unsubscribeHistory?: () => void;\n\tprivate state!: ChartState;\n\n\tconstructor(options: ChartControllerOptions = {}) {\n\t\tthis.history = options.history ?? new HistoryManager();\n\t\tthis.onChange = options.onChange;\n\t\tconst { spec, issues } = normalizeChartSpec(options.spec ?? {});\n\t\tthis.spec = spec;\n\t\tthis.issues = issues;\n\t\tthis.state = this.computeState();\n\t\tthis.connect();\n\t}\n\n\tprivate connect() {\n\t\tthis.unsubscribeHistory?.();\n\t\tthis.unsubscribeHistory = this.history.subscribe((h) => {\n\t\t\t// Edits notify as they apply; only re-notify when the undo/redo state moved on.\n\t\t\tconst s = this.state;\n\t\t\tif (this.applying || (s.canUndo === h.canUndo && s.canRedo === h.canRedo && s.undoLabel === h.undoName && s.redoLabel === h.redoName)) return;\n\t\t\tthis.notify(false);\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// State\n\t// -------------------------------------------------------------------------\n\n\t/** The current snapshot (stable until the next change). */\n\tgetState = (): ChartState => this.state;\n\n\t/** Calls `listener` after every change. Returns an unsubscribe function. */\n\tsubscribe = (listener: (state: ChartState) => void): (() => void) => {\n\t\t// Reconnect after `destroy()` so a remount (React StrictMode) keeps undo working.\n\t\tif (!this.unsubscribeHistory) this.connect();\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\t/** The current spec (do not mutate; edit through the controller). */\n\tgetSpec(): Readonly<ChartSpec> {\n\t\treturn this.spec;\n\t}\n\n\tgetSeries(id: string): ChartSeries | undefined {\n\t\treturn this.spec.series.find((s) => s.id === id);\n\t}\n\n\tprivate computeState(): ChartState {\n\t\tconst h = this.history.getState();\n\t\tconst sel = this.selection;\n\t\tconst seriesId = sel?.kind === 'series' || sel?.kind === 'point' || sel?.kind === 'trendline' ? sel.seriesId : null;\n\t\treturn {\n\t\t\tspec: this.spec,\n\t\t\tselection: sel,\n\t\t\tselectedSeries: seriesId ? (this.spec.series.find((s) => s.id === seriesId) ?? null) : null,\n\t\t\tselectedIndex: sel?.kind === 'point' || sel?.kind === 'category' ? sel.index : null,\n\t\t\tissues: this.issues,\n\t\t\tgesture: this.gestureKey,\n\t\t\tcanUndo: h.canUndo,\n\t\t\tcanRedo: h.canRedo,\n\t\t\tundoLabel: h.undoName,\n\t\t\tredoLabel: h.redoName,\n\t\t\trevision: this.revision\n\t\t};\n\t}\n\n\tprivate notify(specChanged: boolean) {\n\t\tthis.revision++;\n\t\tthis.state = this.computeState();\n\t\tif (specChanged) this.onChange?.(this.spec);\n\t\tconst state = this.state;\n\t\tthis.listeners.forEach((listener) => {\n\t\t\ttry {\n\t\t\t\tlistener(state);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[ChartController] Error in state listener:', error);\n\t\t\t}\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Changes: every edit records a before / after snapshot of the spec\n\t// -------------------------------------------------------------------------\n\n\t/** Drops a selection that no longer points at anything. */\n\tprivate validSelection(sel: ChartSelection | null, spec: ChartSpec): ChartSelection | null {\n\t\tif (!sel) return null;\n\t\tswitch (sel.kind) {\n\t\t\tcase 'series':\n\t\t\t\treturn spec.series.some((s) => s.id === sel.seriesId) ? sel : null;\n\t\t\tcase 'point':\n\t\t\t\treturn spec.series.some((s) => s.id === sel.seriesId) && sel.index < spec.categories.length ? sel : null;\n\t\t\tcase 'category':\n\t\t\t\treturn sel.index < spec.categories.length ? sel : null;\n\t\t\tcase 'trendline':\n\t\t\t\treturn spec.series.find((s) => s.id === sel.seriesId)?.trendlines?.[sel.index] ? sel : null;\n\t\t\tcase 'title':\n\t\t\t\treturn spec.title ? sel : null;\n\t\t\tcase 'subtitle':\n\t\t\t\treturn spec.subtitle ? sel : null;\n\t\t\tdefault:\n\t\t\t\treturn sel;\n\t\t}\n\t}\n\n\tprivate applySpec(spec: ChartSpec) {\n\t\tthis.applying = true;\n\t\ttry {\n\t\t\tthis.spec = spec;\n\t\t\tthis.selection = this.validSelection(this.selection, spec);\n\t\t} finally {\n\t\t\tthis.applying = false;\n\t\t}\n\t\tthis.notify(true);\n\t}\n\n\tprivate commit(label: string, next: ChartSpec, select?: ChartSelection | null) {\n\t\tconst before = this.spec;\n\t\tconst hadIssues = this.issues.length > 0;\n\t\tthis.issues = [];\n\t\t// A no-op edit (same value, same title, …) records no undo step.\n\t\tif (sameChartJson(before, next)) {\n\t\t\tconst reselect = select !== undefined && !sameChartSelection(this.selection, select) && !(select === null && this.selection === null);\n\t\t\tif (reselect) this.selection = select;\n\t\t\tif (reselect || hadIssues) this.notify(false);\n\t\t\treturn;\n\t\t}\n\t\tconst command: Command = {\n\t\t\tname: label,\n\t\t\ttag: 'chart',\n\t\t\texecute: () => this.applySpec(next),\n\t\t\tundo: () => this.applySpec(before),\n\t\t\tredo: () => this.applySpec(next)\n\t\t};\n\t\tif (select !== undefined) this.selection = select;\n\t\tif (this.gestureKey !== null) this.history.executeMerged(command, { key: `chart.gesture:${this.gestureKey}:${this.gestureCount}` });\n\t\telse this.history.execute(command);\n\t}\n\n\tprivate reject(message: string, issues: ChartIssue[] = []): ChartActionResult {\n\t\tthis.issues = issues.length ? issues : [{ path: '', message }];\n\t\tthis.notify(false);\n\t\treturn fail(message, issues.length ? issues : undefined);\n\t}\n\n\t/** A copy of the spec with `edit` applied (series and categories copied as needed). */\n\tprivate edited(edit: (draft: ChartSpec) => void): ChartSpec {\n\t\tconst draft = cloneChartSpec(this.spec);\n\t\tedit(draft);\n\t\treturn draft;\n\t}\n\n\tprivate unknownSeries(id: string): ChartActionResult {\n\t\tconst ids = this.spec.series.map((s) => `\"${s.id}\"`);\n\t\treturn fail(`There is no series \"${id}\"; ${ids.length ? `expected one of ${ids.join(', ')}` : 'the chart has no series yet'}.`);\n\t}\n\n\tprivate badIndex(index: number): ChartActionResult {\n\t\tconst n = this.spec.categories.length;\n\t\treturn fail(n ? `Category index ${index} is out of range; expected 0 to ${n - 1}.` : 'The chart has no categories yet.');\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Presentation\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Changes any presentation or data fields as one undo step. All-or-nothing: if anything\n\t * is invalid, nothing changes and every problem is returned (and shown in `state.issues`).\n\t */\n\tupdate(patch: ChartSpecPatch, options: ChartEditOptions = {}): ChartActionResult {\n\t\tconst s = this.spec;\n\t\tconst merged = {\n\t\t\t...s,\n\t\t\t...patch,\n\t\t\txAxis: patch.xAxis ? { ...s.xAxis, ...patch.xAxis } : s.xAxis,\n\t\t\tyAxis: patch.yAxis ? { ...s.yAxis, ...patch.yAxis } : s.yAxis,\n\t\t\tyAxis2: patch.yAxis2 ? { ...s.yAxis2, ...patch.yAxis2 } : s.yAxis2,\n\t\t\tlegend: patch.legend ? { ...s.legend, ...patch.legend } : s.legend,\n\t\t\tversion: 1\n\t\t};\n\t\tconst { spec, issues } = normalizeChartSpec(merged);\n\t\tif (issues.length) return this.reject(issues.map((i) => i.message).join(' '), issues);\n\t\tif (JSON.stringify(spec) === JSON.stringify(s)) return { ok: true };\n\t\tthis.commit(options.label ?? updateLabel(patch), spec);\n\t\treturn { ok: true };\n\t}\n\n\tsetType(type: ChartType): ChartActionResult {\n\t\treturn this.update({ type }, { label: `Change chart type` });\n\t}\n\n\tsetTitle(title: string): ChartActionResult {\n\t\treturn this.update({ title }, { label: 'Edit title' });\n\t}\n\n\tsetSubtitle(subtitle: string): ChartActionResult {\n\t\treturn this.update({ subtitle }, { label: 'Edit subtitle' });\n\t}\n\n\t/** Changes the category (`x`), value (`y`) or secondary value (`y2`) axis. */\n\tsetAxis(axis: 'x' | 'y' | 'y2', patch: Partial<ChartAxis>): ChartActionResult {\n\t\tconst key = axis === 'x' ? 'xAxis' : axis === 'y' ? 'yAxis' : 'yAxis2';\n\t\treturn this.update({ [key]: patch }, { label: `Change ${axis === 'x' ? 'category' : axis === 'y' ? 'value' : 'secondary value'} axis` });\n\t}\n\n\t/**\n\t * Applies a named quick layout and / or colour scheme (see `CHART_LAYOUT_PRESETS` and\n\t * `CHART_COLOR_SCHEMES`) as one undo step.\n\t */\n\tapplyPreset(options: { layout?: string; colors?: string }): ChartActionResult {\n\t\tconst preset = chartPresetPatch(options);\n\t\tif (!preset.ok) return this.reject(preset.message);\n\t\tconst label = options.layout && options.colors ? 'Apply chart style' : options.layout ? 'Apply quick layout' : 'Change colours';\n\t\treturn this.update(preset.patch, { label });\n\t}\n\n\tsetLegend(patch: Partial<ChartLegend>): ChartActionResult {\n\t\treturn this.update({ legend: patch }, { label: 'Change legend' });\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Data\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Replaces categories and / or series as one undo step. Values are validated and padded\n\t * to the categories; all-or-nothing like `update`.\n\t */\n\tsetData(data: { categories?: readonly unknown[]; series?: readonly ChartSeriesInput[] }, options: ChartEditOptions = {}): ChartActionResult {\n\t\treturn this.update({ ...(data.categories ? { categories: data.categories as string[] } : {}), ...(data.series ? { series: data.series as ChartSeries[] } : {}) }, { label: options.label ?? 'Edit chart data' });\n\t}\n\n\t/**\n\t * Sets one value (numbers, numeric text such as `1,200` or `12%`, or blank for a gap).\n\t * One undo step, or part of the current gesture.\n\t */\n\tsetValue(seriesId: string, index: number, value: unknown, options: ChartEditOptions = {}): ChartActionResult {\n\t\tconst series = this.getSeries(seriesId);\n\t\tif (!series) return this.unknownSeries(seriesId);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= this.spec.categories.length) return this.badIndex(index);\n\t\tconst parsed = parseChartValue(value);\n\t\tif (parsed === undefined) return this.reject(`\"${String(value)}\" is not a number; enter a number or leave the cell blank.`, [{ path: `${seriesId}[${index}]`, message: `\"${String(value)}\" is not a number.` }]);\n\t\tif (series.values[index] === parsed) {\n\t\t\tif (this.issues.length) {\n\t\t\t\tthis.issues = [];\n\t\t\t\tthis.notify(false);\n\t\t\t}\n\t\t\treturn { ok: true };\n\t\t}\n\t\tconst next = this.edited((d) => {\n\t\t\td.series.find((s) => s.id === seriesId)!.values[index] = parsed;\n\t\t});\n\t\tthis.commit(options.label ?? `Edit ${series.name} · ${this.spec.categories[index]}`, next);\n\t\treturn { ok: true };\n\t}\n\n\t/** Several values as one undo step (all-or-nothing). */\n\tsetValues(cells: readonly { seriesId: string; index: number; value: unknown }[], options: ChartEditOptions = {}): ChartActionResult {\n\t\tconst issues: ChartIssue[] = [];\n\t\tconst parsed: { seriesId: string; index: number; value: ChartValue }[] = [];\n\t\tfor (const cell of cells) {\n\t\t\tif (!this.getSeries(cell.seriesId)) issues.push({ path: cell.seriesId, message: (this.unknownSeries(cell.seriesId) as { message: string }).message });\n\t\t\telse if (!Number.isInteger(cell.index) || cell.index < 0 || cell.index >= this.spec.categories.length) issues.push({ path: `${cell.seriesId}[${cell.index}]`, message: (this.badIndex(cell.index) as { message: string }).message });\n\t\t\telse {\n\t\t\t\tconst value = parseChartValue(cell.value);\n\t\t\t\tif (value === undefined) issues.push({ path: `${cell.seriesId}[${cell.index}]`, message: `\"${String(cell.value)}\" is not a number.` });\n\t\t\t\telse parsed.push({ seriesId: cell.seriesId, index: cell.index, value });\n\t\t\t}\n\t\t}\n\t\tif (issues.length) return this.reject(issues.map((i) => i.message).join(' '), issues);\n\t\tconst next = this.edited((d) => {\n\t\t\tfor (const cell of parsed) d.series.find((s) => s.id === cell.seriesId)!.values[cell.index] = cell.value;\n\t\t});\n\t\tif (JSON.stringify(next.series) !== JSON.stringify(this.spec.series)) this.commit(options.label ?? 'Edit values', next);\n\t\treturn { ok: true };\n\t}\n\n\t/** Adds a series (values padded to the categories) and selects it. Returns its id. */\n\taddSeries(input: ChartSeriesInput = {}, options: { at?: number } = {}): { ok: true; id: string } | { ok: false; message: string; issues?: ChartIssue[] } {\n\t\tconst id = input.id && !this.getSeries(input.id) ? input.id : uniqueChartSeriesId(this.spec.series);\n\t\tconst name = input.name ?? `Series ${this.spec.series.length + 1}`;\n\t\tconst at = Math.max(0, Math.min(this.spec.series.length, options.at ?? this.spec.series.length));\n\t\tconst series = [...this.spec.series];\n\t\tseries.splice(at, 0, { ...input, id, name, values: (input.values ?? []) as ChartValue[] } as unknown as ChartSeries);\n\t\tconst { spec, issues } = normalizeChartSpec({ ...this.spec, series });\n\t\tif (issues.length) return this.reject(issues.map((i) => i.message).join(' '), issues) as { ok: false; message: string };\n\t\tthis.commit(`Add series \"${name}\"`, spec, { kind: 'series', seriesId: id });\n\t\treturn { ok: true, id };\n\t}\n\n\tremoveSeries(id: string): ChartActionResult {\n\t\tconst series = this.getSeries(id);\n\t\tif (!series) return this.unknownSeries(id);\n\t\tthis.commit(\n\t\t\t`Delete series \"${series.name}\"`,\n\t\t\tthis.edited((d) => {\n\t\t\t\td.series = d.series.filter((s) => s.id !== id);\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\tupdateSeries(id: string, patch: ChartSeriesPatch): ChartActionResult {\n\t\tconst series = this.getSeries(id);\n\t\tif (!series) return this.unknownSeries(id);\n\t\tconst next = cloneChartSeries(series);\n\t\tif (patch.name !== undefined) next.name = String(patch.name);\n\t\tif (patch.color === null || patch.color === '') delete next.color;\n\t\telse if (patch.color !== undefined) next.color = patch.color;\n\t\tif (patch.type === null) delete next.type;\n\t\telse if (patch.type !== undefined) next.type = patch.type;\n\t\tif (patch.hidden !== undefined) {\n\t\t\tif (patch.hidden) next.hidden = true;\n\t\t\telse delete next.hidden;\n\t\t}\n\t\tconst resettable = ['axis', 'x', 'sizes', 'pointColors', 'marker', 'curve', 'dataLabels', 'format'] as const;\n\t\tfor (const key of resettable) {\n\t\t\tif (!(key in patch) || patch[key] === undefined) continue;\n\t\t\tif (patch[key] === null) delete (next as any)[key];\n\t\t\telse (next as any)[key] = patch[key];\n\t\t}\n\t\tif (next.axis === 'primary') delete next.axis;\n\t\tconst series2 = this.spec.series.map((s) => (s.id === id ? next : s));\n\t\tconst { spec, issues } = normalizeChartSpec({ ...this.spec, series: series2 });\n\t\tif (issues.length) return this.reject(issues.map((i) => i.message).join(' '), issues);\n\t\tif (JSON.stringify(spec.series) === JSON.stringify(this.spec.series)) return { ok: true };\n\t\tconst label =\n\t\t\tpatch.hidden !== undefined && Object.keys(patch).length === 1\n\t\t\t\t? `${patch.hidden ? 'Hide' : 'Show'} \"${series.name}\"`\n\t\t\t\t: patch.name !== undefined && Object.keys(patch).length === 1\n\t\t\t\t\t? 'Rename series'\n\t\t\t\t\t: `Change series \"${series.name}\"`;\n\t\tthis.commit(label, spec);\n\t\treturn { ok: true };\n\t}\n\n\ttoggleSeries(id: string): ChartActionResult {\n\t\tconst series = this.getSeries(id);\n\t\tif (!series) return this.unknownSeries(id);\n\t\treturn this.updateSeries(id, { hidden: !series.hidden });\n\t}\n\n\t/** Moves a series to position `to` (drawing and legend order). */\n\tmoveSeries(id: string, to: number): ChartActionResult {\n\t\tconst from = this.spec.series.findIndex((s) => s.id === id);\n\t\tif (from < 0) return this.unknownSeries(id);\n\t\tconst target = Math.max(0, Math.min(this.spec.series.length - 1, to));\n\t\tif (target === from) return { ok: true };\n\t\tthis.commit(\n\t\t\t'Reorder series',\n\t\t\tthis.edited((d) => {\n\t\t\t\tconst [s] = d.series.splice(from, 1);\n\t\t\t\td.series.splice(target, 0, s);\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\t/** Inserts a category (with gaps in every series) at `at` (default: the end). Returns its index. */\n\taddCategory(label?: string, options: { at?: number } = {}): { ok: true; index: number } {\n\t\tconst at = Math.max(0, Math.min(this.spec.categories.length, options.at ?? this.spec.categories.length));\n\t\tconst name = label ?? `${this.spec.categories.length + 1}`;\n\t\tthis.commit(\n\t\t\t`Add category \"${name}\"`,\n\t\t\tthis.edited((d) => {\n\t\t\t\td.categories.splice(at, 0, name);\n\t\t\t\tfor (const s of d.series) s.values.splice(at, 0, null);\n\t\t\t}),\n\t\t\t{ kind: 'category', index: at }\n\t\t);\n\t\treturn { ok: true, index: at };\n\t}\n\n\tremoveCategory(index: number): ChartActionResult {\n\t\tif (!Number.isInteger(index) || index < 0 || index >= this.spec.categories.length) return this.badIndex(index);\n\t\tthis.commit(\n\t\t\t`Delete category \"${this.spec.categories[index]}\"`,\n\t\t\tthis.edited((d) => {\n\t\t\t\td.categories.splice(index, 1);\n\t\t\t\tfor (const s of d.series) s.values.splice(index, 1);\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\trenameCategory(index: number, label: string): ChartActionResult {\n\t\tif (!Number.isInteger(index) || index < 0 || index >= this.spec.categories.length) return this.badIndex(index);\n\t\tif (this.spec.categories[index] === label) return { ok: true };\n\t\tthis.commit(\n\t\t\t'Rename category',\n\t\t\tthis.edited((d) => {\n\t\t\t\td.categories[index] = String(label);\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\tmoveCategory(from: number, to: number): ChartActionResult {\n\t\tif (!Number.isInteger(from) || from < 0 || from >= this.spec.categories.length) return this.badIndex(from);\n\t\tconst target = Math.max(0, Math.min(this.spec.categories.length - 1, to));\n\t\tif (target === from) return { ok: true };\n\t\tconst move = <T>(list: T[]) => {\n\t\t\tconst [item] = list.splice(from, 1);\n\t\t\tlist.splice(target, 0, item);\n\t\t};\n\t\tthis.commit(\n\t\t\t'Reorder categories',\n\t\t\tthis.edited((d) => {\n\t\t\t\tmove(d.categories);\n\t\t\t\tfor (const s of d.series) move(s.values);\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Pastes a block of cells (TSV / CSV text or rows) into the data grid with its top-left at\n\t * `row` (category index) and `column` (series index; `-1` is the category column). The\n\t * grid grows to fit. Non-numeric value cells become gaps and are reported in `issues`.\n\t */\n\tpasteCells(row: number, column: number, cells: string | ReadonlyArray<ReadonlyArray<unknown>>): ChartActionResult & { issues?: ChartIssue[] } {\n\t\tconst rows: unknown[][] = typeof cells === 'string' ? (cells.includes('\\t') ? parseTsv(cells) : parseCsv(cells)) : cells.map((r) => [...r]);\n\t\tif (!rows.length) return { ok: true };\n\t\tconst issues: ChartIssue[] = [];\n\t\tconst next = this.edited((d) => {\n\t\t\tconst width = Math.max(...rows.map((r) => r.length));\n\t\t\tconst lastSeries = column + width - 1;\n\t\t\twhile (d.series.length <= lastSeries) {\n\t\t\t\tconst id = uniqueChartSeriesId(d.series);\n\t\t\t\td.series.push({ id, name: `Series ${d.series.length + 1}`, values: d.categories.map(() => null) });\n\t\t\t}\n\t\t\tconst lastRow = row + rows.length - 1;\n\t\t\twhile (d.categories.length <= lastRow) {\n\t\t\t\td.categories.push(`${d.categories.length + 1}`);\n\t\t\t\tfor (const s of d.series) s.values.push(null);\n\t\t\t}\n\t\t\trows.forEach((cellsInRow, r) => {\n\t\t\t\tcellsInRow.forEach((cell, c) => {\n\t\t\t\t\tconst col = column + c;\n\t\t\t\t\tconst index = row + r;\n\t\t\t\t\tif (col < 0) d.categories[index] = cell === null || cell === undefined ? '' : String(cell).trim();\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst parsed = parseChartValue(cell);\n\t\t\t\t\t\tif (parsed === undefined) issues.push({ path: `${d.series[col].id}[${index}]`, message: `\"${String(cell)}\" is not a number; it was left blank.` });\n\t\t\t\t\t\td.series[col].values[index] = parsed ?? null;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tthis.commit('Paste cells', next);\n\t\tif (issues.length) {\n\t\t\tthis.issues = issues;\n\t\t\tthis.notify(false);\n\t\t}\n\t\treturn issues.length ? { ok: true, issues } : { ok: true };\n\t}\n\n\t/**\n\t * Replaces the data with a grid of cells (see `chartDataFromTable`): one undo step. Series\n\t * colours and types are kept by name.\n\t */\n\timportTable(rows: ReadonlyArray<ReadonlyArray<unknown>>, options: ChartTableOptions = {}): ChartActionResult & { issues?: ChartIssue[] } {\n\t\tconst data = chartDataFromTable(rows, options);\n\t\tif (!data.categories.length || !data.series.length) return this.reject('There is no data to import: expected a header row and at least one row of values.');\n\t\tconst byName = new Map(this.spec.series.map((s) => [s.name, s]));\n\t\tconst series = data.series.map((s) => {\n\t\t\tconst old = byName.get(s.name);\n\t\t\treturn { ...s, ...(old?.color ? { color: old.color } : {}), ...(old?.type ? { type: old.type } : {}), ...(old ? { id: old.id } : {}) };\n\t\t});\n\t\tconst { spec } = normalizeChartSpec({ ...this.spec, categories: data.categories, series });\n\t\tthis.commit('Import data', spec);\n\t\tif (data.issues.length) {\n\t\t\tthis.issues = data.issues;\n\t\t\tthis.notify(false);\n\t\t\treturn { ok: true, issues: data.issues };\n\t\t}\n\t\treturn { ok: true };\n\t}\n\n\t/** Imports CSV (or TSV, detected by tabs) text; see `importTable`. */\n\timportCsv(text: string, options: ChartTableOptions & { delimiter?: string } = {}): ChartActionResult & { issues?: ChartIssue[] } {\n\t\tconst delimiter = options.delimiter ?? (text.includes('\\t') ? '\\t' : ',');\n\t\treturn this.importTable(parseCsv(text, { delimiter }), options);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Trendlines\n\t// -------------------------------------------------------------------------\n\n\t/** Adds a trendline to a series and selects it. Returns its index (and the fit, when it can be computed). */\n\taddTrendline(seriesId: string, input: ChartTrendline): { ok: true; index: number; fit: ChartTrendFit | null } | { ok: false; message: string; issues?: ChartIssue[] } {\n\t\tconst series = this.getSeries(seriesId);\n\t\tif (!series) return this.unknownSeries(seriesId) as { ok: false; message: string };\n\t\tif (!chartSupportsTrendlines(this.spec.type, this.spec.stacking))\n\t\t\treturn this.reject(`Trendlines need an unstacked bar, line, area, scatter or bubble chart; this is a ${this.spec.stacking !== 'none' ? `${this.spec.stacking} ` : ''}${this.spec.type} chart.`) as { ok: false; message: string };\n\t\tconst issues: ChartIssue[] = [];\n\t\tconst line = normalizeChartTrendline(input, 'trendline', issues);\n\t\tif (!line || issues.length) return this.reject(issues.map((i) => i.message).join(' ') || 'The trendline is not valid.', issues) as { ok: false; message: string };\n\t\tconst index = series.trendlines?.length ?? 0;\n\t\tconst next = this.edited((d) => {\n\t\t\tconst s = d.series.find((x) => x.id === seriesId)!;\n\t\t\ts.trendlines = [...(s.trendlines ?? []), line];\n\t\t});\n\t\tthis.commit(`Add trendline to \"${series.name}\"`, next, { kind: 'trendline', seriesId, index });\n\t\treturn { ok: true, index, fit: this.trendlineFit(seriesId, index) };\n\t}\n\n\t/** Changes a trendline (all-or-nothing). */\n\tupdateTrendline(seriesId: string, index: number, patch: Partial<ChartTrendline>): ChartActionResult {\n\t\tconst series = this.getSeries(seriesId);\n\t\tif (!series) return this.unknownSeries(seriesId);\n\t\tconst current = series.trendlines?.[index];\n\t\tif (!current) return fail(`\"${series.name}\" has no trendline ${index}; ${series.trendlines?.length ? `expected 0 to ${series.trendlines.length - 1}` : 'it has none yet'}.`);\n\t\tconst issues: ChartIssue[] = [];\n\t\tconst merged: Record<string, unknown> = { ...current, ...patch };\n\t\tfor (const [k, v] of Object.entries(patch)) if (v === null) delete merged[k];\n\t\tconst line = normalizeChartTrendline(merged, 'trendline', issues);\n\t\tif (!line || issues.length) return this.reject(issues.map((i) => i.message).join(' '), issues);\n\t\tthis.commit(\n\t\t\t'Change trendline',\n\t\t\tthis.edited((d) => {\n\t\t\t\td.series.find((x) => x.id === seriesId)!.trendlines![index] = line;\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\tremoveTrendline(seriesId: string, index: number): ChartActionResult {\n\t\tconst series = this.getSeries(seriesId);\n\t\tif (!series) return this.unknownSeries(seriesId);\n\t\tif (!series.trendlines?.[index]) return fail(`\"${series.name}\" has no trendline ${index}.`);\n\t\tthis.commit(\n\t\t\t'Delete trendline',\n\t\t\tthis.edited((d) => {\n\t\t\t\tconst s = d.series.find((x) => x.id === seriesId)!;\n\t\t\t\ts.trendlines = s.trendlines!.filter((_, i) => i !== index);\n\t\t\t\tif (!s.trendlines.length) delete s.trendlines;\n\t\t\t})\n\t\t);\n\t\treturn { ok: true };\n\t}\n\n\t/** The points a series' trendlines are fitted to: (x, y) with x = 1, 2, 3 … on category charts. */\n\ttrendlinePoints(seriesId: string): [number, number][] {\n\t\tconst series = this.getSeries(seriesId);\n\t\tif (!series) return [];\n\t\tconst xy = chartFamily(this.spec) === 'xy';\n\t\tconst out: [number, number][] = [];\n\t\tseries.values.forEach((v, i) => {\n\t\t\tconst x = xy ? (series.x?.[i] ?? (this.spec.type === 'bubble' ? i + 1 : null)) : i + 1;\n\t\t\tif (v !== null && x !== null && Number.isFinite(v) && Number.isFinite(x)) out.push([x, v]);\n\t\t});\n\t\treturn out;\n\t}\n\n\t/** The fitted coefficients, R² and equation of a trendline (null for moving averages or unfittable data). */\n\ttrendlineFit(seriesId: string, index: number): ChartTrendFit | null {\n\t\tconst line = this.getSeries(seriesId)?.trendlines?.[index];\n\t\tif (!line) return null;\n\t\treturn fitChartTrendline(line, this.trendlinePoints(seriesId));\n\t}\n\n\t/** The moving-average points of a trendline (empty for other kinds). */\n\ttrendlineMovingAverage(seriesId: string, index: number): [number, number][] {\n\t\tconst line = this.getSeries(seriesId)?.trendlines?.[index];\n\t\tif (!line || line.type !== 'moving-average') return [];\n\t\treturn chartMovingAverage(this.trendlinePoints(seriesId), line.period ?? 2);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Reshaping\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Switches rows and columns: series become categories and categories become series (one\n\t * undo step). Series colours, types and other per-series settings are dropped.\n\t */\n\ttranspose(): ChartActionResult {\n\t\tconst s = this.spec;\n\t\tif (!s.series.length || !s.categories.length) return this.reject('There is no data to switch: the chart needs at least one series and one category.');\n\t\tconst used = new Set<string>();\n\t\tconst series: ChartSeries[] = s.categories.map((name, i) => {\n\t\t\tlet id = `series-${i + 1}`;\n\t\t\tfor (let k = i + 2; used.has(id); k++) id = `series-${k}`;\n\t\t\tused.add(id);\n\t\t\treturn { id, name, values: s.series.map((x) => x.values[i] ?? null) };\n\t\t});\n\t\tconst { spec } = normalizeChartSpec({ ...s, categories: s.series.map((x) => x.name), series });\n\t\tthis.commit('Switch rows and columns', spec, null);\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Selection and gestures\n\t// -------------------------------------------------------------------------\n\n\t/** Selects a chart element (view state; not an undo step). */\n\tselect(selection: ChartSelection | null): void {\n\t\tconst next = this.validSelection(selection, this.spec);\n\t\tif (sameChartSelection(next, this.selection) || (next === null && this.selection === null)) return;\n\t\tthis.selection = next;\n\t\tthis.notify(false);\n\t}\n\n\t/**\n\t * Deletes what is selected: a series or category is removed, a point becomes a gap, a\n\t * title is cleared, the legend or an axis is hidden.\n\t */\n\tdeleteSelection(): ChartActionResult {\n\t\tconst sel = this.selection;\n\t\tif (!sel) return fail('Nothing is selected.');\n\t\tswitch (sel.kind) {\n\t\t\tcase 'series':\n\t\t\t\treturn this.removeSeries(sel.seriesId);\n\t\t\tcase 'category':\n\t\t\t\treturn this.removeCategory(sel.index);\n\t\t\tcase 'point':\n\t\t\t\treturn this.setValue(sel.seriesId, sel.index, null, { label: 'Clear value' });\n\t\t\tcase 'title':\n\t\t\t\treturn this.setTitle('');\n\t\t\tcase 'subtitle':\n\t\t\t\treturn this.setSubtitle('');\n\t\t\tcase 'legend':\n\t\t\t\treturn this.setLegend({ show: false });\n\t\t\tcase 'axis':\n\t\t\t\treturn this.setAxis(sel.axis, { show: false });\n\t\t\tcase 'trendline':\n\t\t\t\treturn this.removeTrendline(sel.seriesId, sel.index);\n\t\t\tdefault:\n\t\t\t\treturn fail('The chart itself cannot be deleted.');\n\t\t}\n\t}\n\n\t/** Adds `delta` to a value (a gap counts as 0). */\n\tnudgeValue(seriesId: string, index: number, delta: number): ChartActionResult {\n\t\tconst series = this.getSeries(seriesId);\n\t\tif (!series) return this.unknownSeries(seriesId);\n\t\tconst current = series.values[index] ?? 0;\n\t\treturn this.setValue(seriesId, index, Number((current + delta).toPrecision(12)), { label: `Edit ${series.name} · ${this.spec.categories[index] ?? index}` });\n\t}\n\n\t/** Starts a continuous edit (a drag): every change until `endGesture()` is one undo step. */\n\tbeginGesture(key: string): void {\n\t\tif (this.gestureKey === key) return;\n\t\tthis.history.endGesture();\n\t\tthis.gestureKey = key;\n\t\tthis.gestureCount++;\n\t\tthis.gestureStart = { spec: this.spec, mark: this.history.mark() };\n\t\tthis.notify(false);\n\t}\n\n\t/**\n\t * Cancels the gesture in progress (Escape during a drag): everything it changed is taken\n\t * back and leaves no undo or redo step.\n\t */\n\tcancelGesture(): void {\n\t\tif (this.gestureKey === null) return;\n\t\tconst start = this.gestureStart;\n\t\tthis.gestureKey = null;\n\t\tthis.gestureStart = null;\n\t\tthis.history.endGesture();\n\t\tif (start) this.history.revertTo(start.mark);\n\t\tthis.notify(false);\n\t}\n\n\tendGesture(): void {\n\t\tif (this.gestureKey === null) return;\n\t\tthis.gestureKey = null;\n\t\tthis.history.endGesture();\n\t\t// A drag that ends where it started leaves no undo step behind.\n\t\tconst start = this.gestureStart;\n\t\tthis.gestureStart = null;\n\t\tif (start && sameChartJson(start.spec, this.spec)) this.history.revertTo(start.mark);\n\t\tthis.notify(false);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Persistence and history\n\t// -------------------------------------------------------------------------\n\n\t/** The spec, for saving (a copy). */\n\ttoJSON(): ChartSpec {\n\t\treturn cloneChartSpec(this.spec);\n\t}\n\n\t/**\n\t * Replaces the chart without an undo step (e.g. when opening a document). Problems are\n\t * fixed with defaults and reported in `state.issues` (and returned).\n\t */\n\tload(input: unknown, options: { clearHistory?: boolean } = {}): ChartIssue[] {\n\t\tconst { spec, issues } = normalizeChartSpec(input);\n\t\tthis.spec = spec;\n\t\tthis.issues = issues;\n\t\tthis.selection = this.validSelection(this.selection, spec);\n\t\tif (options.clearHistory) {\n\t\t\tthis.applying = true;\n\t\t\ttry {\n\t\t\t\tthis.history.clear();\n\t\t\t} finally {\n\t\t\t\tthis.applying = false;\n\t\t\t}\n\t\t}\n\t\tthis.notify(true);\n\t\treturn issues;\n\t}\n\n\tundo(): boolean {\n\t\tthis.endGesture();\n\t\treturn this.history.undo();\n\t}\n\n\tredo(): boolean {\n\t\tthis.endGesture();\n\t\treturn this.history.redo();\n\t}\n\n\t/** Stops listening to the history (reconnected by the next `subscribe`). */\n\tdestroy(): void {\n\t\tthis.unsubscribeHistory?.();\n\t\tthis.unsubscribeHistory = undefined;\n\t\tthis.listeners.clear();\n\t}\n}\n\nexport function createChartController(options: ChartControllerOptions = {}): ChartController {\n\treturn new ChartController(options);\n}\n\nfunction updateLabel(patch: ChartSpecPatch): string {\n\tconst keys = Object.keys(patch);\n\tif (keys.length !== 1) return 'Change chart';\n\tconst labels: Record<string, string> = {\n\t\ttype: 'Change chart type',\n\t\ttitle: 'Edit title',\n\t\tsubtitle: 'Edit subtitle',\n\t\tcategories: 'Edit categories',\n\t\tseries: 'Edit series',\n\t\txAxis: 'Change category axis',\n\t\tyAxis: 'Change value axis',\n\t\tyAxis2: 'Change secondary value axis',\n\t\tlabelPosition: 'Change label position',\n\t\tgapWidth: 'Change bar spacing',\n\t\toverlap: 'Change bar overlap',\n\t\tbins: 'Change histogram bins',\n\t\tshowTotal: 'Toggle waterfall total',\n\t\tlegend: 'Change legend',\n\t\tstacking: 'Change stacking',\n\t\torientation: 'Change orientation',\n\t\tcurve: 'Change line style',\n\t\tpoints: 'Toggle points',\n\t\tdataLabels: 'Toggle data labels',\n\t\tpalette: 'Change colours',\n\t\tinnerRadius: 'Change donut hole'\n\t};\n\treturn labels[keys[0]] ?? 'Change chart';\n}\n","// The xychart-beta, pie and radar-beta grammars follow Ursula's statement adapters (src/xychart, src/pie,\n// src/radar), and the metadata comment follows its `%% @ursula` line (src/source/metadata.ts).\nimport { chartFamily, defaultChartAxis, normalizeChartSpec } from './spec.js';\nimport type { ChartAxis, ChartIssue, ChartSeries, ChartSpec, ChartValue } from './types.js';\n\n/** The comment line that carries what Mermaid cannot express. Every Mermaid tool ignores `%%` comments. */\nexport const CHART_MERMAID_META_PREFIX = '%% @pixerate ';\n\nexport type ChartMermaidFamily = 'xychart' | 'pie' | 'radar';\n\nexport interface ChartMermaidOptions {\n\t/** Write the `%% @pixerate {…}` line so the chart round-trips exactly (default `true`). */\n\tmeta?: boolean;\n\t/** Indentation of statements (default four spaces). */\n\tindent?: string;\n}\n\nconst quote = (text: string) => `\"${text.replace(/\"/g, '#quot;')}\"`;\nconst unquote = (text: string) => {\n\tconst t = text.trim();\n\treturn (t.length >= 2 && t.startsWith('\"') && t.endsWith('\"') ? t.slice(1, -1) : t).replace(/#quot;/g, '\"');\n};\nconst word = (text: string) => (/^[A-Za-z0-9_]+$/.test(text) ? text : quote(text));\nconst num = (value: number) => (Number.isInteger(value) ? String(value) : String(Number(value.toPrecision(10))));\n\n/** Splits on `sep` outside quotes and brackets. */\nfunction splitOutside(text: string, sep: string): string[] {\n\tconst out: string[] = [];\n\tlet cur = '';\n\tlet quoted = false;\n\tlet depth = 0;\n\tfor (const ch of text) {\n\t\tif (ch === '\"') quoted = !quoted;\n\t\telse if (!quoted && (ch === '[' || ch === '{')) depth++;\n\t\telse if (!quoted && (ch === ']' || ch === '}')) depth--;\n\t\tif (ch === sep && !quoted && depth === 0) {\n\t\t\tout.push(cur);\n\t\t\tcur = '';\n\t\t} else cur += ch;\n\t}\n\tout.push(cur);\n\treturn out;\n}\n\n/** The Mermaid family a chart is written as. */\nexport function chartMermaidFamily(spec: Pick<ChartSpec, 'type' | 'series'>): ChartMermaidFamily {\n\tconst family = chartFamily(spec);\n\tif (family === 'pie' || family === 'funnel' || family === 'treemap') return 'pie';\n\tif (family === 'radar') return 'radar';\n\treturn 'xychart';\n}\n\nfunction slug(label: string, i: number, taken: Set<string>): string {\n\tlet base = label.normalize('NFKD').replace(/[^\\w-]+/g, '_').replace(/^_+|_+$/g, '') || `a${i + 1}`;\n\tif (!/^[A-Za-z_]/.test(base)) base = `a_${base}`;\n\tlet id = base;\n\tfor (let k = 2; taken.has(id); k++) id = `${base}_${k}`;\n\ttaken.add(id);\n\treturn id;\n}\n\n/** Fields that differ from what the Mermaid text alone would give, for the metadata line. */\nfunction metaFor(spec: ChartSpec, text: string): Record<string, unknown> | null {\n\tconst base = chartFromMermaid(text, { ignoreMeta: true }).spec;\n\tconst meta: Record<string, unknown> = {};\n\tconst same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n\tfor (const key of Object.keys(spec) as (keyof ChartSpec)[]) {\n\t\tif (key === 'series' || key === 'version') continue;\n\t\tif (!same(spec[key], base[key])) meta[key] = spec[key];\n\t}\n\tconst series = spec.series.map((s, i) => {\n\t\tconst b = base.series[i];\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const [k, v] of Object.entries(s)) {\n\t\t\tif (k === 'values') {\n\t\t\t\t// Gaps are written as 0 in Mermaid; record where they are, and exact values that rounded.\n\t\t\t\tif (b && !same(v, b.values)) out.values = v;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!b || !same(v, (b as unknown as Record<string, unknown>)[k])) out[k] = v;\n\t\t}\n\t\treturn out;\n\t});\n\tif (series.some((s) => Object.keys(s).length) || spec.series.length !== base.series.length) meta.series = series;\n\treturn Object.keys(meta).length ? meta : null;\n}\n\n/**\n * Writes a chart as Mermaid: `xychart-beta` for bar, line, area and scatter charts (areas and\n * scatters drawn as lines), `pie` for pies, donuts, funnels and treemaps, `radar-beta` for\n * radars. Anything Mermaid cannot hold (stacking, colours, formats, gaps, trendlines, other\n * chart types) goes into one `%% @pixerate {…}` comment so `chartFromMermaid` gets the chart\n * back exactly, while any Mermaid renderer still draws the basic chart.\n */\nexport function chartToMermaid(spec: ChartSpec, options: ChartMermaidOptions = {}): string {\n\tconst ind = options.indent ?? ' ';\n\tconst family = chartMermaidFamily(spec);\n\tconst visible = spec.series.filter((s) => !s.hidden);\n\tconst lines: string[] = [];\n\tconst v = (x: ChartValue) => (x === null || !Number.isFinite(x) ? '0' : num(x));\n\tif (family === 'pie') {\n\t\tconst s = visible[0] ?? spec.series[0];\n\t\tlines.push(`pie${spec.dataLabels ? ' showData' : ''}`);\n\t\tif (spec.title) lines.push(`${ind}title ${spec.title}`);\n\t\tspec.categories.forEach((c, i) => {\n\t\t\tconst value = s?.values[i];\n\t\t\tif (value !== null && value !== undefined && Number.isFinite(value) && value > 0) lines.push(`${ind}${quote(c)} : ${num(value)}`);\n\t\t});\n\t} else if (family === 'radar') {\n\t\tlines.push('radar-beta');\n\t\tif (spec.title) lines.push(`${ind}title ${spec.title}`);\n\t\tconst taken = new Set<string>();\n\t\tconst ids = spec.categories.map((c, i) => slug(c, i, taken));\n\t\tlines.push(`${ind}axis ${ids.map((id, i) => (id === spec.categories[i] ? id : `${id}[\"${spec.categories[i].replace(/\"/g, \"'\")}\"]`)).join(', ')}`);\n\t\tconst seriesTaken = new Set<string>(ids);\n\t\tfor (const [i, s] of spec.series.entries()) {\n\t\t\tconst id = slug(s.id, i, seriesTaken);\n\t\t\tlines.push(`${ind}curve ${id}[\"${s.name.replace(/\"/g, \"'\")}\"]{${s.values.map(v).join(', ')}}`);\n\t\t}\n\t\tif (spec.yAxis.max !== null) lines.push(`${ind}max ${num(spec.yAxis.max)}`);\n\t\tif (spec.yAxis.min !== null) lines.push(`${ind}min ${num(spec.yAxis.min)}`);\n\t\tif (!spec.legend.show) lines.push(`${ind}showLegend false`);\n\t} else {\n\t\tlines.push(`xychart-beta${spec.orientation === 'horizontal' ? ' horizontal' : ''}`);\n\t\tif (spec.title) lines.push(`${ind}title ${quote(spec.title)}`);\n\t\tconst xTitle = spec.xAxis.title ? ` ${quote(spec.xAxis.title)}` : '';\n\t\tlines.push(`${ind}x-axis${xTitle} [${spec.categories.map(word).join(', ')}]`);\n\t\tconst y = spec.yAxis;\n\t\tif (y.title || y.min !== null || y.max !== null) {\n\t\t\tlet out = `${ind}y-axis`;\n\t\t\tif (y.title) out += ` ${quote(y.title)}`;\n\t\t\tif (y.min !== null || y.max !== null) {\n\t\t\t\t// Mermaid wants both ends; the missing one comes from the data.\n\t\t\t\tconst all = spec.series.flatMap((s) => s.values).filter((x): x is number => x !== null && Number.isFinite(x));\n\t\t\t\tconst lo = y.min ?? Math.min(0, ...all);\n\t\t\t\tconst hi = y.max ?? Math.max(lo + 1, ...all);\n\t\t\t\tout += ` ${num(lo)} --> ${num(hi)}`;\n\t\t\t}\n\t\t\tlines.push(out);\n\t\t}\n\t\tfor (const s of spec.series) {\n\t\t\tconst kind = (s.type ?? (spec.type === 'bar' ? 'bar' : 'line')) === 'bar' ? 'bar' : 'line';\n\t\t\tlines.push(`${ind}${kind} ${quote(s.name)} [${s.values.map(v).join(', ')}]`);\n\t\t}\n\t}\n\tlet text = `${lines.join('\\n')}\\n`;\n\tif (options.meta !== false) {\n\t\tconst meta = metaFor(spec, text);\n\t\tif (meta) {\n\t\t\tconst [header, ...rest] = lines;\n\t\t\ttext = `${[header, `${CHART_MERMAID_META_PREFIX}${JSON.stringify({ v: 1, ...meta })}`, ...rest].join('\\n')}\\n`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport interface ChartMermaidParseOptions {\n\t/** Accept a statement that is still being written (an unclosed `[` list): for streaming views. */\n\tpartial?: boolean;\n\t/** Ignore the `%% @pixerate` line (what the Mermaid text alone says). */\n\tignoreMeta?: boolean;\n}\n\nexport interface ChartMermaidResult {\n\tspec: ChartSpec;\n\t/** Problems, with 1-based `line` numbers. Lines that could not be read are listed and skipped. */\n\tissues: ChartIssue[];\n\tfamily: ChartMermaidFamily | null;\n\t/** The `%% @pixerate` line was found and applied. */\n\thasMeta: boolean;\n}\n\nconst RANGE = /^(-?\\d+(?:\\.\\d+)?)\\s*-->\\s*(-?\\d+(?:\\.\\d+)?)$/;\n\nfunction takeTitle(text: string): { title?: string; rest: string } {\n\tconst t = text.trim();\n\tif (t.startsWith('\"')) {\n\t\tconst end = t.indexOf('\"', 1);\n\t\tif (end > 0) return { title: unquote(t.slice(0, end + 1)), rest: t.slice(end + 1).trim() };\n\t}\n\tif (!t || t.startsWith('[') || RANGE.test(t) || /^-?\\d/.test(t)) return { rest: t };\n\tconst m = /^(\\S+)\\s*(.*)$/.exec(t)!;\n\treturn { title: m[1], rest: m[2].trim() };\n}\n\nfunction parseList(text: string, partial: boolean): string[] | undefined {\n\tconst t = text.trim();\n\tlet m = /^\\[(.*)\\]$/s.exec(t);\n\tif (!m && partial) m = /^\\[(.*)$/s.exec(t);\n\tif (!m) return undefined;\n\tif (!m[1].trim()) return [];\n\tconst items = splitOutside(m[1], ',').map((x) => x.trim());\n\t// A partial list may end mid-item: drop an empty or unfinished last entry.\n\tif (partial && !/\\]$/.test(t)) {\n\t\tconst last = items[items.length - 1];\n\t\tif (!last || (last.startsWith('\"') && !/\"$/.test(last.slice(1)))) items.pop();\n\t}\n\treturn items.map(unquote);\n}\n\n/**\n * Reads Mermaid `xychart-beta`, `pie` or `radar-beta` text as a chart. Never throws: lines it\n * cannot read are reported with their line numbers and skipped, and the result always draws.\n * A `%% @pixerate {…}` line written by `chartToMermaid` restores everything Mermaid cannot hold.\n */\nexport function chartFromMermaid(text: string, options: ChartMermaidParseOptions = {}): ChartMermaidResult {\n\tconst issues: ChartIssue[] = [];\n\tconst partial = !!options.partial;\n\tconst all = text.replace(/^/, '').split(/\\r?\\n/);\n\tlet start = 0;\n\tlet frontTitle: string | undefined;\n\t// Frontmatter (--- … ---) may carry a title.\n\tif (all[0]?.trim() === '---') {\n\t\tconst end = all.findIndex((l, i) => i > 0 && l.trim() === '---');\n\t\tif (end > 0) {\n\t\t\tfor (const l of all.slice(1, end)) {\n\t\t\t\tconst m = /^title:\\s*(.+)$/.exec(l.trim());\n\t\t\t\tif (m) frontTitle = unquote(m[1]);\n\t\t\t}\n\t\t\tstart = end + 1;\n\t\t}\n\t}\n\tlet family: ChartMermaidFamily | null = null;\n\tlet headerLine = -1;\n\tlet horizontal = false;\n\tlet showData = false;\n\tlet meta: Record<string, unknown> | null = null;\n\tfor (let i = start; i < all.length; i++) {\n\t\tconst t = all[i].trim();\n\t\tif (!t || t.startsWith('%%')) continue;\n\t\tlet m: RegExpExecArray | null;\n\t\tif ((m = /^xychart(?:-beta)?(?:\\s+(horizontal|vertical))?\\s*$/i.exec(t))) {\n\t\t\tfamily = 'xychart';\n\t\t\thorizontal = m[1]?.toLowerCase() === 'horizontal';\n\t\t} else if ((m = /^pie(\\s+showData)?(?:\\s+title\\s+(.*))?\\s*$/i.exec(t))) {\n\t\t\tfamily = 'pie';\n\t\t\tshowData = !!m[1];\n\t\t\tif (m[2]) frontTitle = m[2].trim();\n\t\t} else if (/^radar(?:-beta)?\\s*$/i.test(t)) family = 'radar';\n\t\telse issues.push({ path: 'header', line: i + 1, message: `Line ${i + 1}: expected a chart header (xychart-beta, pie or radar-beta), got \"${t.slice(0, 40)}\".` });\n\t\theaderLine = i;\n\t\tbreak;\n\t}\n\tlet title = frontTitle ?? '';\n\tconst categories: string[] = [];\n\tconst series: ChartSeries[] = [];\n\tconst xAxis: ChartAxis = defaultChartAxis(false);\n\tconst yAxis: ChartAxis = defaultChartAxis(true);\n\tconst radarAxes: { id: string; label: string }[] = [];\n\tconst pieSlices: { label: string; value: number }[] = [];\n\tlet legendShow = true;\n\tconst counts = { bar: 0, line: 0 };\n\tconst lineIssue = (i: number, message: string) => issues.push({ path: `line ${i + 1}`, line: i + 1, message: `Line ${i + 1}: ${message}` });\n\tfor (let i = headerLine + 1; family && i < all.length; i++) {\n\t\tconst raw = all[i];\n\t\tconst t = raw.trim();\n\t\tif (!t) continue;\n\t\tif (t.startsWith(CHART_MERMAID_META_PREFIX.trim())) {\n\t\t\tif (options.ignoreMeta) continue;\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(t.slice(CHART_MERMAID_META_PREFIX.trim().length).trim());\n\t\t\t\tif (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) meta = parsed;\n\t\t\t\telse lineIssue(i, 'the @pixerate metadata is not a JSON object; it was ignored.');\n\t\t\t} catch {\n\t\t\t\tif (!partial) lineIssue(i, 'the @pixerate metadata is not valid JSON; it was ignored.');\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (t.startsWith('%%')) continue;\n\t\tconst isLast = i === all.length - 1 || all.slice(i + 1).every((l) => !l.trim());\n\t\tlet m: RegExpExecArray | null;\n\t\tif ((m = /^title\\s+(.+)$/i.exec(t))) {\n\t\t\ttitle = unquote(m[1]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (family === 'xychart') {\n\t\t\tif ((m = /^x-axis\\b(.*)$/i.exec(t))) {\n\t\t\t\tconst { title: xt, rest } = takeTitle(m[1]);\n\t\t\t\tif (xt) xAxis.title = xt;\n\t\t\t\tconst list = parseList(rest, partial && isLast);\n\t\t\t\tif (list) categories.splice(0, categories.length, ...list);\n\t\t\t\telse if (RANGE.test(rest)) {\n\t\t\t\t\tconst r = RANGE.exec(rest)!;\n\t\t\t\t\txAxis.min = Number(r[1]);\n\t\t\t\t\txAxis.max = Number(r[2]);\n\t\t\t\t} else if (rest) lineIssue(i, `expected x-axis [a, b, …] or a range \"min --> max\", got \"${rest.slice(0, 40)}\".`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ((m = /^y-axis\\b(.*)$/i.exec(t))) {\n\t\t\t\tconst { title: yt, rest } = takeTitle(m[1]);\n\t\t\t\tif (yt) yAxis.title = yt;\n\t\t\t\tconst r = RANGE.exec(rest);\n\t\t\t\tif (r) {\n\t\t\t\t\tyAxis.min = Number(r[1]);\n\t\t\t\t\tyAxis.max = Number(r[2]);\n\t\t\t\t} else if (rest) lineIssue(i, `expected y-axis \"min --> max\", got \"${rest.slice(0, 40)}\".`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ((m = /^(bar|line)\\b(.*)$/i.exec(t))) {\n\t\t\t\tconst kind = m[1].toLowerCase() as 'bar' | 'line';\n\t\t\t\tconst { title: st, rest } = takeTitle(m[2]);\n\t\t\t\tconst list = parseList(rest, partial && isLast);\n\t\t\t\tif (!list) {\n\t\t\t\t\tif (!(partial && isLast)) lineIssue(i, `expected ${kind} [1, 2, 3], got \"${rest.slice(0, 40)}\".`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst values = list.map((x) => (x.trim() === '' ? null : Number(x)));\n\t\t\t\tif (values.some((x) => x !== null && !Number.isFinite(x))) {\n\t\t\t\t\tlineIssue(i, `${kind} values must be numbers.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcounts[kind]++;\n\t\t\t\tseries.push({ id: `series-${series.length + 1}`, name: st ?? `${kind === 'bar' ? 'Bar' : 'Line'} ${counts[kind]}`, values: values as ChartValue[], type: kind });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (family === 'pie') {\n\t\t\tif ((m = /^\"((?:[^\"\\\\]|\\\\.)*)\"\\s*:\\s*(-?\\d+(?:\\.\\d+)?)\\s*$/.exec(t))) {\n\t\t\t\tpieSlices.push({ label: m[1].replace(/#quot;/g, '\"'), value: Number(m[2]) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (/^showData\\s*$/i.test(t)) {\n\t\t\t\tshowData = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (family === 'radar') {\n\t\t\tif ((m = /^axis\\s+(.+)$/.exec(t))) {\n\t\t\t\tfor (const part of splitOutside(m[1], ',')) {\n\t\t\t\t\tconst a = /^([A-Za-z_][\\w-]*)\\s*(?:\\[\\s*\"((?:[^\"\\\\]|\\\\.)*)\"\\s*\\])?$/.exec(part.trim());\n\t\t\t\t\tif (a) radarAxes.push({ id: a[1], label: a[2] ?? a[1] });\n\t\t\t\t\telse lineIssue(i, `could not read the axis \"${part.trim()}\".`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ((m = /^curve\\s+([A-Za-z_][\\w-]*)\\s*(?:\\[\\s*\"((?:[^\"\\\\]|\\\\.)*)\"\\s*\\])?\\s*\\{(.*)\\}?\\s*$/.exec(t))) {\n\t\t\t\tconst body = m[3].replace(/\\}\\s*$/, '');\n\t\t\t\tconst entries = body.trim() ? splitOutside(body, ',').map((x) => x.trim()).filter(Boolean) : [];\n\t\t\t\tconst ids = radarAxes.map((a) => a.id);\n\t\t\t\tconst values: ChartValue[] = ids.map(() => null);\n\t\t\t\tlet k = 0;\n\t\t\t\tfor (const e of entries) {\n\t\t\t\t\tconst keyed = /^([A-Za-z_][\\w-]*)\\s*:\\s*(-?\\d+(?:\\.\\d+)?)$/.exec(e);\n\t\t\t\t\tif (keyed) {\n\t\t\t\t\t\tconst at = ids.indexOf(keyed[1]);\n\t\t\t\t\t\tif (at >= 0) values[at] = Number(keyed[2]);\n\t\t\t\t\t\telse lineIssue(i, `curve ${m[1]} names an unknown axis \"${keyed[1]}\".`);\n\t\t\t\t\t} else if (/^-?\\d+(?:\\.\\d+)?$/.test(e)) {\n\t\t\t\t\t\tif (k < values.length) values[k] = Number(e);\n\t\t\t\t\t\telse values.push(Number(e));\n\t\t\t\t\t\tk++;\n\t\t\t\t\t} else lineIssue(i, `could not read \"${e}\" in curve ${m[1]}.`);\n\t\t\t\t}\n\t\t\t\tseries.push({ id: m[1], name: m[2] ?? m[1], values });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ((m = /^(max|min|ticks|graticule|showLegend)\\s+(\\S+)$/.exec(t))) {\n\t\t\t\tif (m[1] === 'max') yAxis.max = Number(m[2]);\n\t\t\t\telse if (m[1] === 'min') yAxis.min = Number(m[2]);\n\t\t\t\telse if (m[1] === 'showLegend') legendShow = m[2] !== 'false';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!(partial && isLast)) lineIssue(i, `could not read \"${t.slice(0, 60)}\"; it was skipped.`);\n\t}\n\n\tlet input: Record<string, unknown>;\n\tif (family === 'pie') {\n\t\tinput = {\n\t\t\ttype: 'pie',\n\t\t\ttitle,\n\t\t\tdataLabels: showData,\n\t\t\tcategories: pieSlices.map((s) => s.label),\n\t\t\tseries: [{ id: 'series-1', name: title || 'Values', values: pieSlices.map((s) => s.value) }]\n\t\t};\n\t} else if (family === 'radar') {\n\t\tinput = { type: 'radar', title, categories: radarAxes.map((a) => a.label), series, yAxis, legend: { show: legendShow, position: 'bottom' } };\n\t} else {\n\t\tconst allBar = series.length > 0 && series.every((s) => s.type === 'bar');\n\t\tconst allLine = series.length > 0 && series.every((s) => s.type === 'line');\n\t\tconst type = allLine ? 'line' : 'bar';\n\t\tconst longest = Math.max(0, ...series.map((s) => s.values.length));\n\t\tconst cats = categories.length ? categories : Array.from({ length: longest }, (_, i) => `${i + 1}`);\n\t\tinput = {\n\t\t\ttype,\n\t\t\ttitle,\n\t\t\torientation: horizontal ? 'horizontal' : 'vertical',\n\t\t\tcategories: cats,\n\t\t\txAxis,\n\t\t\tyAxis,\n\t\t\t// Series that match the chart type do not need their own type.\n\t\t\tseries: series.map((s) => (allBar || allLine || s.type === type ? { ...s, type: undefined } : s))\n\t\t};\n\t}\n\tif (meta) {\n\t\tconst { v: _v, series: metaSeries, ...rest } = meta as Record<string, unknown> & { v?: number; series?: Record<string, unknown>[] };\n\t\tObject.assign(input, rest);\n\t\tif (Array.isArray(metaSeries)) {\n\t\t\tconst base = (input.series as Record<string, unknown>[]) ?? [];\n\t\t\tinput.series = metaSeries.map((extra, i) => ({ ...(base[i] ?? {}), ...(extra ?? {}) }));\n\t\t}\n\t}\n\tconst { spec, issues: specIssues } = normalizeChartSpec(input);\n\tif (!family && !partial && !issues.length) issues.push({ path: 'header', message: 'The text is empty: expected a chart header (xychart-beta, pie or radar-beta).' });\n\treturn { spec, issues: [...issues, ...specIssues], family, hasMeta: !!meta };\n}\n\nexport interface FoundChartMermaid {\n\tsource: string;\n\tfamily: ChartMermaidFamily;\n\t/** 1-based line where the block starts in the input. */\n\tline: number;\n}\n\n/**\n * Finds Mermaid charts in Markdown or chat text: fenced ```mermaid blocks (and unlabelled\n * fences) whose header is xychart-beta, pie or radar-beta, else the whole text when it is one.\n */\nexport function findMermaidCharts(text: string): FoundChartMermaid[] {\n\tconst lines = text.replace(/^/, '').split(/\\r?\\n/);\n\tconst found: FoundChartMermaid[] = [];\n\tconst familyOf = (body: string): ChartMermaidFamily | null => {\n\t\tconst header = body.split(/\\r?\\n/).find((l) => l.trim() && !l.trim().startsWith('%%') && l.trim() !== '---');\n\t\tif (!header) return null;\n\t\tif (/^\\s*xychart(-beta)?\\b/.test(header)) return 'xychart';\n\t\tif (/^\\s*pie\\b/.test(header)) return 'pie';\n\t\tif (/^\\s*radar(-beta)?\\b/.test(header)) return 'radar';\n\t\treturn null;\n\t};\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst open = /^ {0,3}(`{3,}|~{3,})\\s*([\\w-]*)/.exec(lines[i]);\n\t\tif (!open) continue;\n\t\tconst fence = open[1];\n\t\tconst info = open[2].toLowerCase();\n\t\tlet end = i + 1;\n\t\twhile (end < lines.length && !new RegExp(`^ {0,3}${fence[0]}{${fence.length},}\\\\s*$`).test(lines[end])) end++;\n\t\tconst body = lines.slice(i + 1, end).join('\\n');\n\t\tif (!info || info === 'mermaid') {\n\t\t\tconst family = familyOf(body);\n\t\t\tif (family) found.push({ source: `${body.trimEnd()}\\n`, family, line: i + 2 });\n\t\t}\n\t\ti = end;\n\t}\n\tif (!found.length) {\n\t\tconst family = familyOf(text);\n\t\tif (family) found.push({ source: `${text.trim()}\\n`, family, line: 1 });\n\t}\n\treturn found;\n}\n\n","import type { JsonSchema } from '../tools/schema.js';\nimport {\n\tCHART_AXIS_KINDS,\n\tCHART_CURVES,\n\tCHART_LABEL_POSITIONS,\n\tCHART_LEGEND_POSITIONS,\n\tCHART_MARKERS,\n\tCHART_NUMBER_STYLES,\n\tCHART_ORIENTATIONS,\n\tCHART_SERIES_TYPES,\n\tCHART_STACKINGS,\n\tCHART_TRENDLINE_TYPES,\n\tCHART_TYPES\n} from './spec.js';\n\n// JSON Schema fragments shared by the chart commands and the chart agent tools.\n\nexport const VALUE: JsonSchema = { type: ['number', 'string', 'null'], description: 'A number, numeric text (\"1,200\", \"12%\", \"$40\", \"(3)\") or null for a gap.' };\nexport const SERIES_REF: JsonSchema = { type: 'string', description: 'Series id (from get_chart) or exact series name.' };\nexport const CATEGORY_REF: JsonSchema = { type: ['string', 'integer'], description: 'Category index (0-based) or exact category label.' };\nexport const WIDTH: JsonSchema = { type: 'number', minimum: 50, maximum: 4096, description: 'Width in pixels (default 640).' };\nexport const HEIGHT: JsonSchema = { type: 'number', minimum: 50, maximum: 4096, description: 'Height in pixels (default 400).' };\n\nexport const FORMAT: JsonSchema = {\n\ttype: 'object',\n\tdescription: 'How numbers are written on this axis or series.',\n\tproperties: {\n\t\tstyle: { type: 'string', enum: [...CHART_NUMBER_STYLES], description: 'number (default), percent (0.25 → 25%), currency or compact (1.2K).' },\n\t\tdecimals: { type: 'integer', minimum: 0, maximum: 10, description: 'Fixed decimals (default: what the ticks need).' },\n\t\tcurrency: { type: 'string', description: 'ISO currency code for style \"currency\", e.g. \"EUR\" (default USD).' },\n\t\tprefix: { type: 'string', description: 'Text before every number.' },\n\t\tsuffix: { type: 'string', description: 'Text after every number.' },\n\t\tcode: { type: 'string', description: 'Spreadsheet format code such as \"#,##0.0,,\\\\\"M\\\\\"\" or \"0.0%\"; wins over the other fields.' }\n\t},\n\tadditionalProperties: false\n};\n\nexport const AXIS = (what: string): JsonSchema => ({\n\ttype: 'object',\n\tdescription: what,\n\tproperties: {\n\t\tshow: { type: 'boolean', description: 'Draw the axis labels (default true).' },\n\t\ttitle: { type: 'string', description: 'Axis title (\"\" for none).' },\n\t\tmin: { type: ['number', 'null'], description: 'Fixed lower bound, or null for automatic.' },\n\t\tmax: { type: ['number', 'null'], description: 'Fixed upper bound, or null for automatic.' },\n\t\tstep: { type: ['number', 'null'], exclusiveMinimum: 0, description: 'Fixed distance between ticks, or null for automatic.' },\n\t\tgridlines: { type: 'boolean', description: 'Grid lines at each tick.' },\n\t\tformat: FORMAT,\n\t\tkind: { type: ['string', 'null'], enum: [...CHART_AXIS_KINDS, null], description: 'Category axis only: \"date\" reads categories as dates and labels them by calendar steps.' }\n\t},\n\tadditionalProperties: false\n});\n\nexport const TRENDLINE_PROPS: Record<string, JsonSchema> = {\n\ttype: { type: 'string', enum: [...CHART_TRENDLINE_TYPES], description: 'Fit: linear, exponential, logarithmic, power, polynomial or moving-average.' },\n\torder: { type: 'integer', minimum: 2, maximum: 6, description: 'Polynomial order (default 2).' },\n\tperiod: { type: 'integer', minimum: 2, description: 'Moving-average period in points (default 2).' },\n\tforward: { type: 'number', minimum: 0, description: 'Extend the line this many x units past the last point (default 0).' },\n\tbackward: { type: 'number', minimum: 0, description: 'Extend the line this many x units before the first point (default 0).' },\n\tintercept: { type: ['number', 'null'], description: 'Force the fit through this y at x = 0 (linear, polynomial, exponential).' },\n\tshowEquation: { type: 'boolean', description: 'Write the fitted equation on the chart.' },\n\tshowR2: { type: 'boolean', description: 'Write R² on the chart.' },\n\tname: { type: 'string', description: 'Legend name (default e.g. \"Linear (Sales)\").' },\n\tcolor: { type: 'string', description: 'CSS colour (default: the series colour).' }\n};\n\nexport const SERIES_PROPS: Record<string, JsonSchema> = {\n\tname: { type: 'string', description: 'Series name (legend and data grid header).' },\n\tvalues: { type: 'array', items: VALUE, description: 'One value per category, in category order (padded with gaps).' },\n\tcolor: { type: ['string', 'null'], description: 'CSS colour, or null for the palette colour.' },\n\ttype: { type: ['string', 'null'], enum: [...CHART_SERIES_TYPES, null], description: 'Draw this series as bar, line, area or scatter (a combo chart); null follows the chart type.' },\n\thidden: { type: 'boolean', description: 'Hide the series (its data is kept).' },\n\taxis: { type: ['string', 'null'], enum: ['primary', 'secondary', null], description: 'Value axis: secondary is drawn on the right with its own scale.' },\n\tx: { type: ['array', 'null'], items: VALUE, description: 'Numeric x per category, for scatter and bubble charts.' },\n\tsizes: { type: ['array', 'null'], items: VALUE, description: 'Bubble sizes per category (area is proportional to size).' },\n\tpointColors: { type: ['array', 'null'], items: { type: ['string', 'null'] }, description: 'Colour per category (null keeps the series colour).' },\n\tmarker: { type: ['string', 'null'], enum: [...CHART_MARKERS, null], description: 'Point marker shape for line, area and scatter series.' },\n\tcurve: { type: ['string', 'null'], enum: [...CHART_CURVES, null], description: 'Line shape for this series: linear, smooth or step.' },\n\tdataLabels: { type: ['boolean', 'null'], description: 'Value labels for this series (null follows the chart).' },\n\tformat: { ...FORMAT, type: ['object', 'null'], description: 'How this series\\' labels are written (null follows the value axis).' }\n};\n\n\nexport const CHART_UPDATE_PROPERTIES: Record<string, JsonSchema> = {\n\t\t\t\ttype: { type: 'string', enum: [...CHART_TYPES], description: 'Chart type.' },\n\t\t\t\ttitle: { type: 'string', description: 'Title (\"\" for none).' },\n\t\t\t\tsubtitle: { type: 'string', description: 'Subtitle (\"\" for none).' },\n\t\t\t\txAxis: AXIS('Category axis (or numeric x axis of scatter / bubble charts).'),\n\t\t\t\tyAxis: AXIS('Value axis.'),\n\t\t\t\tyAxis2: AXIS('Secondary value axis (for series with axis \"secondary\").'),\n\t\t\t\tlegend: {\n\t\t\t\t\ttype: 'object',\n\t\t\t\t\tdescription: 'Legend.',\n\t\t\t\t\tproperties: { show: { type: 'boolean', description: 'Show the legend.' }, position: { type: 'string', enum: [...CHART_LEGEND_POSITIONS], description: 'Where the legend goes.' } },\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t},\n\t\t\t\tstacking: { type: 'string', enum: [...CHART_STACKINGS], description: 'none, stacked, or percent (each category scaled to 100%).' },\n\t\t\t\torientation: { type: 'string', enum: [...CHART_ORIENTATIONS], description: 'horizontal draws bars sideways.' },\n\t\t\t\tcurve: { type: 'string', enum: [...CHART_CURVES], description: 'Line shape: linear, smooth or step.' },\n\t\t\t\tpoints: { type: 'boolean', description: 'Dots on line and area series.' },\n\t\t\t\tdataLabels: { type: 'boolean', description: 'Value labels on bars, points and slices.' },\n\t\t\t\tlabelPosition: { type: 'string', enum: [...CHART_LABEL_POSITIONS], description: 'Bar label position; auto drops labels that do not fit.' },\n\t\t\t\tpalette: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Series colours in order (CSS colours).' },\n\t\t\t\tinnerRadius: { type: 'number', minimum: 0, maximum: 0.9, description: 'Donut hole as a fraction of the radius.' },\n\t\t\t\tgapWidth: { type: 'number', minimum: 0, maximum: 0.9, description: 'Space between bar groups as a fraction of the category (default 0.28).' },\n\t\t\t\toverlap: { type: 'number', minimum: -1, maximum: 1, description: 'Bar overlap within a group as a fraction of a bar (negative: a gap; default -0.12).' },\n\t\t\t\tbins: { type: ['integer', 'null'], minimum: 1, maximum: 500, description: 'Histogram bin count, or null for √n.' },\n\t\t\t\tshowTotal: { type: 'boolean', description: 'Waterfall: append a total bar.' }\n\t\t\t};\n","import type { CommandSpec } from '../commands/registry.js';\nimport { parseCsv } from '../spreadsheet/csv.js';\nimport { checkChartColors } from './color.js';\nimport type { ChartController, ChartSpecPatch } from './controller.js';\nimport { chartFromMermaid, chartToMermaid } from './mermaid.js';\nimport { chartToOoxml } from './ooxml.js';\nimport { CHART_COLOR_SCHEMES, CHART_LAYOUT_PRESETS } from './presets.js';\nimport { recommendChartTypes } from './recommend.js';\nimport { CATEGORY_REF, CHART_UPDATE_PROPERTIES, HEIGHT, SERIES_PROPS, SERIES_REF, TRENDLINE_PROPS, VALUE, WIDTH } from './schemas.js';\nimport { chartColorsByCategory, chartDataToTable, chartSeriesColor, chartSliceColor } from './spec.js';\nimport { summarizeChart } from './summary.js';\nimport { chartToSvg } from './svg.js';\nimport type { ChartTrendline } from './types.js';\n\nexport interface ChartCommandOptions {\n\t/** Id prefix (default `chart.`); use one per chart when several are registered. */\n\tprefix?: string;\n\t/** Palette group (default `Chart`). */\n\tgroup?: string;\n\t/** Command scope. Omit for global commands. */\n\tscope?: string;\n}\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nconst check = (result: { ok: boolean; message?: string }) => {\n\tif (!result.ok) fail(result.message ?? 'The change was rejected.');\n};\n\n/**\n * Palette and agent commands for a chart: describe, update presentation, replace data, set\n * values, add / remove series, categories and trendlines, apply presets, switch rows and\n * columns, import CSV or Mermaid, export SVG, Mermaid or Office XML, recommend types and\n * check colours. Register them in a `CommandRegistry` and agents get them through\n * `createCommandToolProvider`; `createChartToolProvider` offers the same operations as\n * individual tools. Failures throw sentences, which the registry returns as\n * `{ ok: false, code: 'failed', message }`.\n */\nexport function createChartCommands(controller: ChartController, options: ChartCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'chart.';\n\tconst base = { group: options.group ?? 'Chart', ...(options.scope ? { scope: options.scope } : {}) };\n\tconst seriesIds = () => controller.getSpec().series.map((s) => s.id);\n\tconst resolveSeries = (ref: string) => {\n\t\tconst spec = controller.getSpec();\n\t\tconst series = spec.series.find((s) => s.id === ref) ?? spec.series.find((s) => s.name === ref);\n\t\tif (!series) fail(`There is no series \"${ref}\"; expected one of ${seriesIds().map((id) => `\"${id}\"`).join(', ') || '(none yet)'}.`);\n\t\treturn series!;\n\t};\n\tconst resolveCategory = (ref: string | number) => {\n\t\tconst categories = controller.getSpec().categories;\n\t\tconst index = typeof ref === 'number' ? ref : categories.indexOf(ref);\n\t\tif (index < 0 || index >= categories.length || !Number.isInteger(index)) fail(`There is no category ${JSON.stringify(ref)}; expected an index from 0 to ${categories.length - 1} or one of the labels.`);\n\t\treturn index;\n\t};\n\tconst object = (properties: Record<string, unknown>, required?: string[]) => ({ type: 'object' as const, properties, ...(required ? { required } : {}), additionalProperties: false }) as any;\n\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}describe`,\n\t\t\tlabel: 'Describe Chart',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'data', 'spec', 'get', 'summary'],\n\t\t\tdescription: 'Returns the chart spec, its data as a table (series names in the header row) and a summary: per-series min / max / mean / trend, axes as drawn, layout warnings and a colour check.',\n\t\t\tparams: object({ width: WIDTH, height: HEIGHT }),\n\t\t\trun: (_ctx: unknown, params: { width?: number; height?: number } = {}) => {\n\t\t\t\tconst spec = controller.getSpec();\n\t\t\t\treturn { spec: controller.toJSON(), table: chartDataToTable(spec), summary: summarizeChart(controller.toJSON(), { width: params?.width ?? 640, height: params?.height ?? 400 }), issues: controller.getState().issues };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}update`,\n\t\t\tlabel: 'Change Chart…',\n\t\t\tkeywords: ['chart', 'title', 'axis', 'legend', 'stack', 'style', 'format', 'type'],\n\t\t\tdescription:\n\t\t\t\t'Changes chart presentation as one undo step: type, titles, axes (xAxis = categories, yAxis = values, yAxis2 = secondary values), legend, stacking, orientation, curve, points, data labels, palette, donut hole, bar spacing, histogram bins or waterfall total. Invalid values change nothing and return why.',\n\t\t\tparams: object(CHART_UPDATE_PROPERTIES),\n\t\t\trun: (_ctx: unknown, params: ChartSpecPatch) => {\n\t\t\t\tcheck(controller.update(params));\n\t\t\t\treturn { spec: controller.toJSON() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setData`,\n\t\t\tlabel: 'Replace Chart Data…',\n\t\t\tkeywords: ['chart', 'data', 'series', 'categories'],\n\t\t\tdescription: 'Replaces the categories and series as one undo step. Each series has one value per category (padded with gaps).',\n\t\t\tparams: object({\n\t\t\t\tcategories: { type: 'array', items: { type: 'string' }, description: 'Category labels in order.' },\n\t\t\t\tseries: { type: 'array', description: 'The new series.', items: object({ id: { type: 'string', description: 'Stable id (optional).' }, ...SERIES_PROPS }, ['name', 'values']) }\n\t\t\t}),\n\t\t\trun: (_ctx: unknown, params: { categories?: string[]; series?: any[] }) => {\n\t\t\t\tcheck(controller.setData(params));\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setValues`,\n\t\t\tlabel: 'Set Chart Values…',\n\t\t\tkeywords: ['chart', 'value', 'cell', 'edit'],\n\t\t\tdescription: 'Sets individual values as one undo step. Series by id or name; category by index or label.',\n\t\t\tparams: object({ cells: { type: 'array', minItems: 1, description: 'Values to set.', items: object({ series: SERIES_REF, category: CATEGORY_REF, value: VALUE }, ['series', 'category', 'value']) } }, ['cells']),\n\t\t\trun: (_ctx: unknown, params: { cells: { series: string; category: string | number; value: unknown }[] }) => {\n\t\t\t\tcheck(controller.setValues(params.cells.map((c) => ({ seriesId: resolveSeries(c.series).id, index: resolveCategory(c.category), value: c.value }))));\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addSeries`,\n\t\t\tlabel: 'Add Series',\n\t\t\tkeywords: ['chart', 'series', 'new'],\n\t\t\tdescription: 'Adds a series (default: an empty one at the end). Returns its id.',\n\t\t\tparams: object({ ...SERIES_PROPS, id: { type: 'string', description: 'Id to use (default series-N).' }, at: { type: 'integer', minimum: 0, description: 'Position (default: last).' } }),\n\t\t\trun: (_ctx: unknown, params: { at?: number; name?: string; values?: unknown[] } = {}) => {\n\t\t\t\tconst { at, ...input } = params ?? {};\n\t\t\t\tconst clean = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== null));\n\t\t\t\tconst result = controller.addSeries(clean as any, { at });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { id: (result as { id: string }).id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}updateSeries`,\n\t\t\tlabel: 'Change Series…',\n\t\t\tkeywords: ['chart', 'series', 'rename', 'colour', 'color', 'hide', 'axis', 'marker'],\n\t\t\tdescription: 'Renames, recolours, hides, moves to the secondary axis or changes how a series is drawn (null resets a field).',\n\t\t\tparams: object({ series: SERIES_REF, ...Object.fromEntries(Object.entries(SERIES_PROPS).filter(([k]) => k !== 'values')) }, ['series']),\n\t\t\trun: (_ctx: unknown, params: { series: string } & Record<string, unknown>) => {\n\t\t\t\tconst { series, ...patch } = params;\n\t\t\t\tconst id = resolveSeries(series).id;\n\t\t\t\tcheck(controller.updateSeries(id, patch as any));\n\t\t\t\treturn { series: controller.getSeries(id) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeSeries`,\n\t\t\tlabel: 'Delete Series',\n\t\t\tkeywords: ['chart', 'series', 'remove'],\n\t\t\tdescription: 'Deletes a series by id or name.',\n\t\t\tparams: object({ series: SERIES_REF }, ['series']),\n\t\t\trun: (_ctx: unknown, params: { series: string }) => {\n\t\t\t\tcheck(controller.removeSeries(resolveSeries(params.series).id));\n\t\t\t\treturn { series: seriesIds() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addCategory`,\n\t\t\tlabel: 'Add Category',\n\t\t\tkeywords: ['chart', 'category', 'row', 'label'],\n\t\t\tdescription: 'Inserts a category (gaps in every series) at `at` (default: the end).',\n\t\t\tparams: object({ label: { type: 'string', description: 'Category label (default: its number).' }, at: { type: 'integer', minimum: 0, description: 'Index to insert at (default: the end).' } }),\n\t\t\trun: (_ctx: unknown, params: { label?: string; at?: number } = {}) => controller.addCategory(params?.label, { at: params?.at })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeCategory`,\n\t\t\tlabel: 'Delete Category',\n\t\t\tkeywords: ['chart', 'category', 'row', 'remove'],\n\t\t\tdescription: 'Deletes a category (and its values) by index or label.',\n\t\t\tparams: object({ category: CATEGORY_REF }, ['category']),\n\t\t\trun: (_ctx: unknown, params: { category: string | number }) => {\n\t\t\t\tcheck(controller.removeCategory(resolveCategory(params.category)));\n\t\t\t\treturn { categories: controller.getSpec().categories };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addTrendline`,\n\t\t\tlabel: 'Add Trendline…',\n\t\t\tkeywords: ['chart', 'trend', 'regression', 'fit', 'forecast', 'moving average'],\n\t\t\tdescription: 'Fits a trendline to a series (linear, exponential, logarithmic, power, polynomial or moving average). Returns its index and the fit.',\n\t\t\tparams: object({ series: SERIES_REF, ...TRENDLINE_PROPS }, ['series', 'type']),\n\t\t\trun: (_ctx: unknown, params: { series: string } & ChartTrendline) => {\n\t\t\t\tconst { series, ...line } = params;\n\t\t\t\tconst result = controller.addTrendline(resolveSeries(series).id, line);\n\t\t\t\tcheck(result);\n\t\t\t\tconst ok = result as { index: number; fit: { coefficients: number[]; r2: number | null; equation: string } | null };\n\t\t\t\treturn { index: ok.index, ...(ok.fit ? { coefficients: ok.fit.coefficients, r2: ok.fit.r2, equation: ok.fit.equation } : {}) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeTrendline`,\n\t\t\tlabel: 'Delete Trendline',\n\t\t\tkeywords: ['chart', 'trend', 'remove'],\n\t\t\tdescription: 'Deletes a trendline from a series.',\n\t\t\tparams: object({ series: SERIES_REF, index: { type: 'integer', minimum: 0, description: 'Trendline index (0 = first).' } }, ['series', 'index']),\n\t\t\trun: (_ctx: unknown, params: { series: string; index: number }) => {\n\t\t\t\tcheck(controller.removeTrendline(resolveSeries(params.series).id, params.index));\n\t\t\t\treturn { trendlines: controller.getSeries(resolveSeries(params.series).id)?.trendlines ?? [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}applyPreset`,\n\t\t\tlabel: 'Apply Chart Style…',\n\t\t\tkeywords: ['chart', 'quick layout', 'style', 'colours', 'colors', 'monochrome', 'theme'],\n\t\t\tdescription: 'Applies a quick layout and / or colour scheme as one undo step.',\n\t\t\tparams: object({\n\t\t\t\tlayout: { type: 'string', enum: CHART_LAYOUT_PRESETS.map((p) => p.id), description: 'Quick layout id.' },\n\t\t\t\tcolors: { type: 'string', enum: CHART_COLOR_SCHEMES.map((p) => p.id), description: 'Colour scheme id.' }\n\t\t\t}),\n\t\t\trun: (_ctx: unknown, params: { layout?: string; colors?: string } = {}) => {\n\t\t\t\tcheck(controller.applyPreset(params ?? {}));\n\t\t\t\treturn { spec: controller.toJSON() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transpose`,\n\t\t\tlabel: 'Switch Rows and Columns',\n\t\t\tkeywords: ['chart', 'transpose', 'swap', 'rows', 'columns', 'series'],\n\t\t\tdescription: 'Swaps series and categories as one undo step.',\n\t\t\trun: () => {\n\t\t\t\tcheck(controller.transpose());\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importCsv`,\n\t\t\tlabel: 'Import Chart Data from CSV…',\n\t\t\tkeywords: ['chart', 'csv', 'tsv', 'paste', 'import'],\n\t\t\tdescription: 'Replaces the data with CSV / TSV text: by default the first column holds categories and the first row series names.',\n\t\t\tparams: object(\n\t\t\t\t{\n\t\t\t\t\tcsv: { type: 'string', description: 'CSV or TSV text.' },\n\t\t\t\t\tseriesIn: { type: 'string', enum: ['columns', 'rows'], description: 'Series run down columns (default) or along rows.' },\n\t\t\t\t\theader: { type: ['boolean', 'string'], enum: [true, false, 'auto'], description: 'The first row holds series names (default true).' }\n\t\t\t\t},\n\t\t\t\t['csv']\n\t\t\t),\n\t\t\trun: (_ctx: unknown, params: { csv: string; seriesIn?: 'columns' | 'rows'; header?: boolean | 'auto' }) => {\n\t\t\t\tconst result = controller.importCsv(params.csv, { seriesIn: params.seriesIn, header: params.header });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()), issues: result.issues ?? [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importMermaid`,\n\t\t\tlabel: 'Import Mermaid Chart…',\n\t\t\tkeywords: ['chart', 'mermaid', 'markdown', 'xychart', 'pie', 'radar', 'import'],\n\t\t\tdescription: 'Replaces the chart with Mermaid xychart-beta, pie or radar-beta text (one undo step). Unreadable lines are listed with line numbers.',\n\t\t\tparams: object({ mermaid: { type: 'string', description: 'Mermaid text.' } }, ['mermaid']),\n\t\t\trun: (_ctx: unknown, params: { mermaid: string }) => {\n\t\t\t\tconst read = chartFromMermaid(params.mermaid);\n\t\t\t\tif (!read.family) fail(read.issues.map((i) => i.message).join(' ') || 'Expected Mermaid starting with xychart-beta, pie or radar-beta.');\n\t\t\t\tcheck(controller.update({ ...read.spec } as ChartSpecPatch, { label: 'Import Mermaid chart' }));\n\t\t\t\treturn { spec: controller.toJSON(), issues: read.issues };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportMermaid`,\n\t\t\tlabel: 'Copy Chart as Mermaid',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'mermaid', 'markdown', 'export'],\n\t\t\tdescription: 'Returns the chart as Mermaid text (with a round-trip comment unless meta is false).',\n\t\t\tparams: object({ meta: { type: 'boolean', description: 'Include the %% @pixerate round-trip comment (default true).' } }),\n\t\t\trun: (_ctx: unknown, params: { meta?: boolean } = {}) => ({ mermaid: chartToMermaid(controller.toJSON(), { meta: params?.meta }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportOoxml`,\n\t\t\tlabel: 'Export Chart as Office XML',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'office', 'word', 'powerpoint', 'docx', 'pptx', 'xml', 'export'],\n\t\t\tdescription: 'Returns the chart as a DrawingML chart part (c:chartSpace) and what could not be written.',\n\t\t\trun: () => chartToOoxml(controller.toJSON())\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportSvg`,\n\t\t\tlabel: 'Export Chart as SVG',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'svg', 'export', 'image'],\n\t\t\tdescription: 'Returns the chart drawn as a standalone, accessible SVG string (with <title> and <desc>).',\n\t\t\tparams: object({ width: WIDTH, height: HEIGHT }),\n\t\t\trun: (_ctx: unknown, params: { width?: number; height?: number } = {}) => ({\n\t\t\t\tsvg: chartToSvg(controller.toJSON(), { width: params?.width ?? 640, height: params?.height ?? 400 })\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}recommend`,\n\t\t\tlabel: 'Recommend Chart Types',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'recommend', 'suggest', 'type'],\n\t\t\tdescription: 'Suggests chart types for the current data (or CSV), best first, each with a reason.',\n\t\t\tparams: object({ csv: { type: 'string', description: 'CSV text to analyse instead of the current data.' } }),\n\t\t\trun: (_ctx: unknown, params: { csv?: string } = {}) => ({\n\t\t\t\trecommendations: recommendChartTypes(params?.csv !== undefined ? parseCsv(params.csv) : chartDataToTable(controller.getSpec()))\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}checkColors`,\n\t\t\tlabel: 'Check Chart Colours',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'colour', 'color', 'accessibility', 'colour-blind', 'contrast'],\n\t\t\tdescription: 'Checks that the series colours can be told apart (including with colour-blindness) and stand out from the background.',\n\t\t\trun: () => {\n\t\t\t\tconst s = controller.getSpec();\n\t\t\t\tconst visible = s.series.filter((x) => !x.hidden);\n\t\t\t\tconst colors = chartColorsByCategory(s.type) ? s.categories.map((_, i) => visible[0]?.pointColors?.[i] || chartSliceColor(s, i)) : visible.map((x) => chartSeriesColor(s, s.series.indexOf(x)));\n\t\t\t\treturn { colors, ...checkChartColors(colors) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}undo`,\n\t\t\tlabel: 'Undo Chart Edit',\n\t\t\tkeywords: ['chart', 'undo'],\n\t\t\tenabled: () => controller.getState().canUndo || 'Nothing to undo',\n\t\t\trun: () => ({ undone: controller.undo() })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}redo`,\n\t\t\tlabel: 'Redo Chart Edit',\n\t\t\tkeywords: ['chart', 'redo'],\n\t\t\tenabled: () => controller.getState().canRedo || 'Nothing to redo',\n\t\t\trun: () => ({ redone: controller.redo() })\n\t\t}\n\t];\n}\n","// Drag behaviour follows effectcraft-main/crates/ui-egui/src/panels/graph.rs and graph_tools.rs (the value axis\n// is frozen while a key is dragged, Shift locks to the axis that moved most, `snap_px` picks the nearest\n// candidate within a few screen pixels) and lightcraft-main's curve tests (Alt moves a tenth as far)\n// (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport type { ChartController } from './controller.js';\nimport { chartValueAtPoint, chartXAtPoint, snapChartValue } from './layout.js';\nimport { linearMap } from './scale.js';\nimport { chartFamily } from './spec.js';\nimport type { ChartScene, ChartSelection, ChartValueScale } from './types.js';\n\n/** Scene coordinates of a pointer, given the rendered element's box (the scene is scaled to fit it). */\nexport function chartClientToScene(scene: Pick<ChartScene, 'width' | 'height'>, box: { left: number; top: number; width: number; height: number }, clientX: number, clientY: number): { x: number; y: number } {\n\tconst sx = box.width ? scene.width / box.width : 1;\n\tconst sy = box.height ? scene.height / box.height : 1;\n\treturn { x: (clientX - box.left) * sx, y: (clientY - box.top) * sy };\n}\n\n/**\n * Whether a point can be dragged to a new value in this scene: bar, line, area and scatter\n * charts (not percent-stacked), scatter and bubble charts with x values (x and y), and\n * waterfall steps. Hidden series and gaps cannot be dragged.\n */\nexport function canDragChartPoint(controller: ChartController, scene: ChartScene, target: ChartSelection | undefined): target is Extract<ChartSelection, { kind: 'point' }> {\n\tif (target?.kind !== 'point' || !scene.valueScale || scene.percent) return false;\n\tconst spec = controller.getSpec();\n\tconst family = chartFamily(spec);\n\tif (family !== 'cartesian' && family !== 'xy' && family !== 'waterfall') return false;\n\tconst series = controller.getSeries(target.seriesId);\n\treturn !!series && !series.hidden && series.values[target.index] !== null;\n}\n\nexport interface ChartDragMoveOptions {\n\t/** Move a tenth as far as the pointer (fine adjustment; Alt). */\n\tfine?: boolean;\n\t/** Only change the axis the pointer has moved along most (scatter charts; Shift). */\n\tlockAxis?: boolean;\n\t/** Skip snapping to nearby values and ticks (e.g. while Ctrl / Cmd is held). */\n\tnoSnap?: boolean;\n}\n\nexport interface ChartPointDrag {\n\t/**\n\t * The value axis range when the drag started. Pass it to `layoutChart` (`valueDomain`)\n\t * until `end()` so the axis does not rescale under the pointer.\n\t */\n\treadonly valueDomain: { min: number; max: number };\n\t/** The secondary value axis range when the drag started (`layoutChart`'s `valueDomain2`). */\n\treadonly valueDomain2?: { min: number; max: number };\n\t/** The numeric x range of a scatter or bubble chart when the drag started (`xDomain`). */\n\treadonly xDomain?: { min: number; max: number };\n\t/** The point being dragged, for `layoutChart`'s `readout`. */\n\treadonly target: { seriesId: string; index: number };\n\t/** Moves the value with the pointer (scene coordinates). */\n\tmove(point: { x: number; y: number }, options?: ChartDragMoveOptions): void;\n\t/** Ends the drag (one undo step for the whole drag). */\n\tend(): void;\n\t/** Cancels the drag: the value goes back and no undo step is left (Escape). */\n\tcancel(): void;\n}\n\nexport interface ChartSnapOptions {\n\t/** Values to snap to when the pointer is within `tolerancePx` of them. */\n\tcandidates?: readonly number[];\n\t/** Screen distance that snaps (default 6). */\n\ttolerancePx?: number;\n\t/** Fallback step when no candidate is close (default: a tenth of the tick step). */\n\tstep?: number;\n\t/** The scale the value is on (default: the scene's value scale). */\n\tscale?: ChartValueScale;\n}\n\n/**\n * Snaps a dragged value: to the nearest candidate (other series at the same category, the\n * neighbouring values, zero, the start value, ticks) within `tolerancePx` screen pixels, or\n * else to a tenth of the tick step.\n */\nexport function snapChartDragValue(scene: ChartScene, value: number, options: ChartSnapOptions = {}): number {\n\tconst scale = options.scale ?? scene.valueScale;\n\tconst tolerance = options.tolerancePx ?? 6;\n\tif (scale) {\n\t\tconst px = (v: number) => linearMap(v, scale.domain, scale.range);\n\t\tconst at = px(value);\n\t\tlet best: number | null = null;\n\t\tlet bestDist = tolerance;\n\t\tfor (const c of [...(options.candidates ?? []), ...scale.ticks]) {\n\t\t\tif (!Number.isFinite(c)) continue;\n\t\t\tconst d = Math.abs(px(c) - at);\n\t\t\tif (d <= bestDist) {\n\t\t\t\tbest = c;\n\t\t\t\tbestDist = d;\n\t\t\t}\n\t\t}\n\t\tif (best !== null) return best;\n\t}\n\treturn snapChartValue(scene, value, options.step, scale?.ticks);\n}\n\n/**\n * Starts dragging a bar or point: the value follows the pointer along its value axis (and\n * along x on scatter and bubble charts), snapped to nearby values and then to a tenth of the\n * tick step (`step` overrides), and the whole drag is one undo step. Works for stacked bars\n * too (the drag changes the segment by the distance moved). Returns `null` when the target\n * cannot be dragged.\n */\nexport function startChartPointDrag(controller: ChartController, scene: ChartScene, target: ChartSelection | undefined, start: { x: number; y: number }, options: { step?: number; tolerancePx?: number } = {}): ChartPointDrag | null {\n\tif (!canDragChartPoint(controller, scene, target)) return null;\n\tconst { seriesId, index } = target;\n\tconst spec = controller.getSpec();\n\tconst series = controller.getSeries(seriesId)!;\n\tconst secondary = series.axis === 'secondary' && !!scene.valueScale2;\n\tconst scale = secondary ? scene.valueScale2! : scene.valueScale!;\n\tconst xy = chartFamily(spec) === 'xy' && !!scene.xScale;\n\tconst startValue = series.values[index] ?? 0;\n\tconst startX = series.x?.[index] ?? null;\n\tconst startAt = chartValueAtPoint(scene, start, secondary);\n\tconst startAtX = xy ? chartXAtPoint(scene, start) : undefined;\n\tif (startAt === undefined) return null;\n\t// Nearby values worth snapping to: zero, where the drag started, other series at this\n\t// category and this series' neighbours.\n\tconst candidates = [0, startValue];\n\tif (!xy) {\n\t\tfor (const s of spec.series) if (s.id !== seriesId && !s.hidden && (s.axis === 'secondary') === secondary) candidates.push(s.values[index] ?? NaN);\n\t\tcandidates.push(series.values[index - 1] ?? NaN, series.values[index + 1] ?? NaN);\n\t}\n\tcontroller.beginGesture(`drag:${seriesId}:${index}`);\n\tlet ended = false;\n\tconst [min, max] = scene.valueScale!.domain;\n\tconst label = `Drag ${series.name}`;\n\treturn {\n\t\tvalueDomain: { min, max },\n\t\t...(scene.valueScale2 ? { valueDomain2: { min: scene.valueScale2.domain[0], max: scene.valueScale2.domain[1] } } : {}),\n\t\t...(xy ? { xDomain: { min: scene.xScale!.domain[0], max: scene.xScale!.domain[1] } } : {}),\n\t\ttarget: { seriesId, index },\n\t\tmove(point, moveOptions = {}) {\n\t\t\tif (ended) return;\n\t\t\tconst at = chartValueAtPoint(scene, point, secondary);\n\t\t\tif (at === undefined) return;\n\t\t\tconst factor = moveOptions.fine ? 0.1 : 1;\n\t\t\tlet dy = (at - startAt) * factor;\n\t\t\tlet dx = 0;\n\t\t\tif (xy && startX !== null && startAtX !== undefined) {\n\t\t\t\tconst atX = chartXAtPoint(scene, point);\n\t\t\t\tif (atX !== undefined) dx = (atX - startAtX) * factor;\n\t\t\t\tif (moveOptions.lockAxis) {\n\t\t\t\t\t// Keep the axis the pointer moved further along (in pixels).\n\t\t\t\t\tif (Math.abs(point.x - start.x) >= Math.abs(point.y - start.y)) dy = 0;\n\t\t\t\t\telse dx = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst snap = (v: number, s: ChartValueScale, c: readonly number[]) => {\n\t\t\t\tif (moveOptions.noSnap) return Number(v.toPrecision(12));\n\t\t\t\tif (moveOptions.fine) {\n\t\t\t\t\tconst unit = options.step ? options.step / 10 : s.ticks.length > 1 ? (s.ticks[1] - s.ticks[0]) / 100 : undefined;\n\t\t\t\t\treturn snapChartValue(scene, v, unit, s.ticks);\n\t\t\t\t}\n\t\t\t\treturn snapChartDragValue(scene, v, { candidates: c, tolerancePx: options.tolerancePx, step: options.step, scale: s });\n\t\t\t};\n\t\t\tconst y = snap(startValue + dy, scale, candidates);\n\t\t\tif (xy && startX !== null) {\n\t\t\t\tconst x = dx !== 0 ? snap(startX + dx, scene.xScale!, [0, startX]) : startX;\n\t\t\t\tconst xs = [...(series.x ?? [])];\n\t\t\t\txs[index] = x;\n\t\t\t\tcontroller.setValue(seriesId, index, y, { label });\n\t\t\t\tif (x !== controller.getSeries(seriesId)?.x?.[index]) controller.updateSeries(seriesId, { x: xs });\n\t\t\t} else controller.setValue(seriesId, index, y, { label });\n\t\t},\n\t\tend() {\n\t\t\tif (ended) return;\n\t\t\tended = true;\n\t\t\tcontroller.endGesture();\n\t\t},\n\t\tcancel() {\n\t\t\tif (ended) return;\n\t\t\tended = true;\n\t\t\tcontroller.cancelGesture();\n\t\t}\n\t};\n}\n\nexport interface ChartKeyInput {\n\tkey: string;\n\tshiftKey?: boolean;\n\taltKey?: boolean;\n\tmetaKey?: boolean;\n\tctrlKey?: boolean;\n}\n\n/**\n * Keyboard editing on a focused chart: arrows move a point selection between categories\n * (← →) and change its value (↑ ↓, a tenth of the tick step; Shift: a whole step; Alt: a\n * hundredth), Delete / Backspace deletes the selection, Escape cancels a drag or clears the\n * selection. Returns `true` when the key was used (call `preventDefault`).\n */\nexport function handleChartKey(controller: ChartController, scene: ChartScene | null, event: ChartKeyInput): boolean {\n\tif (event.metaKey || event.ctrlKey) return false;\n\tconst { selection, spec, gesture } = controller.getState();\n\tswitch (event.key) {\n\t\tcase 'Escape':\n\t\t\tif (gesture) {\n\t\t\t\tcontroller.cancelGesture();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (!selection) return false;\n\t\t\tcontroller.select(null);\n\t\t\treturn true;\n\t\tcase 'Delete':\n\t\tcase 'Backspace':\n\t\t\tif (event.altKey || !selection || selection.kind === 'chart') return false;\n\t\t\tcontroller.deleteSelection();\n\t\t\treturn true;\n\t\tcase 'ArrowLeft':\n\t\tcase 'ArrowRight': {\n\t\t\tif (event.altKey || (selection?.kind !== 'point' && selection?.kind !== 'category')) return false;\n\t\t\tconst n = spec.categories.length;\n\t\t\tconst index = Math.max(0, Math.min(n - 1, selection.index + (event.key === 'ArrowRight' ? 1 : -1)));\n\t\t\tcontroller.select({ ...selection, index });\n\t\t\treturn true;\n\t\t}\n\t\tcase 'ArrowUp':\n\t\tcase 'ArrowDown': {\n\t\t\tif (selection?.kind !== 'point' || scene?.percent) return false;\n\t\t\tconst secondary = controller.getSeries(selection.seriesId)?.axis === 'secondary';\n\t\t\tconst ticks = (secondary ? scene?.valueScale2 : null)?.ticks ?? scene?.valueScale?.ticks ?? [];\n\t\t\tconst step = ticks.length > 1 ? ticks[1] - ticks[0] : 1;\n\t\t\tconst amount = event.shiftKey ? step : event.altKey ? step / 100 : step / 10;\n\t\t\tcontroller.nudgeValue(selection.seriesId, selection.index, amount * (event.key === 'ArrowUp' ? 1 : -1));\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** A short description of the selection for an inspector heading or a screen reader. */\nexport function describeChartSelection(controller: ChartController, selection: ChartSelection | null = controller.getState().selection): string {\n\tif (!selection) return 'Nothing selected';\n\tconst spec = controller.getSpec();\n\tswitch (selection.kind) {\n\t\tcase 'chart':\n\t\t\treturn 'Chart';\n\t\tcase 'title':\n\t\t\treturn 'Title';\n\t\tcase 'subtitle':\n\t\t\treturn 'Subtitle';\n\t\tcase 'legend':\n\t\t\treturn 'Legend';\n\t\tcase 'axis':\n\t\t\treturn selection.axis === 'x' ? (chartFamily(spec) === 'xy' ? 'X axis' : 'Category axis') : selection.axis === 'y' ? 'Value axis' : 'Secondary value axis';\n\t\tcase 'series':\n\t\t\treturn `Series \"${controller.getSeries(selection.seriesId)?.name ?? selection.seriesId}\"`;\n\t\tcase 'category':\n\t\t\treturn `Category \"${spec.categories[selection.index] ?? selection.index}\"`;\n\t\tcase 'trendline': {\n\t\t\tconst series = controller.getSeries(selection.seriesId);\n\t\t\tconst line = series?.trendlines?.[selection.index];\n\t\t\treturn `${line ? line.type.replace('-', ' ') : 'Trendline'} trendline on \"${series?.name ?? selection.seriesId}\"`;\n\t\t}\n\t\tcase 'point': {\n\t\t\tconst series = controller.getSeries(selection.seriesId);\n\t\t\tconst value = series?.values[selection.index];\n\t\t\tconst x = series?.x?.[selection.index];\n\t\t\tif (x !== undefined && x !== null && chartFamily(spec) === 'xy') return `${series?.name ?? selection.seriesId}: (${x}, ${value ?? 'blank'})`;\n\t\t\treturn `${series?.name ?? selection.seriesId} · ${spec.categories[selection.index] ?? selection.index}: ${value ?? 'blank'}`;\n\t\t}\n\t}\n}\n\n/**\n * The mark under a scene point (topmost first), for hosts without DOM events and for agents\n * that drive the pointer: rects, circles, lines (within 4 px) and text boxes. Returns the\n * mark's `target`, or `{ kind: 'chart' }` over the background, or `null` outside.\n */\nexport function chartHitTest(scene: ChartScene, point: { x: number; y: number }, measure: (text: string, size: number, weight?: number) => number = (t, s, w = 400) => t.length * s * (w >= 600 ? 0.6 : 0.56)): ChartSelection | null {\n\tfor (let i = scene.marks.length - 1; i >= 0; i--) {\n\t\tconst m = scene.marks[i];\n\t\tif (!m.target || m.role === 'selection' || m.role === 'background') continue;\n\t\tlet hit = false;\n\t\tswitch (m.kind) {\n\t\t\tcase 'rect':\n\t\t\t\thit = point.x >= m.x && point.x <= m.x + m.width && point.y >= m.y && point.y <= m.y + m.height;\n\t\t\t\tbreak;\n\t\t\tcase 'circle':\n\t\t\t\thit = Math.hypot(point.x - m.cx, point.y - m.cy) <= Math.max(m.r, 4) + 2;\n\t\t\t\tbreak;\n\t\t\tcase 'line': {\n\t\t\t\tconst dx = m.x2 - m.x1;\n\t\t\t\tconst dy = m.y2 - m.y1;\n\t\t\t\tconst len2 = dx * dx + dy * dy;\n\t\t\t\tconst t = len2 ? Math.max(0, Math.min(1, ((point.x - m.x1) * dx + (point.y - m.y1) * dy) / len2)) : 0;\n\t\t\t\thit = Math.hypot(point.x - (m.x1 + t * dx), point.y - (m.y1 + t * dy)) <= 4;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'text': {\n\t\t\t\tif (m.rotate) break;\n\t\t\t\tconst w = measure(m.text, m.size, m.weight);\n\t\t\t\tconst x0 = m.anchor === 'start' ? m.x : m.anchor === 'end' ? m.x - w : m.x - w / 2;\n\t\t\t\tconst y0 = m.baseline === 'top' ? m.y : m.baseline === 'bottom' ? m.y - m.size : m.y - m.size / 2;\n\t\t\t\thit = point.x >= x0 - 2 && point.x <= x0 + w + 2 && point.y >= y0 - 2 && point.y <= y0 + m.size + 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\tif (hit) return m.target;\n\t}\n\treturn point.x >= 0 && point.y >= 0 && point.x <= scene.width && point.y <= scene.height ? { kind: 'chart' } : null;\n}\n","// The render-preview, pointer-gesture and key tools follow the conventions of the craft apps' MCP servers\n// (vectorcraft-main/crates/mcp/src/tools.rs `render_preview`, lightcraft-main `pointer_gesture`,\n// designcraft-main `key`) (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport type { AgentTool, AgentToolProvider } from '../tools/registry.js';\nimport type { JsonSchema } from '../tools/schema.js';\nimport { parseCsv } from '../spreadsheet/csv.js';\nimport { checkChartColors } from './color.js';\nimport type { ChartController, ChartSeriesPatch, ChartSpecPatch } from './controller.js';\nimport { chartHitTest, handleChartKey, startChartPointDrag } from './interaction.js';\nimport { layoutChart } from './layout.js';\nimport { chartFromMermaid, chartToMermaid } from './mermaid.js';\nimport { chartFromOoxml, chartToOoxml } from './ooxml.js';\nimport type { ChartDirector, ChartDirectorActor } from './presence.js';\nimport { CHART_COLOR_SCHEMES, CHART_LAYOUT_PRESETS } from './presets.js';\nimport { chartFromTable, recommendChartTypes } from './recommend.js';\nimport {\n\tparseChartValue,\n\tCHART_AXIS_KINDS,\n\tCHART_CURVES,\n\tCHART_LABEL_POSITIONS,\n\tCHART_LEGEND_POSITIONS,\n\tCHART_MARKERS,\n\tCHART_NUMBER_STYLES,\n\tCHART_ORIENTATIONS,\n\tCHART_SERIES_TYPES,\n\tCHART_STACKINGS,\n\tCHART_TRENDLINE_TYPES,\n\tCHART_TYPES,\n\tchartColorsByCategory,\n\tchartDataToTable,\n\tchartSeriesColor,\n\tchartSliceColor\n} from './spec.js';\nimport { AXIS, CATEGORY_REF, CHART_UPDATE_PROPERTIES, FORMAT, HEIGHT, SERIES_PROPS, SERIES_REF, TRENDLINE_PROPS, VALUE, WIDTH } from './schemas.js';\nimport { summarizeChart } from './summary.js';\nimport { chartToSvg } from './svg.js';\nimport type { ChartSelection, ChartTrendline } from './types.js';\n\ntype ParserCtor = { new (): DOMParser };\n\nexport interface ChartToolProviderOptions {\n\t/** Provider id (unique per registry). Default `chart`. */\n\tid?: string;\n\t/** Always prefix tool names with `<namespace>__`. */\n\tnamespace?: string;\n\t/**\n\t * The chart cannot be edited: write tools are hidden and `get_chart` says why. A string\n\t * is the reason (\"The report is locked\").\n\t */\n\treadOnly?: boolean | string | (() => boolean | string);\n\t/** Size used for summaries, previews and pointer gestures (default 640 × 400). */\n\tsize?: { width: number; height: number };\n\t/** Enables `import_chart_ooxml` (reading Office chart XML needs a DOMParser). Default: the global one, if any. */\n\tDOMParser?: ParserCtor;\n\t/**\n\t * Acts out `set_chart_values` and `select_chart_element` with a visible cursor (see\n\t * `ChartDirector`); each call is still one undo step. Without it, edits apply at once.\n\t */\n\tdirector?: ChartDirector;\n\t/** Who the cursor belongs to (default `{ id: 'agent', name: 'Agent' }`). */\n\tactor?: ChartDirectorActor;\n\t/** Turns SVG into an image so `render_chart` can return PNG (e.g. through a canvas). */\n\trasterize?: (svg: string, size: { width: number; height: number }) => Promise<{ data: string; mimeType: string }> | { data: string; mimeType: string };\n}\n\nconst READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;\nconst WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } as const;\nconst WRITE_IDEMPOTENT = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;\nconst DESTRUCTIVE = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false } as const;\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nfunction resolve<T>(result: { ok: boolean; message?: string } & T): T {\n\tif (!result.ok) fail(result.message ?? 'The change was rejected.');\n\treturn result;\n}\n\n/**\n * Agent tools for a chart editor, for a `ToolRegistry`: one tool per operation with strict\n * schemas. Reads (`get_chart`, `render_chart`, `check_chart_colors`, `recommend_chart`,\n * `get_chart_trendline`, `list_chart_presets`, `export_chart_mermaid`, `export_chart_ooxml`)\n * are always there; writes (data, series, categories, presentation, trendlines, presets,\n * imports, selection, pointer and key input, undo / redo) are hidden while the chart is\n * read-only. Every write is one undo step and returns what it changed.\n */\nexport function createChartToolProvider(controller: ChartController, options: ChartToolProviderOptions = {}): AgentToolProvider {\n\tconst size = options.size ?? { width: 640, height: 400 };\n\tconst readOnlyReason = (): string | null => {\n\t\tconst r = typeof options.readOnly === 'function' ? options.readOnly() : options.readOnly;\n\t\tif (!r) return null;\n\t\treturn typeof r === 'string' ? r : 'This chart is read-only.';\n\t};\n\tconst spec = () => controller.getSpec();\n\tconst seriesById = (ref: string) => {\n\t\tconst s = spec().series.find((x) => x.id === ref) ?? spec().series.find((x) => x.name === ref);\n\t\tif (!s) fail(`There is no series \"${ref}\"; expected one of ${spec().series.map((x) => `\"${x.id}\" (${x.name})`).join(', ') || '(none yet; add one with add_chart_series)'}.`);\n\t\treturn s!;\n\t};\n\tconst categoryIndex = (ref: string | number) => {\n\t\tconst categories = spec().categories;\n\t\tconst index = typeof ref === 'number' ? ref : categories.indexOf(ref);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= categories.length)\n\t\t\tfail(`There is no category ${JSON.stringify(ref)}; expected an index from 0 to ${categories.length - 1} or one of ${categories.slice(0, 20).map((c) => JSON.stringify(c)).join(', ')}.`);\n\t\treturn index;\n\t};\n\tconst table = () => chartDataToTable(spec());\n\tconst Parser = (): ParserCtor | undefined => options.DOMParser ?? (globalThis as { DOMParser?: ParserCtor }).DOMParser;\n\n\tconst getChart: AgentTool = {\n\t\tname: 'get_chart',\n\t\ttitle: 'Read the chart',\n\t\tdescription:\n\t\t\t'Returns the chart spec (type, titles, axes, legend, series with ids and settings), its data as a table (header row of series names, then one row per category), the current selection, and a summary at the given size: per-series min / max / mean / trend, the axes as drawn, layout warnings (hidden labels, thinned lines), a colour check and a plain-language description. Use the series ids and category indexes it returns with the write tools.',\n\t\tinputSchema: { type: 'object', properties: { width: WIDTH, height: HEIGHT }, additionalProperties: false },\n\t\tannotations: { title: 'Read the chart', ...READ },\n\t\thandler: ({ width = size.width, height = size.height }) => {\n\t\t\tconst reason = readOnlyReason();\n\t\t\treturn {\n\t\t\t\tspec: controller.toJSON(),\n\t\t\t\ttable: table(),\n\t\t\t\tselection: controller.getState().selection,\n\t\t\t\tsummary: summarizeChart(controller.toJSON(), { width, height }),\n\t\t\t\tissues: controller.getState().issues,\n\t\t\t\t...(reason ? { readOnly: reason } : {})\n\t\t\t};\n\t\t}\n\t};\n\n\tconst renderChart: AgentTool = {\n\t\tname: 'render_chart',\n\t\ttitle: 'Render the chart',\n\t\tdescription:\n\t\t\t'Draws the chart without changing it, to check it visually: SVG text by default, or a PNG image (format \"png\") when the host can rasterize. Look for overlapping or hidden labels; get_chart lists layout warnings without a render.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { width: WIDTH, height: HEIGHT, format: { type: 'string', enum: ['svg', 'png'], description: 'svg (default) or png (only when the host supports it).' } },\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Render the chart', ...READ },\n\t\thandler: async ({ width = size.width, height = size.height, format = 'svg' }) => {\n\t\t\tconst svg = chartToSvg(controller.toJSON(), { width, height });\n\t\t\tif (format === 'png') {\n\t\t\t\tif (!options.rasterize) fail('This host cannot rasterize charts; call render_chart with format \"svg\".');\n\t\t\t\tconst image = await options.rasterize!(svg, { width, height });\n\t\t\t\treturn { content: [{ type: 'image', data: image.data, mimeType: image.mimeType }], structuredContent: { width, height, mimeType: image.mimeType } };\n\t\t\t}\n\t\t\treturn { svg, width, height };\n\t\t}\n\t};\n\n\tconst checkColors: AgentTool = {\n\t\tname: 'check_chart_colors',\n\t\ttitle: 'Check chart colours',\n\t\tdescription:\n\t\t\t'Checks that colours can be told apart with normal vision and with protanopia, deuteranopia and tritanopia (OKLab distance after simulation), and that they stand out from the background. Checks the chart\\'s own series (or slice) colours unless colours are given. Returns the closest pair per vision, contrast ratios and problems as sentences.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcolors: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Colours to check instead of the chart\\'s (hex or rgb()).' },\n\t\t\t\tsurface: { type: 'string', description: 'Background colour (default white).' }\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Check chart colours', ...READ },\n\t\thandler: ({ colors, surface }) => {\n\t\t\tconst s = spec();\n\t\t\tconst visible = s.series.filter((x) => !x.hidden);\n\t\t\tconst own = chartColorsByCategory(s.type) ? s.categories.map((_, i) => visible[0]?.pointColors?.[i] || chartSliceColor(s, i)) : visible.map((x) => chartSeriesColor(s, s.series.indexOf(x)));\n\t\t\treturn { colors: colors ?? own, ...checkChartColors(colors ?? own, { surface }) };\n\t\t}\n\t};\n\n\tconst recommend: AgentTool = {\n\t\tname: 'recommend_chart',\n\t\ttitle: 'Recommend chart types',\n\t\tdescription:\n\t\t\t'Suggests chart types for data, best first, each with a reason: from CSV text when given, else from the chart\\'s current data. Uses the shape of the data (series count, points, dates, negative values).',\n\t\tinputSchema: { type: 'object', properties: { csv: { type: 'string', description: 'CSV or TSV text to analyse instead of the current data (first row may be series names, first column categories).' } }, additionalProperties: false },\n\t\tannotations: { title: 'Recommend chart types', ...READ },\n\t\thandler: ({ csv }) => {\n\t\t\tconst rows = csv !== undefined ? parseCsv(csv, { delimiter: csv.includes('\\t') ? '\\t' : ',' }) : table();\n\t\t\tconst recommendations = recommendChartTypes(rows);\n\t\t\tif (!recommendations.length) fail('There are no numbers to chart: give CSV with at least one numeric column.');\n\t\t\treturn { recommendations };\n\t\t}\n\t};\n\n\tconst getTrendline: AgentTool = {\n\t\tname: 'get_chart_trendline',\n\t\ttitle: 'Read a trendline fit',\n\t\tdescription: 'Returns a trendline\\'s fitted coefficients (in x for category charts, x = 1, 2, 3, …), R², equation and the number of points, or the moving-average points.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { series: SERIES_REF, index: { type: 'integer', minimum: 0, description: 'Trendline index on the series (0 = first).' } },\n\t\t\trequired: ['series', 'index'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Read a trendline fit', ...READ },\n\t\thandler: ({ series, index }) => {\n\t\t\tconst s = seriesById(series);\n\t\t\tconst line = s.trendlines?.[index];\n\t\t\tif (!line) fail(`\"${s.name}\" has no trendline ${index}; it has ${s.trendlines?.length ?? 0}.`);\n\t\t\tif (line!.type === 'moving-average') return { trendline: line, points: controller.trendlineMovingAverage(s.id, index) };\n\t\t\tconst fit = controller.trendlineFit(s.id, index);\n\t\t\tif (!fit) fail(`The ${line!.type} trendline on \"${s.name}\" cannot be fitted: it needs more points (and positive values for log, exponential and power fits).`);\n\t\t\treturn { trendline: line, coefficients: fit!.coefficients, r2: fit!.r2, equation: fit!.equation, points: fit!.points };\n\t\t}\n\t};\n\n\tconst listPresets: AgentTool = {\n\t\tname: 'list_chart_presets',\n\t\ttitle: 'List chart presets',\n\t\tdescription: 'Lists the quick layouts and colour schemes apply_chart_preset accepts, with what each changes.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'List chart presets', ...READ },\n\t\thandler: () => ({\n\t\t\tlayouts: CHART_LAYOUT_PRESETS.map(({ id, label, description }) => ({ id, label, description })),\n\t\t\tcolorSchemes: CHART_COLOR_SCHEMES.map(({ id, label, description, palette }) => ({ id, label, description, palette }))\n\t\t})\n\t};\n\n\tconst exportMermaid: AgentTool = {\n\t\tname: 'export_chart_mermaid',\n\t\ttitle: 'Export chart as Mermaid',\n\t\tdescription:\n\t\t\t'Returns the chart as Mermaid text (xychart-beta, pie or radar-beta) for Markdown or chat. With meta (default true) one \"%% @pixerate {…}\" comment keeps what Mermaid cannot express, so import_chart_mermaid gets the chart back exactly.',\n\t\tinputSchema: { type: 'object', properties: { meta: { type: 'boolean', description: 'Include the round-trip comment (default true).' } }, additionalProperties: false },\n\t\tannotations: { title: 'Export chart as Mermaid', ...READ },\n\t\thandler: ({ meta = true }) => ({ mermaid: chartToMermaid(controller.toJSON(), { meta }) })\n\t};\n\n\tconst exportOoxml: AgentTool = {\n\t\tname: 'export_chart_ooxml',\n\t\ttitle: 'Export chart as Office XML',\n\t\tdescription: 'Returns the chart as a DrawingML chart part (c:chartSpace) for Word or PowerPoint files, with what could not be written as sentences.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Export chart as Office XML', ...READ },\n\t\thandler: () => chartToOoxml(controller.toJSON())\n\t};\n\n\t// ---------------------------------------------------------------- writes\n\n\tconst updateChart: AgentTool = {\n\t\tname: 'update_chart',\n\t\ttitle: 'Change chart presentation',\n\t\tdescription:\n\t\t\t'Changes how the chart looks, as one undo step: type, titles, axes (xAxis = categories or numeric x, yAxis = values, yAxis2 = secondary values), legend, stacking, orientation, curve, points, data labels and their position, palette, donut hole, bar spacing, histogram bins, waterfall total. All-or-nothing: invalid values change nothing and come back as sentences. Returns the new spec.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: CHART_UPDATE_PROPERTIES,\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Change chart presentation', ...WRITE_IDEMPOTENT },\n\t\thandler: (args) => {\n\t\t\tif (!Object.keys(args).length) fail('Nothing to change: pass at least one field, e.g. {\"type\": \"line\"}.');\n\t\t\tresolve(controller.update(args as ChartSpecPatch));\n\t\t\treturn { spec: controller.toJSON() };\n\t\t}\n\t};\n\n\tconst setData: AgentTool = {\n\t\tname: 'set_chart_data',\n\t\ttitle: 'Replace chart data',\n\t\tdescription: 'Replaces the categories and / or the series as one undo step. Each series has one value per category (padded with gaps). Returns the data table and the series ids.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcategories: { type: 'array', items: { type: 'string' }, description: 'Category labels in order.' },\n\t\t\t\tseries: {\n\t\t\t\t\ttype: 'array',\n\t\t\t\t\tdescription: 'The new series (replaces all).',\n\t\t\t\t\titems: { type: 'object', properties: { id: { type: 'string', description: 'Stable id (optional).' }, ...SERIES_PROPS }, required: ['name', 'values'], additionalProperties: false }\n\t\t\t\t}\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Replace chart data', ...DESTRUCTIVE },\n\t\thandler: (args) => {\n\t\t\tif (!args.categories && !args.series) fail('Pass categories, series or both.');\n\t\t\tresolve(controller.setData(args as any));\n\t\t\treturn { table: table(), series: spec().series.map((s) => ({ id: s.id, name: s.name })) };\n\t\t}\n\t};\n\n\tconst setValues: AgentTool = {\n\t\tname: 'set_chart_values',\n\t\ttitle: 'Set chart values',\n\t\tdescription: 'Sets individual values as one undo step (all-or-nothing). Series by id or name, category by index or label. Returns the values as stored.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcells: {\n\t\t\t\t\ttype: 'array',\n\t\t\t\t\tminItems: 1,\n\t\t\t\t\tdescription: 'Values to set.',\n\t\t\t\t\titems: { type: 'object', properties: { series: SERIES_REF, category: CATEGORY_REF, value: VALUE }, required: ['series', 'category', 'value'], additionalProperties: false }\n\t\t\t\t}\n\t\t\t},\n\t\t\trequired: ['cells'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Set chart values', ...WRITE_IDEMPOTENT },\n\t\thandler: async ({ cells }) => {\n\t\t\tconst resolved = (cells as { series: string; category: string | number; value: unknown }[]).map((c) => ({ seriesId: seriesById(c.series).id, index: categoryIndex(c.category), value: c.value }));\n\t\t\tconst parsed = resolved.map((c) => parseChartValue(c.value));\n\t\t\tconst bad = resolved.find((_, i) => parsed[i] === undefined);\n\t\t\tif (bad) fail(`\"${String(bad.value)}\" is not a number; pass a number, numeric text or null for a gap. Nothing was changed.`);\n\t\t\tif (options.director && parsed.every((v) => typeof v === 'number')) {\n\t\t\t\tconst results = await options.director.perform(options.actor ?? { id: 'agent', name: 'Agent' }, resolved.map((c, i) => ({ kind: 'setValue' as const, seriesId: c.seriesId, index: c.index, value: parsed[i] as number })));\n\t\t\t\tconst failed = results.find((r) => !r.ok);\n\t\t\t\tif (failed && !failed.ok) fail(failed.message);\n\t\t\t} else resolve(controller.setValues(resolved));\n\t\t\treturn { cells: resolved.map((c) => ({ series: c.seriesId, category: spec().categories[c.index], index: c.index, value: controller.getSeries(c.seriesId)!.values[c.index] })) };\n\t\t}\n\t};\n\n\tconst addSeries: AgentTool = {\n\t\tname: 'add_chart_series',\n\t\ttitle: 'Add a series',\n\t\tdescription: 'Adds a series (values padded to the categories) and selects it. Returns its id and stored values.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { ...SERIES_PROPS, id: { type: 'string', description: 'Id to use (default: series-N).' }, at: { type: 'integer', minimum: 0, description: 'Position (default: last).' } },\n\t\t\trequired: ['name'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Add a series', ...WRITE },\n\t\thandler: ({ at, ...input }) => {\n\t\t\tconst clean = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== null));\n\t\t\tconst result = resolve(controller.addSeries(clean as any, { at })) as { id: string };\n\t\t\tconst s = controller.getSeries(result.id)!;\n\t\t\treturn { id: s.id, name: s.name, values: s.values };\n\t\t}\n\t};\n\n\tconst updateSeries: AgentTool = {\n\t\tname: 'update_chart_series',\n\t\ttitle: 'Change a series',\n\t\tdescription: 'Renames, recolours, hides, moves to the secondary axis or changes how a series is drawn (marker, curve, labels, format, x values, bubble sizes, point colours). null resets a field. Values change with set_chart_values. Returns the series.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { series: SERIES_REF, ...Object.fromEntries(Object.entries(SERIES_PROPS).filter(([k]) => k !== 'values')) },\n\t\t\trequired: ['series'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Change a series', ...WRITE_IDEMPOTENT },\n\t\thandler: ({ series, ...patch }) => {\n\t\t\tconst id = seriesById(series).id;\n\t\t\tif (!Object.keys(patch).length) fail('Nothing to change: pass a field such as {\"color\": \"#e8710a\"} or {\"axis\": \"secondary\"}.');\n\t\t\tresolve(controller.updateSeries(id, patch as ChartSeriesPatch));\n\t\t\treturn { series: controller.getSeries(id) };\n\t\t}\n\t};\n\n\tconst removeSeries: AgentTool = {\n\t\tname: 'remove_chart_series',\n\t\ttitle: 'Delete a series',\n\t\tdescription: 'Deletes a series and its values. Returns the remaining series ids.',\n\t\tinputSchema: { type: 'object', properties: { series: SERIES_REF }, required: ['series'], additionalProperties: false },\n\t\tannotations: { title: 'Delete a series', ...DESTRUCTIVE },\n\t\thandler: ({ series }) => {\n\t\t\tresolve(controller.removeSeries(seriesById(series).id));\n\t\t\treturn { series: spec().series.map((s) => ({ id: s.id, name: s.name })) };\n\t\t}\n\t};\n\n\tconst addCategory: AgentTool = {\n\t\tname: 'add_chart_category',\n\t\ttitle: 'Add a category',\n\t\tdescription: 'Inserts a category (a gap in every series) and returns its index.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { label: { type: 'string', description: 'Category label (default: its number).' }, at: { type: 'integer', minimum: 0, description: 'Index to insert at (default: the end).' } },\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Add a category', ...WRITE },\n\t\thandler: ({ label, at }) => {\n\t\t\tconst result = controller.addCategory(label, { at });\n\t\t\treturn { index: result.index, categories: spec().categories };\n\t\t}\n\t};\n\n\tconst removeCategory: AgentTool = {\n\t\tname: 'remove_chart_category',\n\t\ttitle: 'Delete a category',\n\t\tdescription: 'Deletes a category and its value in every series. Returns the remaining categories.',\n\t\tinputSchema: { type: 'object', properties: { category: CATEGORY_REF }, required: ['category'], additionalProperties: false },\n\t\tannotations: { title: 'Delete a category', ...DESTRUCTIVE },\n\t\thandler: ({ category }) => {\n\t\t\tresolve(controller.removeCategory(categoryIndex(category)));\n\t\t\treturn { categories: spec().categories };\n\t\t}\n\t};\n\n\tconst importCsv: AgentTool = {\n\t\tname: 'import_chart_csv',\n\t\ttitle: 'Import chart data from CSV',\n\t\tdescription:\n\t\t\t'Replaces the data with CSV or TSV text as one undo step. By default the first row holds series names and the first column categories (detected when \"auto\"). chartType \"auto\" also picks the recommended chart type (two unlabelled numeric columns become a scatter of x against y). Returns the data table, the chart type and cells that were not numbers.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcsv: { type: 'string', description: 'CSV or TSV text (tabs are detected).' },\n\t\t\t\tseriesIn: { type: 'string', enum: ['columns', 'rows'], description: 'Series run down columns (default) or along rows. Ignored with chartType \"auto\".' },\n\t\t\t\theader: { type: ['boolean', 'string'], enum: [true, false, 'auto'], description: 'The first row holds series names: true (default), false or \"auto\". Ignored with chartType \"auto\".' },\n\t\t\t\tchartType: { type: 'string', enum: ['keep', 'auto'], description: '\"keep\" (default) keeps the chart type; \"auto\" reads the table shape and picks a type.' }\n\t\t\t},\n\t\t\trequired: ['csv'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Import chart data from CSV', ...DESTRUCTIVE },\n\t\thandler: ({ csv, seriesIn, header, chartType = 'keep' }) => {\n\t\t\tif (chartType === 'auto') {\n\t\t\t\tconst rows = parseCsv(csv, { delimiter: csv.includes('\\t') ? '\\t' : ',' });\n\t\t\t\tconst built = chartFromTable(rows);\n\t\t\t\tif (!built.series.length || !built.categories.length) fail('There is no data to import: expected at least one row of numbers.');\n\t\t\t\tresolve(controller.update({ type: built.type, stacking: built.stacking, categories: built.categories, series: built.series }, { label: 'Import data' }));\n\t\t\t\treturn { type: built.type, table: table(), issues: built.issues };\n\t\t\t}\n\t\t\tconst result = resolve(controller.importCsv(csv, { seriesIn, header })) as { issues?: unknown[] };\n\t\t\treturn { type: spec().type, table: table(), issues: result.issues ?? [] };\n\t\t}\n\t};\n\n\tconst importMermaid: AgentTool = {\n\t\tname: 'import_chart_mermaid',\n\t\ttitle: 'Import a Mermaid chart',\n\t\tdescription:\n\t\t\t'Replaces the chart with Mermaid xychart-beta, pie or radar-beta text as one undo step (a \"%% @pixerate\" comment from export_chart_mermaid restores everything else). Lines that cannot be read are skipped and listed with their line numbers. Returns the spec.',\n\t\tinputSchema: { type: 'object', properties: { mermaid: { type: 'string', description: 'Mermaid text, optionally inside a ```mermaid fence.' } }, required: ['mermaid'], additionalProperties: false },\n\t\tannotations: { title: 'Import a Mermaid chart', ...DESTRUCTIVE },\n\t\thandler: ({ mermaid }) => {\n\t\t\tconst fenced = /```(?:mermaid)?\\s*\\n([\\s\\S]*?)```/.exec(mermaid);\n\t\t\tconst read = chartFromMermaid(fenced ? fenced[1] : mermaid);\n\t\t\tif (!read.family) fail(read.issues.map((i) => i.message).join(' ') || 'Expected Mermaid starting with xychart-beta, pie or radar-beta.');\n\t\t\tresolve(controller.update({ ...read.spec } as ChartSpecPatch, { label: 'Import Mermaid chart' }));\n\t\t\treturn { spec: controller.toJSON(), issues: read.issues };\n\t\t}\n\t};\n\n\tconst importOoxml: AgentTool = {\n\t\tname: 'import_chart_ooxml',\n\t\ttitle: 'Import an Office chart',\n\t\tdescription:\n\t\t\t'Replaces the chart with an Office chart part (DrawingML c:chartSpace, or chartex for waterfall, funnel, treemap, histogram and box charts) as one undo step. Returns the spec, problems, and the features the editor cannot hold.',\n\t\tinputSchema: { type: 'object', properties: { xml: { type: 'string', description: 'The chart part XML, e.g. word/charts/chart1.xml.' } }, required: ['xml'], additionalProperties: false },\n\t\tannotations: { title: 'Import an Office chart', ...DESTRUCTIVE },\n\t\thandler: ({ xml }) => {\n\t\t\tconst read = chartFromOoxml(xml, { DOMParser: Parser() });\n\t\t\tif (read.issues.some((i) => i.path === '' || i.path === 'plotArea')) fail(read.issues.map((i) => i.message).join(' '));\n\t\t\tresolve(controller.update({ ...read.spec } as ChartSpecPatch, { label: 'Import Office chart' }));\n\t\t\treturn { spec: controller.toJSON(), issues: read.issues.map((i) => i.message), unsupported: read.unsupported, lossless: read.lossless };\n\t\t}\n\t};\n\n\tconst addTrendline: AgentTool = {\n\t\tname: 'add_chart_trendline',\n\t\ttitle: 'Add a trendline',\n\t\tdescription: 'Fits a trendline to a series and draws it (unstacked bar, line, area, scatter and bubble charts). Returns its index and the fit: coefficients, R² and equation.',\n\t\tinputSchema: { type: 'object', properties: { series: SERIES_REF, ...TRENDLINE_PROPS }, required: ['series', 'type'], additionalProperties: false },\n\t\tannotations: { title: 'Add a trendline', ...WRITE },\n\t\thandler: ({ series, ...line }) => {\n\t\t\tconst s = seriesById(series);\n\t\t\tconst result = resolve(controller.addTrendline(s.id, line as ChartTrendline)) as { index: number; fit: ReturnType<ChartController['trendlineFit']> };\n\t\t\treturn { series: s.id, index: result.index, ...(result.fit ? { coefficients: result.fit.coefficients, r2: result.fit.r2, equation: result.fit.equation } : {}) };\n\t\t}\n\t};\n\n\tconst removeTrendline: AgentTool = {\n\t\tname: 'remove_chart_trendline',\n\t\ttitle: 'Delete a trendline',\n\t\tdescription: 'Deletes a trendline from a series. Returns the series\\' remaining trendlines.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { series: SERIES_REF, index: { type: 'integer', minimum: 0, description: 'Trendline index on the series (0 = first).' } },\n\t\t\trequired: ['series', 'index'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Delete a trendline', ...DESTRUCTIVE },\n\t\thandler: ({ series, index }) => {\n\t\t\tconst s = seriesById(series);\n\t\t\tresolve(controller.removeTrendline(s.id, index));\n\t\t\treturn { series: s.id, trendlines: controller.getSeries(s.id)?.trendlines ?? [] };\n\t\t}\n\t};\n\n\tconst applyPreset: AgentTool = {\n\t\tname: 'apply_chart_preset',\n\t\ttitle: 'Apply a chart style',\n\t\tdescription: 'Applies a quick layout (legend, labels and grid lines together) and / or a colour scheme as one undo step. See list_chart_presets for the names. Returns the new spec.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tlayout: { type: 'string', enum: CHART_LAYOUT_PRESETS.map((p) => p.id), description: 'Quick layout id.' },\n\t\t\t\tcolors: { type: 'string', enum: CHART_COLOR_SCHEMES.map((p) => p.id), description: 'Colour scheme id.' }\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Apply a chart style', ...WRITE_IDEMPOTENT },\n\t\thandler: ({ layout, colors }) => {\n\t\t\tresolve(controller.applyPreset({ layout, colors }));\n\t\t\treturn { spec: controller.toJSON() };\n\t\t}\n\t};\n\n\tconst transpose: AgentTool = {\n\t\tname: 'transpose_chart',\n\t\ttitle: 'Switch rows and columns',\n\t\tdescription: 'Swaps series and categories (each category becomes a series) as one undo step. Per-series colours and settings are dropped. Returns the data table.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Switch rows and columns', ...WRITE },\n\t\thandler: () => {\n\t\t\tresolve(controller.transpose());\n\t\t\treturn { table: table(), series: spec().series.map((s) => ({ id: s.id, name: s.name })) };\n\t\t}\n\t};\n\n\tconst select: AgentTool = {\n\t\tname: 'select_chart_element',\n\t\ttitle: 'Select a chart element',\n\t\tdescription: 'Selects part of the chart (as a click would), for press_chart_key and for the user to see. kind \"none\" clears the selection. Returns the selection.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tkind: { type: 'string', enum: ['none', 'chart', 'title', 'subtitle', 'legend', 'axis', 'series', 'point', 'category', 'trendline'], description: 'What to select.' },\n\t\t\t\tseries: { ...SERIES_REF, description: 'Series id or name (series, point, trendline).' },\n\t\t\t\tcategory: { ...CATEGORY_REF, description: 'Category index or label (point, category).' },\n\t\t\t\taxis: { type: 'string', enum: ['x', 'y', 'y2'], description: 'Axis (axis).' },\n\t\t\t\tindex: { type: 'integer', minimum: 0, description: 'Trendline index (trendline).' }\n\t\t\t},\n\t\t\trequired: ['kind'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Select a chart element', ...WRITE_IDEMPOTENT },\n\t\thandler: async ({ kind, series, category, axis, index }) => {\n\t\t\tlet sel: ChartSelection | null;\n\t\t\tconst need = (v: unknown, what: string) => v === undefined && fail(`kind \"${kind}\" needs ${what}.`);\n\t\t\tswitch (kind) {\n\t\t\t\tcase 'none':\n\t\t\t\t\tsel = null;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'axis':\n\t\t\t\t\tneed(axis, 'axis');\n\t\t\t\t\tsel = { kind, axis };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'series':\n\t\t\t\t\tneed(series, 'series');\n\t\t\t\t\tsel = { kind, seriesId: seriesById(series).id };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'point':\n\t\t\t\t\tneed(series, 'series');\n\t\t\t\t\tneed(category, 'category');\n\t\t\t\t\tsel = { kind, seriesId: seriesById(series).id, index: categoryIndex(category) };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'category':\n\t\t\t\t\tneed(category, 'category');\n\t\t\t\t\tsel = { kind, index: categoryIndex(category) };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'trendline':\n\t\t\t\t\tneed(series, 'series');\n\t\t\t\t\tneed(index, 'index');\n\t\t\t\t\tsel = { kind, seriesId: seriesById(series).id, index };\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsel = { kind } as ChartSelection;\n\t\t\t}\n\t\t\tif (options.director) await options.director.perform(options.actor ?? { id: 'agent', name: 'Agent' }, [{ kind: 'select', selection: sel }]);\n\t\t\telse controller.select(sel);\n\t\t\tconst now = controller.getState().selection;\n\t\t\tif (sel && !now) fail(`Nothing to select there (e.g. the chart has no ${kind} of that kind).`);\n\t\t\treturn { selection: now };\n\t\t}\n\t};\n\n\tconst drag: AgentTool = {\n\t\tname: 'drag_chart_point',\n\t\ttitle: 'Drag a chart point',\n\t\tdescription:\n\t\t\t'Drags on the chart as a pointer would, through the same code as the mouse: from a bar or point to a new position, with the same snapping (to other values, zero and ticks), fine adjustment (fine: Alt) and axis lock on scatter charts (lockAxis: Shift). Positions are 0–1 fractions of the chart\\'s width and height at the given size (use render_chart to see where marks are). One undo step. Returns what was dragged and the value before and after.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tfrom: { type: 'object', description: 'Start, as fractions of the chart (0,0 top-left).', properties: { x: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the width.' }, y: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the height.' } }, required: ['x', 'y'], additionalProperties: false },\n\t\t\t\tto: { type: 'object', description: 'End, as fractions of the chart.', properties: { x: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the width.' }, y: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the height.' } }, required: ['x', 'y'], additionalProperties: false },\n\t\t\t\tfine: { type: 'boolean', description: 'Move a tenth as far (Alt).' },\n\t\t\t\tlockAxis: { type: 'boolean', description: 'Scatter charts: change only the axis moved along most (Shift).' },\n\t\t\t\twidth: WIDTH,\n\t\t\t\theight: HEIGHT\n\t\t\t},\n\t\t\trequired: ['from', 'to'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Drag a chart point', ...WRITE },\n\t\thandler: ({ from, to, fine, lockAxis, width = size.width, height = size.height }) => {\n\t\t\tconst scene = layoutChart(controller.toJSON(), { width, height });\n\t\t\tconst start = { x: from.x * width, y: from.y * height };\n\t\t\tconst target = chartHitTest(scene, start);\n\t\t\tif (target?.kind !== 'point') fail(`There is no bar or point at (${from.x}, ${from.y}); ${target ? `that is the ${target.kind}` : 'that is outside the chart'}. Use render_chart to find marks.`);\n\t\t\tconst t = target as Extract<ChartSelection, { kind: 'point' }>;\n\t\t\tconst before = controller.getSeries(t.seriesId)?.values[t.index] ?? null;\n\t\t\tconst session = startChartPointDrag(controller, scene, t, start);\n\t\t\tif (!session) fail('That point cannot be dragged here (percent-stacked charts, pies and gaps cannot be dragged).');\n\t\t\tsession!.move({ x: to.x * width, y: to.y * height }, { fine, lockAxis });\n\t\t\tsession!.end();\n\t\t\tconst s = controller.getSeries(t.seriesId)!;\n\t\t\treturn { series: s.id, category: spec().categories[t.index], index: t.index, before, after: s.values[t.index], ...(s.x ? { x: s.x[t.index] } : {}) };\n\t\t}\n\t};\n\n\tconst key: AgentTool = {\n\t\tname: 'press_chart_key',\n\t\ttitle: 'Press a key on the chart',\n\t\tdescription:\n\t\t\t'Sends a key to the chart as the keyboard would, acting on the selection (select_chart_element first): ← → move between categories, ↑ ↓ change the selected value by a tenth of a tick (shift: a whole tick, alt: a hundredth), Delete removes the selection, Escape clears it. Returns whether the key did anything and the new selection.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tkey: { type: 'string', enum: ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Delete', 'Backspace', 'Escape'], description: 'Key name.' },\n\t\t\t\tshift: { type: 'boolean', description: 'Hold Shift.' },\n\t\t\t\talt: { type: 'boolean', description: 'Hold Alt / Option.' }\n\t\t\t},\n\t\t\trequired: ['key'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Press a key on the chart', ...DESTRUCTIVE },\n\t\thandler: ({ key: k, shift, alt }) => {\n\t\t\tconst scene = layoutChart(controller.toJSON(), size);\n\t\t\tconst used = handleChartKey(controller, scene, { key: k, shiftKey: shift, altKey: alt });\n\t\t\tconst sel = controller.getState().selection;\n\t\t\tconst value = sel?.kind === 'point' ? (controller.getSeries(sel.seriesId)?.values[sel.index] ?? null) : undefined;\n\t\t\treturn { used, selection: sel, ...(value !== undefined ? { value } : {}) };\n\t\t}\n\t};\n\n\tconst undo: AgentTool = {\n\t\tname: 'undo_chart',\n\t\ttitle: 'Undo a chart edit',\n\t\tdescription: 'Undoes the last chart edit. Returns whether something was undone and what the next undo would be.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Undo a chart edit', ...WRITE },\n\t\thandler: () => {\n\t\t\tconst label = controller.getState().undoLabel;\n\t\t\tconst undone = controller.undo();\n\t\t\treturn { undone, ...(undone ? { label } : {}), next: controller.getState().undoLabel || null };\n\t\t}\n\t};\n\n\tconst redo: AgentTool = {\n\t\tname: 'redo_chart',\n\t\ttitle: 'Redo a chart edit',\n\t\tdescription: 'Redoes the last undone chart edit. Returns whether something was redone.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Redo a chart edit', ...WRITE },\n\t\thandler: () => {\n\t\t\tconst label = controller.getState().redoLabel;\n\t\t\tconst redone = controller.redo();\n\t\t\treturn { redone, ...(redone ? { label } : {}) };\n\t\t}\n\t};\n\n\tconst reads = [getChart, renderChart, checkColors, recommend, getTrendline, listPresets, exportMermaid, exportOoxml];\n\tconst writes = [updateChart, setData, setValues, addSeries, updateSeries, removeSeries, addCategory, removeCategory, importCsv, importMermaid, addTrendline, removeTrendline, applyPreset, transpose, select, drag, key, undo, redo];\n\n\treturn {\n\t\tid: options.id ?? 'chart',\n\t\tnamespace: options.namespace,\n\t\ttools: () => {\n\t\t\tif (readOnlyReason()) return reads;\n\t\t\treturn [...reads, ...writes.slice(0, 10), ...(Parser() ? [importOoxml] : []), ...writes.slice(10)];\n\t\t},\n\t\tsubscribe: (notify) => {\n\t\t\t// Re-announce when read-only state may have changed.\n\t\t\tlet last = readOnlyReason();\n\t\t\treturn controller.subscribe(() => {\n\t\t\t\tconst now = readOnlyReason();\n\t\t\t\tif (now !== last) {\n\t\t\t\t\tlast = now;\n\t\t\t\t\tnotify();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n}\n","// Streaming follows Ursula's MermaidStreamingView and src/graph/view.ts (`blendLayout`: marks are matched by id,\n// new ones appear at their target, missing ones drop out; layouts are adopted on a throttle and the scale is held\n// steady until the source is complete).\nimport { chartFromMermaid } from './mermaid.js';\nimport { normalizeChartSpec } from './spec.js';\nimport type { ChartIssue, ChartMark, ChartScene, ChartSpec } from './types.js';\n\n/**\n * Reads JSON that is still arriving: closes open strings, arrays and objects and drops a\n * dangling key or comma, so `{\"type\":\"bar\",\"series\":[{\"name\":\"A\",\"values\":[1,2` reads as far\n * as it goes. Returns `undefined` when nothing usable has arrived yet.\n */\nexport function parsePartialChartJson(text: string): unknown {\n\tconst src = text.trim();\n\tif (!src) return undefined;\n\ttry {\n\t\treturn JSON.parse(src);\n\t} catch {\n\t\t// fall through\n\t}\n\tconst stack: string[] = [];\n\tlet inString = false;\n\tlet escaped = false;\n\tlet out = '';\n\tfor (const ch of src) {\n\t\tout += ch;\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (ch === '\\\\') escaped = true;\n\t\t\telse if (ch === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"') inString = true;\n\t\telse if (ch === '{' || ch === '[') stack.push(ch === '{' ? '}' : ']');\n\t\telse if (ch === '}' || ch === ']') stack.pop();\n\t}\n\tif (inString) out += '\"';\n\t// Drop what cannot end a value: a trailing comma, colon, key without value or partial literal.\n\tfor (let attempt = 0; attempt < 6; attempt++) {\n\t\tconst trimmed = out.replace(/\\s+$/, '');\n\t\tconst candidate = trimmed + [...stack].reverse().join('');\n\t\ttry {\n\t\t\treturn JSON.parse(candidate);\n\t\t} catch {\n\t\t\tconst next = trimmed\n\t\t\t\t.replace(/,\\s*$/, '')\n\t\t\t\t.replace(/(?:,|\\{)\\s*\"[^\"]*\"\\s*:?\\s*$/, (m) => (m.trim().startsWith('{') ? '{' : ''))\n\t\t\t\t.replace(/:\\s*$/, ': null')\n\t\t\t\t.replace(/(?<=[\\[,:]\\s*)(-|tr?u?|fa?l?s?|nu?l?)$/, '')\n\t\t\t\t.replace(/(?<=[\\[,:]\\s*)(-?\\d+\\.)$/, (m) => m.slice(0, -1));\n\t\t\tif (next === trimmed) break;\n\t\t\tout = next;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport type ChartStreamFormat = 'auto' | 'mermaid' | 'json';\n\nexport interface ChartStreamResult {\n\t/** The chart as far as it has arrived, or `null` before anything can be drawn. */\n\tspec: ChartSpec | null;\n\tissues: ChartIssue[];\n\t/**\n\t * The value range to lay out with while incomplete: it only grows, so the axis does not\n\t * jump as values arrive. `null` once complete (the chart's own scale takes over).\n\t */\n\tvalueDomain: { min: number; max: number } | null;\n}\n\n/**\n * Turns a chart source that is still being written (Mermaid or a JSON spec, e.g. streamed\n * from a model) into drawable specs. Series appear once their values start, axis bounds only\n * grow until `complete`, and parse problems are reported only once the source is complete.\n */\nexport class ChartStream {\n\tprivate lo = Infinity;\n\tprivate hi = -Infinity;\n\tprivate last: ChartSpec | null = null;\n\n\tconstructor(private readonly format: ChartStreamFormat = 'auto') {}\n\n\t/** Reads the source so far. `complete` when nothing more will arrive. */\n\tupdate(source: string, complete = false): ChartStreamResult {\n\t\tconst text = source.replace(/^\\s*```(?:mermaid|json)?\\s*\\n?/, '').replace(/```\\s*$/, '');\n\t\tconst format = this.format === 'auto' ? (/^\\s*[[{]/.test(text) ? 'json' : 'mermaid') : this.format;\n\t\tlet spec: ChartSpec | null = null;\n\t\tlet issues: ChartIssue[] = [];\n\t\tif (format === 'json') {\n\t\t\tconst value = complete ? safeParse(text) : parsePartialChartJson(text);\n\t\t\tif (value !== undefined) {\n\t\t\t\tconst read = normalizeChartSpec(value);\n\t\t\t\tspec = read.spec;\n\t\t\t\tissues = complete ? read.issues : [];\n\t\t\t}\n\t\t} else {\n\t\t\tconst read = chartFromMermaid(text, { partial: !complete });\n\t\t\tif (read.family) {\n\t\t\t\tspec = read.spec;\n\t\t\t\tissues = complete ? read.issues : [];\n\t\t\t}\n\t\t}\n\t\tif (spec && !spec.series.some((s) => s.values.some((v) => v !== null))) spec = complete ? spec : this.last;\n\t\tif (spec) this.last = spec;\n\t\tif (spec) {\n\t\t\tfor (const s of spec.series) for (const v of s.values) if (v !== null && Number.isFinite(v)) (this.lo = Math.min(this.lo, v)), (this.hi = Math.max(this.hi, v));\n\t\t}\n\t\tconst valueDomain = !complete && Number.isFinite(this.lo) && this.hi > this.lo ? { min: Math.min(0, this.lo), max: this.hi } : null;\n\t\treturn { spec, issues, valueDomain };\n\t}\n\n\t/** Forgets the axis bounds (a new source). */\n\treset(): void {\n\t\tthis.lo = Infinity;\n\t\tthis.hi = -Infinity;\n\t\tthis.last = null;\n\t}\n}\n\nfunction safeParse(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn parsePartialChartJson(text);\n\t}\n}\n\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\n\n/** Paths with the same commands blend number by number; others switch at the end. */\nfunction blendPath(a: string, b: string, t: number): string {\n\tconst na = a.match(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g);\n\tconst nb = b.match(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g);\n\tif (!na || !nb || na.length !== nb.length || a.replace(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g, '#') !== b.replace(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g, '#')) return t < 1 ? a : b;\n\tlet i = 0;\n\treturn b.replace(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g, () => {\n\t\tconst v = mix(Number(na[i]), Number(nb[i]), t);\n\t\ti++;\n\t\treturn String(Math.round(v * 100) / 100);\n\t});\n}\n\n/**\n * A scene between two scenes, for animating changes (streamed data arriving, an agent's\n * edit): marks are matched by `key`; numbers and same-shaped paths move from `from` to `to`;\n * new marks fade in and marks that are gone are dropped. `t` runs from 0 to 1.\n */\nexport function blendChartScenes(from: ChartScene | null, to: ChartScene, t: number): ChartScene {\n\tif (!from || t >= 1) return to;\n\tconst k = Math.max(0, Math.min(1, t));\n\tconst before = new Map(from.marks.map((m) => [m.key, m]));\n\tconst marks: ChartMark[] = to.marks.map((m) => {\n\t\tconst a = before.get(m.key);\n\t\tif (!a || a.kind !== m.kind) return { ...m, opacity: (m.opacity ?? 1) * k };\n\t\tswitch (m.kind) {\n\t\t\tcase 'rect': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, x: mix(p.x, m.x, k), y: mix(p.y, m.y, k), width: mix(p.width, m.width, k), height: mix(p.height, m.height, k) };\n\t\t\t}\n\t\t\tcase 'circle': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, cx: mix(p.cx, m.cx, k), cy: mix(p.cy, m.cy, k), r: mix(p.r, m.r, k) };\n\t\t\t}\n\t\t\tcase 'line': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, x1: mix(p.x1, m.x1, k), y1: mix(p.y1, m.y1, k), x2: mix(p.x2, m.x2, k), y2: mix(p.y2, m.y2, k) };\n\t\t\t}\n\t\t\tcase 'text': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, x: mix(p.x, m.x, k), y: mix(p.y, m.y, k) };\n\t\t\t}\n\t\t\tcase 'path':\n\t\t\t\treturn { ...m, d: blendPath((a as typeof m).d, m.d, k) };\n\t\t}\n\t});\n\treturn { ...to, marks };\n}\n\n/** Ease-out cubic, for tweens. */\nexport const easeChartTween = (t: number) => 1 - Math.pow(1 - Math.max(0, Math.min(1, t)), 3);\n","// Agent \"performances\" follow Ursula's remote control (src/remote/commands.ts `planCommand`, src/react/remote/director.ts,\n// presence.ts, clock.ts): a pure planner turns a command into cursor steps, a director acts them out per actor and\n// commits each command as one undo step, and the clock is injectable so performances are repeatable in tests.\nimport type { ChartController, ChartSpecPatch } from './controller.js';\nimport { linearMap } from './scale.js';\nimport type { ChartScene, ChartSelection, ChartSpec } from './types.js';\n\nexport interface ChartPresenceActor {\n\tid: string;\n\tname: string;\n\tcolor: string;\n\t/** Cursor position in scene coordinates. */\n\tx: number;\n\ty: number;\n\t/** The button is down (dragging). */\n\tpressed: boolean;\n\t/** A short note shown next to the cursor (what the agent is doing). */\n\tmessage?: string;\n}\n\nexport interface ChartPresenceState {\n\tactors: readonly ChartPresenceActor[];\n}\n\n/** Cursor positions and notes of agents acting on a chart, for an overlay. */\nexport class ChartPresence {\n\tprivate state: ChartPresenceState = { actors: [] };\n\tprivate readonly listeners = new Set<(state: ChartPresenceState) => void>();\n\n\tgetState = (): ChartPresenceState => this.state;\n\n\tsubscribe = (listener: (state: ChartPresenceState) => void): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\t/** Adds or changes an actor. */\n\tset(actor: Pick<ChartPresenceActor, 'id'> & Partial<ChartPresenceActor>): void {\n\t\tconst current = this.state.actors.find((a) => a.id === actor.id);\n\t\tconst next: ChartPresenceActor = { name: actor.id, color: CHART_PRESENCE_COLORS[this.state.actors.length % CHART_PRESENCE_COLORS.length], x: 0, y: 0, pressed: false, ...current, ...actor };\n\t\tthis.state = { actors: current ? this.state.actors.map((a) => (a.id === actor.id ? next : a)) : [...this.state.actors, next] };\n\t\tthis.listeners.forEach((l) => l(this.state));\n\t}\n\n\tremove(id: string): void {\n\t\tif (!this.state.actors.some((a) => a.id === id)) return;\n\t\tthis.state = { actors: this.state.actors.filter((a) => a.id !== id) };\n\t\tthis.listeners.forEach((l) => l(this.state));\n\t}\n}\n\nexport const CHART_PRESENCE_COLORS: readonly string[] = ['#7c3aed', '#db2777', '#0891b2', '#ea580c', '#16a34a'];\n\n/** Time for performances: real timers, or an instant clock for tests and recordings. */\nexport interface ChartClock {\n\tnow(): number;\n\twait(ms: number): Promise<void>;\n}\n\nexport const realChartClock: ChartClock = {\n\tnow: () => Date.now(),\n\twait: (ms) => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)))\n};\n\n/** A clock whose waits finish at once while its time still advances (repeatable performances). */\nexport function createInstantChartClock(start = 0): ChartClock & { elapsed(): number } {\n\tlet t = start;\n\treturn {\n\t\tnow: () => t,\n\t\twait: async (ms) => {\n\t\t\tt += Math.max(0, ms);\n\t\t},\n\t\telapsed: () => t - start\n\t};\n}\n\n/** What an agent asks for. Each command commits as one undo step. */\nexport type ChartAgentCommand =\n\t| { kind: 'setValue'; seriesId: string; index: number; value: number; note?: string }\n\t| { kind: 'select'; selection: ChartSelection | null; note?: string }\n\t| { kind: 'update'; patch: ChartSpecPatch; label?: string; note?: string }\n\t| { kind: 'say'; text: string };\n\nexport type ChartPerformanceStep =\n\t| { type: 'move'; to: { x: number; y: number }; ms: number }\n\t| { type: 'say'; text: string; ms: number }\n\t| { type: 'press' }\n\t| { type: 'drag'; to: { x: number; y: number }; ms: number; from: number; value: number }\n\t| { type: 'release' }\n\t| { type: 'commit' };\n\n/** Where a point or bar sits in the scene (its top for bars), or null when it is not drawn. */\nexport function chartPointAnchor(scene: ChartScene, seriesId: string, index: number): { x: number; y: number } | null {\n\tconst mark = scene.marks.find((m) => (m.role === 'bar' || m.role === 'point') && m.target?.kind === 'point' && m.target.seriesId === seriesId && m.target.index === index);\n\tif (!mark) return null;\n\tif (mark.kind === 'rect') return { x: mark.x + mark.width / 2, y: mark.y };\n\tif (mark.kind === 'circle') return { x: mark.cx, y: mark.cy };\n\treturn null;\n}\n\nconst anchorFor = (scene: ChartScene, role: string) => {\n\tconst m = scene.marks.find((x) => x.role === role);\n\tif (!m) return null;\n\tif (m.kind === 'text') return { x: m.x, y: m.y };\n\tif (m.kind === 'rect') return { x: m.x + m.width / 2, y: m.y + m.height / 2 };\n\tif (m.kind === 'line') return { x: (m.x1 + m.x2) / 2, y: (m.y1 + m.y2) / 2 };\n\treturn null;\n};\n\n/**\n * Plans how an agent acts out a command on the chart: cursor moves, a drag along the value\n * axis for a value change (its end at the new value), a note, then a commit. Pure: the same\n * scene and command give the same steps.\n */\nexport function planChartCommand(spec: ChartSpec, scene: ChartScene, command: ChartAgentCommand, speed = 1): ChartPerformanceStep[] {\n\tconst ms = (n: number) => Math.round(n / Math.max(0.1, speed));\n\tconst steps: ChartPerformanceStep[] = [];\n\tconst note = 'note' in command && command.note ? command.note : undefined;\n\tif (note) steps.push({ type: 'say', text: note, ms: ms(500) });\n\tswitch (command.kind) {\n\t\tcase 'say':\n\t\t\tsteps.push({ type: 'say', text: command.text, ms: ms(900) });\n\t\t\treturn steps;\n\t\tcase 'setValue': {\n\t\t\tconst at = chartPointAnchor(scene, command.seriesId, command.index);\n\t\t\tconst series = spec.series.find((s) => s.id === command.seriesId);\n\t\t\tconst from = series?.values[command.index] ?? 0;\n\t\t\tconst scale = series?.axis === 'secondary' ? (scene.valueScale2 ?? scene.valueScale) : scene.valueScale;\n\t\t\tif (at && scale) {\n\t\t\t\tconst px = linearMap(command.value, scale.domain, scale.range);\n\t\t\t\tconst to = scale.axis === 'y' ? { x: at.x, y: px } : { x: px, y: at.y };\n\t\t\t\tsteps.push({ type: 'move', to: at, ms: ms(380) }, { type: 'press' }, { type: 'drag', to, ms: ms(520), from, value: command.value }, { type: 'release' });\n\t\t\t} else steps.push({ type: 'drag', to: { x: scene.plot.x + scene.plot.width / 2, y: scene.plot.y + scene.plot.height / 2 }, ms: ms(200), from, value: command.value });\n\t\t\tsteps.push({ type: 'commit' });\n\t\t\treturn steps;\n\t\t}\n\t\tcase 'select': {\n\t\t\tconst sel = command.selection;\n\t\t\tlet to: { x: number; y: number } | null = null;\n\t\t\tif (sel?.kind === 'point') to = chartPointAnchor(scene, sel.seriesId, sel.index);\n\t\t\telse if (sel) {\n\t\t\t\tconst m = scene.marks.find((x) => x.target && JSON.stringify(x.target) === JSON.stringify(sel));\n\t\t\t\tif (m?.kind === 'text') to = { x: m.x, y: m.y };\n\t\t\t\telse if (m?.kind === 'rect') to = { x: m.x + m.width / 2, y: m.y + m.height / 2 };\n\t\t\t\telse if (m?.kind === 'circle') to = { x: m.cx, y: m.cy };\n\t\t\t}\n\t\t\tif (to) steps.push({ type: 'move', to, ms: ms(380) }, { type: 'press' }, { type: 'release' });\n\t\t\tsteps.push({ type: 'commit' });\n\t\t\treturn steps;\n\t\t}\n\t\tcase 'update': {\n\t\t\tconst keys = Object.keys(command.patch);\n\t\t\tconst role = keys.includes('title') ? 'title' : keys.includes('legend') ? 'legend-label' : keys.some((k) => k === 'xAxis') ? 'axis' : keys.some((k) => k === 'yAxis' || k === 'yAxis2') ? 'tick-label' : null;\n\t\t\tconst to = (role && anchorFor(scene, role)) || { x: scene.plot.x + scene.plot.width / 2, y: scene.plot.y + 12 };\n\t\t\tsteps.push({ type: 'move', to, ms: ms(380) }, { type: 'press' }, { type: 'release' }, { type: 'commit' });\n\t\t\treturn steps;\n\t\t}\n\t}\n}\n\nexport interface ChartDirectorOptions {\n\t/** The scene as currently drawn (for cursor targets), e.g. the canvas' last layout. */\n\tscene: () => ChartScene;\n\tclock?: ChartClock;\n\t/** 1 = natural speed; 2 = twice as fast. */\n\tspeed?: number;\n\t/** Hide each actor's cursor this long after its last command (ms, default 1500; 0 keeps it). */\n\tlinger?: number;\n}\n\nexport interface ChartDirectorActor {\n\tid: string;\n\tname?: string;\n\tcolor?: string;\n}\n\nexport type ChartPerformanceResult = { ok: true; command: ChartAgentCommand } | { ok: false; command: ChartAgentCommand; message: string };\n\n/**\n * Acts out agent commands on a chart: each actor's cursor moves to the target, drags values\n * into place (the chart updates live) and the command commits as one undo step, while the\n * user keeps editing. Commands queue per actor; a command whose target was deleted meanwhile\n * fails with a sentence instead of editing something else.\n */\nexport class ChartDirector {\n\tprivate readonly queues = new Map<string, Promise<unknown>>();\n\tprivate readonly clock: ChartClock;\n\tprivate calls = 0;\n\n\tconstructor(\n\t\tprivate readonly controller: ChartController,\n\t\treadonly presence: ChartPresence,\n\t\tprivate readonly options: ChartDirectorOptions\n\t) {\n\t\tthis.clock = options.clock ?? realChartClock;\n\t}\n\n\t/** Acts out `commands` in order for `actor`. Resolves with one result per command. */\n\tperform(actor: ChartDirectorActor, commands: readonly ChartAgentCommand[]): Promise<ChartPerformanceResult[]> {\n\t\tconst prev = this.queues.get(actor.id) ?? Promise.resolve();\n\t\tconst run = prev.then(async () => {\n\t\t\tconst results: ChartPerformanceResult[] = [];\n\t\t\tthis.presence.set({ id: actor.id, ...(actor.name ? { name: actor.name } : {}), ...(actor.color ? { color: actor.color } : {}) });\n\t\t\t// Everything one call changes is one undo step.\n\t\t\tthis.controller.beginGesture(`agent:${actor.id}:${++this.calls}`);\n\t\t\ttry {\n\t\t\t\tfor (const command of commands) results.push(await this.performOne(actor.id, command));\n\t\t\t} finally {\n\t\t\t\tthis.controller.endGesture();\n\t\t\t\tthis.presence.set({ id: actor.id, message: undefined, pressed: false });\n\t\t\t}\n\t\t\tconst linger = this.options.linger ?? 1500;\n\t\t\tif (linger > 0) {\n\t\t\t\tawait this.clock.wait(linger);\n\t\t\t\tif (this.queues.get(actor.id) === run) this.presence.remove(actor.id);\n\t\t\t}\n\t\t\treturn results;\n\t\t});\n\t\tthis.queues.set(actor.id, run.catch(() => undefined));\n\t\treturn run;\n\t}\n\n\tprivate stale(command: ChartAgentCommand): string | null {\n\t\tconst spec = this.controller.getSpec();\n\t\tif (command.kind === 'setValue') {\n\t\t\tconst s = spec.series.find((x) => x.id === command.seriesId);\n\t\t\tif (!s) return `The series \"${command.seriesId}\" no longer exists.`;\n\t\t\tif (command.index < 0 || command.index >= spec.categories.length) return `Category ${command.index} no longer exists.`;\n\t\t\tif (!Number.isFinite(command.value)) return 'The value must be a finite number.';\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate async move(id: string, from: { x: number; y: number }, to: { x: number; y: number }, ms: number, each?: (t: number) => void) {\n\t\tconst frames = Math.max(1, Math.round(ms / 16));\n\t\tfor (let f = 1; f <= frames; f++) {\n\t\t\tconst t = f / frames;\n\t\t\tconst e = 1 - Math.pow(1 - t, 3);\n\t\t\tthis.presence.set({ id, x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e });\n\t\t\teach?.(e);\n\t\t\tawait this.clock.wait(ms / frames);\n\t\t}\n\t}\n\n\tprivate async performOne(id: string, command: ChartAgentCommand): Promise<ChartPerformanceResult> {\n\t\tconst stale = this.stale(command);\n\t\tif (stale) return { ok: false, command, message: stale };\n\t\tconst steps = planChartCommand(this.controller.getSpec(), this.options.scene(), command, this.options.speed);\n\t\tconst where = () => {\n\t\t\tconst a = this.presence.getState().actors.find((x) => x.id === id)!;\n\t\t\treturn { x: a.x, y: a.y };\n\t\t};\n\t\t{\n\t\t\tfor (const step of steps) {\n\t\t\t\tswitch (step.type) {\n\t\t\t\t\tcase 'say':\n\t\t\t\t\t\tthis.presence.set({ id, message: step.text });\n\t\t\t\t\t\tawait this.clock.wait(step.ms);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'move':\n\t\t\t\t\t\tawait this.move(id, where(), step.to, step.ms);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'press':\n\t\t\t\t\t\tthis.presence.set({ id, pressed: true });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'release':\n\t\t\t\t\t\tthis.presence.set({ id, pressed: false });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'drag': {\n\t\t\t\t\t\tif (command.kind !== 'setValue') break;\n\t\t\t\t\t\t// The value follows the cursor; the whole drag is one undo step.\n\t\t\t\t\t\tconst stale2 = this.stale(command);\n\t\t\t\t\t\tif (stale2) return { ok: false, command, message: stale2 };\n\t\t\t\t\t\tconst label = `${this.presence.getState().actors.find((a) => a.id === id)?.name ?? 'Agent'}: edit value`;\n\t\t\t\t\t\tawait this.move(id, where(), step.to, step.ms, (e) => {\n\t\t\t\t\t\t\tconst v = step.from + (step.value - step.from) * e;\n\t\t\t\t\t\t\tthis.controller.setValue(command.seriesId, command.index, Number(v.toPrecision(12)), { label });\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.controller.setValue(command.seriesId, command.index, step.value, { label });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'commit': {\n\t\t\t\t\t\tif (command.kind === 'select') this.controller.select(command.selection);\n\t\t\t\t\t\telse if (command.kind === 'update') {\n\t\t\t\t\t\t\tconst result = this.controller.update(command.patch, command.label ? { label: command.label } : {});\n\t\t\t\t\t\t\tif (!result.ok) return { ok: false, command, message: result.message };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, command };\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBO,SAAS,uBAAuB,MAA+B;AACrE,QAAM,MAAM,aAAa,YAAY,IAAI;AACzC,SAAO;AAAA,IACN,QAAQ,IAAI,OAAO;AAAA,IACnB,WAAW,IAAI,UAAU;AAAA,IACzB,QAAQ,CAAC,UAAmB,OAAO,SAAS,KAAK,IAAI,IAAI,aAAa,KAAK,EAAE,OAAO;AAAA,EACrF;AACD;AAGO,SAAS,yBAAyB,OAAe,MAAsB;AAC7E,SAAO,uBAAuB,IAAI,EAAE,OAAO,KAAK;AACjD;AAGO,SAAS,kBAAkB,QAAsB;AAEvD,QAAM,SAAS,SAAS,KAAK,KAAK,IAAI,MAAM,IAAI,EAAE,IAAI,KAAK,IAAI,MAAM,IAAI,EAAE;AAC3E,SAAO,IAAI,KAAK,SAAS,KAAK,MAAM,SAAS,KAAQ,CAAC;AACvD;AAGO,SAAS,kBAAkB,MAAoB;AACrD,QAAM,UAAU,KAAK,QAAQ,IAAI,KAAK,IAAI,MAAM,IAAI,EAAE,KAAK;AAC3D,SAAO,SAAS,KAAK,SAAS,IAAI;AACnC;;;ACtCO,SAAS,SAAS,MAAc,OAAuB;AAC7D,MAAI,EAAE,OAAO,MAAM,EAAE,QAAQ,GAAI,QAAO;AACxC,QAAM,MAAM,OAAO;AACnB,QAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,MAAM,KAAK,MAAM,GAAG,CAAC,CAAC;AACtD,QAAM,WAAW,MAAM;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MAAM,CAAC;AAC/E;AAAA,UACD;AAAA,UACA,KAAK,UAAU;AACd,gBAAI,QAAQ,SAAS,SAAU,MAAK,WAAW,OAAO,QAAQ,SAAS;AAAA,qBAC9D,QAAQ,SAAS,UAAU;AACnC,oBAAM,SAAS,KAAK,WAAW,OAAO,QAAQ,OAAO,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAC;AAClG,kBAAI,CAAC,OAAO,GAAI,QAAO,EAAE,IAAI,OAAO,SAAS,SAAS,OAAO,QAAQ;AAAA,YACtE;AACA;AAAA,UACD;AAAA,QACD;AAAA,MACD;AACA,aAAO,EAAE,IAAI,MAAM,QAAQ;AAAA,IAC5B;AAAA,EACD;AACD;","names":["n","clean","i","m","r2","clean","band","p","k","t","check","span","fy","fail","clean","snap","fail","clean","resolve"]}
1
+ {"version":3,"sources":["../../src/chart/recommend.ts","../../src/chart/commands.ts","../../src/chart/interaction.ts","../../src/chart/tools.ts","../../src/chart/stream.ts","../../src/chart/presence.ts"],"sourcesContent":["// Ported from gridcraft-main/crates/engine/src/cmd/insert.rs (`series_from_range`, `scatter_x_from_first`,\n// `recommend_charts`) (MIT OR Apache-2.0, © ArtCraft Team and contributors), extended for the chart types\n// this editor adds. See THIRD_PARTY_NOTICES.md.\nimport { parseChartDate } from './date.js';\nimport { chartDataFromTable, parseChartValue } from './spec.js';\nimport type { ChartIssue, ChartSeries, ChartStacking, ChartType } from './types.js';\n\nexport interface ChartTableShape {\n\t/** The first row holds series names (some text, every value cell text or blank). */\n\theaderRow: boolean;\n\t/** The first column holds category labels (all text, or a blank top-left cell above a header row). */\n\tlabelColumn: boolean;\n\t/** Series run along rows (the block is much wider than tall). */\n\tbyRows: boolean;\n\tseries: number;\n\t/** Points per series. */\n\tpoints: number;\n\tanyNumber: boolean;\n\tnonNegative: boolean;\n\tmixedSigns: boolean;\n\t/** The category labels read as dates. */\n\tdates: boolean;\n}\n\nconst blank = (c: unknown) => c === null || c === undefined || String(c).trim() === '';\nconst isText = (c: unknown) => blank(c) || parseChartValue(c) === undefined;\n\n/**\n * Reads the shape of a block of cells the way spreadsheets do: a header row when the first\n * row is text, a label column when the first column is text (or the top-left cell is blank\n * above a header row, the convention for years and x values), and series along the longer side.\n */\nexport function analyzeChartTable(rows: ReadonlyArray<ReadonlyArray<unknown>>): ChartTableShape {\n\tconst grid = rows.filter((r) => r.some((c) => !blank(c)));\n\tconst height = grid.length;\n\tconst width = Math.max(0, ...grid.map((r) => r.length));\n\tconst cell = (r: number, c: number) => grid[r]?.[c];\n\tconst headerRow = height > 1 && grid[0].some((c) => !blank(c) && isText(c)) && Array.from({ length: width - 1 }, (_, i) => i + 1).every((c) => isText(cell(0, c)));\n\tconst blankCorner = headerRow && blank(cell(0, 0));\n\tconst labelColumn = width > 1 && (blankCorner || Array.from({ length: height - (headerRow ? 1 : 0) }, (_, i) => i + (headerRow ? 1 : 0)).every((r) => isText(cell(r, 0))));\n\tconst byRows = width > height + 1;\n\tconst dataRows = height - (headerRow ? 1 : 0);\n\tconst dataCols = width - (labelColumn ? 1 : 0);\n\tlet anyNumber = false;\n\tlet nonNegative = true;\n\tlet anyNegative = false;\n\tlet anyPositive = false;\n\tfor (let r = headerRow ? 1 : 0; r < height; r++)\n\t\tfor (let c = labelColumn ? 1 : 0; c < width; c++) {\n\t\t\tconst v = parseChartValue(cell(r, c));\n\t\t\tif (typeof v !== 'number') continue;\n\t\t\tanyNumber = true;\n\t\t\tif (v < 0) {\n\t\t\t\tnonNegative = false;\n\t\t\t\tanyNegative = true;\n\t\t\t} else if (v > 0) anyPositive = true;\n\t\t}\n\tconst labels = byRows ? grid[0]?.slice(labelColumn ? 1 : 0) ?? [] : grid.slice(headerRow ? 1 : 0).map((r) => r[0]);\n\tconst dates = (byRows ? headerRow : labelColumn) && labels.length > 1 && labels.filter((l) => !blank(l) && parseChartDate(String(l)) !== null).length >= labels.length * 0.8;\n\treturn {\n\t\theaderRow,\n\t\tlabelColumn,\n\t\tbyRows,\n\t\tseries: Math.max(0, byRows ? dataRows : dataCols),\n\t\tpoints: Math.max(0, byRows ? dataCols : dataRows),\n\t\tanyNumber,\n\t\tnonNegative,\n\t\tmixedSigns: anyNegative && anyPositive,\n\t\tdates\n\t};\n}\n\nexport interface ChartRecommendation {\n\ttype: ChartType;\n\tstacking?: ChartStacking;\n\tlabel: string;\n\t/** Why it suits the data, as a sentence. */\n\treason: string;\n}\n\n/**\n * Chart types that suit the shape of a block of cells, best first. A heuristic from the shape\n * (series count, points per series, text or date categories, negative values), not a copy of\n * any spreadsheet's ranking.\n */\nexport function recommendChartTypes(rows: ReadonlyArray<ReadonlyArray<unknown>>): ChartRecommendation[] {\n\tconst shape = analyzeChartTable(rows);\n\tif (!shape.anyNumber || !shape.series) return [];\n\treturn recommendForShape(shape);\n}\n\nexport function recommendForShape(shape: Omit<ChartTableShape, 'headerRow' | 'byRows'> & Partial<ChartTableShape>): ChartRecommendation[] {\n\tconst out: ChartRecommendation[] = [];\n\tconst add = (type: ChartType, label: string, reason: string, stacking?: ChartStacking) => out.push({ type, label, reason, ...(stacking ? { stacking } : {}) });\n\tif (shape.series === 2 && !shape.labelColumn && !shape.byRows) {\n\t\tadd('scatter', 'Scatter', 'Two numeric columns without labels: the first is x, the second y.');\n\t\tadd('line', 'Line', 'Shows the second column in order.');\n\t\tadd('bar', 'Column', 'Compares the values side by side.');\n\t\treturn out;\n\t}\n\tif (shape.series === 1 && !shape.labelColumn && shape.points > 20) {\n\t\tadd('histogram', 'Histogram', 'Many unlabelled values: shows how they are distributed.');\n\t\tadd('box', 'Box plot', 'Summarises the spread: quartiles, median and outliers.');\n\t\tadd('line', 'Line', 'Shows the values in order.');\n\t\treturn out;\n\t}\n\tif (shape.dates) {\n\t\tadd('line', 'Line', 'The categories are dates: a line shows change over time.');\n\t\tadd('area', 'Area', 'Shows change over time with volume.');\n\t\tadd('bar', 'Column', 'Compares each period.');\n\t\tif (shape.series > 1) add('area', 'Stacked area', 'Shows how the parts add up over time.', 'stacked');\n\t\treturn out;\n\t}\n\tif (shape.series === 1) {\n\t\tif (shape.points > 12) {\n\t\t\tadd('line', 'Line', 'One long series: a line shows its shape.');\n\t\t\tadd('bar', 'Column', 'Compares every value.');\n\t\t\tadd('area', 'Area', 'Emphasises the volume under the series.');\n\t\t} else {\n\t\t\tadd('bar', 'Column', 'One short series: columns compare the values.');\n\t\t\tif (shape.mixedSigns) add('waterfall', 'Waterfall', 'Positive and negative values: shows how they add up to a total.');\n\t\t\tadd('bar', 'Bar', 'Horizontal bars fit long category names.');\n\t\t\tif (shape.nonNegative && shape.points >= 2) {\n\t\t\t\tadd('pie', 'Pie', 'Shares of a whole (all values are positive).');\n\t\t\t\tadd('donut', 'Donut', 'Shares of a whole with the total in the middle.');\n\t\t\t\tif (shape.points >= 5) add('treemap', 'Treemap', 'Compares many shares by area.');\n\t\t\t\tadd('funnel', 'Funnel', 'Shows stages that narrow down.');\n\t\t\t}\n\t\t\tadd('line', 'Line', 'Shows the values in order.');\n\t\t}\n\t\treturn out;\n\t}\n\tif (shape.points > 12) {\n\t\tadd('line', 'Line', 'Several long series: lines keep them readable.');\n\t\tadd('bar', 'Column', 'Compares the series at each category.');\n\t\tadd('area', 'Area', 'Emphasises volume.');\n\t\tadd('bar', 'Stacked column', 'Shows how the series add up.', 'stacked');\n\t} else {\n\t\tadd('bar', 'Column', 'Several series: clustered columns compare them per category.');\n\t\tadd('bar', 'Bar', 'Horizontal bars fit long category names.');\n\t\tadd('bar', 'Stacked column', 'Shows how the series add up.', 'stacked');\n\t\tadd('line', 'Line', 'Shows the series in order.');\n\t\tif (shape.points >= 3 && shape.series <= 6) add('radar', 'Radar', 'Compares several measures across the series.');\n\t}\n\treturn out;\n}\n\nexport interface ChartFromTable {\n\ttype: ChartType;\n\tstacking: ChartStacking;\n\tcategories: string[];\n\tseries: ChartSeries[];\n\tissues: ChartIssue[];\n\tshape: ChartTableShape;\n}\n\n/**\n * Builds chart data from a block of cells (CSV, a clipboard grid or a spreadsheet range) using\n * the spreadsheet conventions of `analyzeChartTable`. `type: 'auto'` (the default) takes the\n * first recommendation. A scatter chart of a block without labels takes the first column as\n * the x values of the others.\n */\nexport function chartFromTable(rows: ReadonlyArray<ReadonlyArray<unknown>>, options: { type?: ChartType | 'auto' } = {}): ChartFromTable {\n\tconst shape = analyzeChartTable(rows);\n\tconst rec = (options.type ?? 'auto') === 'auto' ? recommendForShape(shape)[0] : undefined;\n\tconst type = rec?.type ?? (options.type === 'auto' || !options.type ? 'bar' : options.type);\n\tconst stacking = rec?.stacking ?? 'none';\n\tconst grid = rows.filter((r) => r.some((c) => !blank(c))).map((r) => [...r]);\n\t// Without a header row, invent one so chartDataFromTable reads every row as data.\n\tconst width = Math.max(0, ...grid.map((r) => r.length));\n\tlet table = grid;\n\tif (!shape.labelColumn) table = table.map((r, i) => [shape.headerRow && i === 0 ? '' : String(i + (shape.headerRow ? 0 : 1)), ...r]);\n\tif (!shape.headerRow) table = [['', ...Array.from({ length: width }, (_, i) => `Series ${i + 1}`)], ...table];\n\tconst xFromFirst = type === 'scatter' && !shape.labelColumn && !shape.byRows && shape.series > 1;\n\tif (xFromFirst) {\n\t\t// The first data column becomes x: move it into the label column.\n\t\ttable = table.map((r) => [r[1], ...r.slice(2)]);\n\t}\n\tconst data = chartDataFromTable(table, { seriesIn: shape.byRows ? 'rows' : 'columns', header: true, xFromFirstColumn: xFromFirst });\n\treturn { type, stacking, categories: data.categories, series: data.series, issues: data.issues, shape };\n}\n","import type { CommandSpec } from '../commands/registry.js';\nimport { parseCsv } from '../spreadsheet/csv.js';\nimport { checkChartColors } from './color.js';\nimport type { ChartController, ChartSpecPatch } from './controller.js';\nimport { chartFromMermaid, chartToMermaid } from './mermaid.js';\nimport { chartToOoxml } from './ooxml.js';\nimport { CHART_COLOR_SCHEMES, CHART_LAYOUT_PRESETS } from './presets.js';\nimport { recommendChartTypes } from './recommend.js';\nimport { CATEGORY_REF, CHART_UPDATE_PROPERTIES, HEIGHT, SERIES_PROPS, SERIES_REF, TRENDLINE_PROPS, VALUE, WIDTH } from './schemas.js';\nimport { chartColorsByCategory, chartDataToTable, chartSeriesColor, chartSliceColor } from './spec.js';\nimport { summarizeChart } from './summary.js';\nimport { chartToSvg } from './svg.js';\nimport type { ChartTrendline } from './types.js';\n\nexport interface ChartCommandOptions {\n\t/** Id prefix (default `chart.`); use one per chart when several are registered. */\n\tprefix?: string;\n\t/** Palette group (default `Chart`). */\n\tgroup?: string;\n\t/** Command scope. Omit for global commands. */\n\tscope?: string;\n}\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nconst check = (result: { ok: boolean; message?: string }) => {\n\tif (!result.ok) fail(result.message ?? 'The change was rejected.');\n};\n\n/**\n * Palette and agent commands for a chart: describe, update presentation, replace data, set\n * values, add / remove series, categories and trendlines, apply presets, switch rows and\n * columns, import CSV or Mermaid, export SVG, Mermaid or Office XML, recommend types and\n * check colours. Register them in a `CommandRegistry` and agents get them through\n * `createCommandToolProvider`; `createChartToolProvider` offers the same operations as\n * individual tools. Failures throw sentences, which the registry returns as\n * `{ ok: false, code: 'failed', message }`.\n */\nexport function createChartCommands(controller: ChartController, options: ChartCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'chart.';\n\tconst base = { group: options.group ?? 'Chart', ...(options.scope ? { scope: options.scope } : {}) };\n\tconst seriesIds = () => controller.getSpec().series.map((s) => s.id);\n\tconst resolveSeries = (ref: string) => {\n\t\tconst spec = controller.getSpec();\n\t\tconst series = spec.series.find((s) => s.id === ref) ?? spec.series.find((s) => s.name === ref);\n\t\tif (!series) fail(`There is no series \"${ref}\"; expected one of ${seriesIds().map((id) => `\"${id}\"`).join(', ') || '(none yet)'}.`);\n\t\treturn series!;\n\t};\n\tconst resolveCategory = (ref: string | number) => {\n\t\tconst categories = controller.getSpec().categories;\n\t\tconst index = typeof ref === 'number' ? ref : categories.indexOf(ref);\n\t\tif (index < 0 || index >= categories.length || !Number.isInteger(index)) fail(`There is no category ${JSON.stringify(ref)}; expected an index from 0 to ${categories.length - 1} or one of the labels.`);\n\t\treturn index;\n\t};\n\tconst object = (properties: Record<string, unknown>, required?: string[]) => ({ type: 'object' as const, properties, ...(required ? { required } : {}), additionalProperties: false }) as any;\n\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}describe`,\n\t\t\tlabel: 'Describe Chart',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'data', 'spec', 'get', 'summary'],\n\t\t\tdescription: 'Returns the chart spec, its data as a table (series names in the header row) and a summary: per-series min / max / mean / trend, axes as drawn, layout warnings and a colour check.',\n\t\t\tparams: object({ width: WIDTH, height: HEIGHT }),\n\t\t\trun: (_ctx: unknown, params: { width?: number; height?: number } = {}) => {\n\t\t\t\tconst spec = controller.getSpec();\n\t\t\t\treturn { spec: controller.toJSON(), table: chartDataToTable(spec), summary: summarizeChart(controller.toJSON(), { width: params?.width ?? 640, height: params?.height ?? 400 }), issues: controller.getState().issues };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}update`,\n\t\t\tlabel: 'Change Chart…',\n\t\t\tkeywords: ['chart', 'title', 'axis', 'legend', 'stack', 'style', 'format', 'type'],\n\t\t\tdescription:\n\t\t\t\t'Changes chart presentation as one undo step: type, titles, axes (xAxis = categories, yAxis = values, yAxis2 = secondary values), legend, stacking, orientation, curve, points, data labels, palette, donut hole, bar spacing, histogram bins or waterfall total. Invalid values change nothing and return why.',\n\t\t\tparams: object(CHART_UPDATE_PROPERTIES),\n\t\t\trun: (_ctx: unknown, params: ChartSpecPatch) => {\n\t\t\t\tcheck(controller.update(params));\n\t\t\t\treturn { spec: controller.toJSON() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setData`,\n\t\t\tlabel: 'Replace Chart Data…',\n\t\t\tkeywords: ['chart', 'data', 'series', 'categories'],\n\t\t\tdescription: 'Replaces the categories and series as one undo step. Each series has one value per category (padded with gaps).',\n\t\t\tparams: object({\n\t\t\t\tcategories: { type: 'array', items: { type: 'string' }, description: 'Category labels in order.' },\n\t\t\t\tseries: { type: 'array', description: 'The new series.', items: object({ id: { type: 'string', description: 'Stable id (optional).' }, ...SERIES_PROPS }, ['name', 'values']) }\n\t\t\t}),\n\t\t\trun: (_ctx: unknown, params: { categories?: string[]; series?: any[] }) => {\n\t\t\t\tcheck(controller.setData(params));\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setValues`,\n\t\t\tlabel: 'Set Chart Values…',\n\t\t\tkeywords: ['chart', 'value', 'cell', 'edit'],\n\t\t\tdescription: 'Sets individual values as one undo step. Series by id or name; category by index or label.',\n\t\t\tparams: object({ cells: { type: 'array', minItems: 1, description: 'Values to set.', items: object({ series: SERIES_REF, category: CATEGORY_REF, value: VALUE }, ['series', 'category', 'value']) } }, ['cells']),\n\t\t\trun: (_ctx: unknown, params: { cells: { series: string; category: string | number; value: unknown }[] }) => {\n\t\t\t\tcheck(controller.setValues(params.cells.map((c) => ({ seriesId: resolveSeries(c.series).id, index: resolveCategory(c.category), value: c.value }))));\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addSeries`,\n\t\t\tlabel: 'Add Series',\n\t\t\tkeywords: ['chart', 'series', 'new'],\n\t\t\tdescription: 'Adds a series (default: an empty one at the end). Returns its id.',\n\t\t\tparams: object({ ...SERIES_PROPS, id: { type: 'string', description: 'Id to use (default series-N).' }, at: { type: 'integer', minimum: 0, description: 'Position (default: last).' } }),\n\t\t\trun: (_ctx: unknown, params: { at?: number; name?: string; values?: unknown[] } = {}) => {\n\t\t\t\tconst { at, ...input } = params ?? {};\n\t\t\t\tconst clean = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== null));\n\t\t\t\tconst result = controller.addSeries(clean as any, { at });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { id: (result as { id: string }).id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}updateSeries`,\n\t\t\tlabel: 'Change Series…',\n\t\t\tkeywords: ['chart', 'series', 'rename', 'colour', 'color', 'hide', 'axis', 'marker'],\n\t\t\tdescription: 'Renames, recolours, hides, moves to the secondary axis or changes how a series is drawn (null resets a field).',\n\t\t\tparams: object({ series: SERIES_REF, ...Object.fromEntries(Object.entries(SERIES_PROPS).filter(([k]) => k !== 'values')) }, ['series']),\n\t\t\trun: (_ctx: unknown, params: { series: string } & Record<string, unknown>) => {\n\t\t\t\tconst { series, ...patch } = params;\n\t\t\t\tconst id = resolveSeries(series).id;\n\t\t\t\tcheck(controller.updateSeries(id, patch as any));\n\t\t\t\treturn { series: controller.getSeries(id) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeSeries`,\n\t\t\tlabel: 'Delete Series',\n\t\t\tkeywords: ['chart', 'series', 'remove'],\n\t\t\tdescription: 'Deletes a series by id or name.',\n\t\t\tparams: object({ series: SERIES_REF }, ['series']),\n\t\t\trun: (_ctx: unknown, params: { series: string }) => {\n\t\t\t\tcheck(controller.removeSeries(resolveSeries(params.series).id));\n\t\t\t\treturn { series: seriesIds() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addCategory`,\n\t\t\tlabel: 'Add Category',\n\t\t\tkeywords: ['chart', 'category', 'row', 'label'],\n\t\t\tdescription: 'Inserts a category (gaps in every series) at `at` (default: the end).',\n\t\t\tparams: object({ label: { type: 'string', description: 'Category label (default: its number).' }, at: { type: 'integer', minimum: 0, description: 'Index to insert at (default: the end).' } }),\n\t\t\trun: (_ctx: unknown, params: { label?: string; at?: number } = {}) => controller.addCategory(params?.label, { at: params?.at })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeCategory`,\n\t\t\tlabel: 'Delete Category',\n\t\t\tkeywords: ['chart', 'category', 'row', 'remove'],\n\t\t\tdescription: 'Deletes a category (and its values) by index or label.',\n\t\t\tparams: object({ category: CATEGORY_REF }, ['category']),\n\t\t\trun: (_ctx: unknown, params: { category: string | number }) => {\n\t\t\t\tcheck(controller.removeCategory(resolveCategory(params.category)));\n\t\t\t\treturn { categories: controller.getSpec().categories };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addTrendline`,\n\t\t\tlabel: 'Add Trendline…',\n\t\t\tkeywords: ['chart', 'trend', 'regression', 'fit', 'forecast', 'moving average'],\n\t\t\tdescription: 'Fits a trendline to a series (linear, exponential, logarithmic, power, polynomial or moving average). Returns its index and the fit.',\n\t\t\tparams: object({ series: SERIES_REF, ...TRENDLINE_PROPS }, ['series', 'type']),\n\t\t\trun: (_ctx: unknown, params: { series: string } & ChartTrendline) => {\n\t\t\t\tconst { series, ...line } = params;\n\t\t\t\tconst result = controller.addTrendline(resolveSeries(series).id, line);\n\t\t\t\tcheck(result);\n\t\t\t\tconst ok = result as { index: number; fit: { coefficients: number[]; r2: number | null; equation: string } | null };\n\t\t\t\treturn { index: ok.index, ...(ok.fit ? { coefficients: ok.fit.coefficients, r2: ok.fit.r2, equation: ok.fit.equation } : {}) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeTrendline`,\n\t\t\tlabel: 'Delete Trendline',\n\t\t\tkeywords: ['chart', 'trend', 'remove'],\n\t\t\tdescription: 'Deletes a trendline from a series.',\n\t\t\tparams: object({ series: SERIES_REF, index: { type: 'integer', minimum: 0, description: 'Trendline index (0 = first).' } }, ['series', 'index']),\n\t\t\trun: (_ctx: unknown, params: { series: string; index: number }) => {\n\t\t\t\tcheck(controller.removeTrendline(resolveSeries(params.series).id, params.index));\n\t\t\t\treturn { trendlines: controller.getSeries(resolveSeries(params.series).id)?.trendlines ?? [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}applyPreset`,\n\t\t\tlabel: 'Apply Chart Style…',\n\t\t\tkeywords: ['chart', 'quick layout', 'style', 'colours', 'colors', 'monochrome', 'theme'],\n\t\t\tdescription: 'Applies a quick layout and / or colour scheme as one undo step.',\n\t\t\tparams: object({\n\t\t\t\tlayout: { type: 'string', enum: CHART_LAYOUT_PRESETS.map((p) => p.id), description: 'Quick layout id.' },\n\t\t\t\tcolors: { type: 'string', enum: CHART_COLOR_SCHEMES.map((p) => p.id), description: 'Colour scheme id.' }\n\t\t\t}),\n\t\t\trun: (_ctx: unknown, params: { layout?: string; colors?: string } = {}) => {\n\t\t\t\tcheck(controller.applyPreset(params ?? {}));\n\t\t\t\treturn { spec: controller.toJSON() };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transpose`,\n\t\t\tlabel: 'Switch Rows and Columns',\n\t\t\tkeywords: ['chart', 'transpose', 'swap', 'rows', 'columns', 'series'],\n\t\t\tdescription: 'Swaps series and categories as one undo step.',\n\t\t\trun: () => {\n\t\t\t\tcheck(controller.transpose());\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importCsv`,\n\t\t\tlabel: 'Import Chart Data from CSV…',\n\t\t\tkeywords: ['chart', 'csv', 'tsv', 'paste', 'import'],\n\t\t\tdescription: 'Replaces the data with CSV / TSV text: by default the first column holds categories and the first row series names.',\n\t\t\tparams: object(\n\t\t\t\t{\n\t\t\t\t\tcsv: { type: 'string', description: 'CSV or TSV text.' },\n\t\t\t\t\tseriesIn: { type: 'string', enum: ['columns', 'rows'], description: 'Series run down columns (default) or along rows.' },\n\t\t\t\t\theader: { type: ['boolean', 'string'], enum: [true, false, 'auto'], description: 'The first row holds series names (default true).' }\n\t\t\t\t},\n\t\t\t\t['csv']\n\t\t\t),\n\t\t\trun: (_ctx: unknown, params: { csv: string; seriesIn?: 'columns' | 'rows'; header?: boolean | 'auto' }) => {\n\t\t\t\tconst result = controller.importCsv(params.csv, { seriesIn: params.seriesIn, header: params.header });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { table: chartDataToTable(controller.getSpec()), issues: result.issues ?? [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importMermaid`,\n\t\t\tlabel: 'Import Mermaid Chart…',\n\t\t\tkeywords: ['chart', 'mermaid', 'markdown', 'xychart', 'pie', 'radar', 'import'],\n\t\t\tdescription: 'Replaces the chart with Mermaid xychart-beta, pie or radar-beta text (one undo step). Unreadable lines are listed with line numbers.',\n\t\t\tparams: object({ mermaid: { type: 'string', description: 'Mermaid text.' } }, ['mermaid']),\n\t\t\trun: (_ctx: unknown, params: { mermaid: string }) => {\n\t\t\t\tconst read = chartFromMermaid(params.mermaid);\n\t\t\t\tif (!read.family) fail(read.issues.map((i) => i.message).join(' ') || 'Expected Mermaid starting with xychart-beta, pie or radar-beta.');\n\t\t\t\tcheck(controller.update({ ...read.spec } as ChartSpecPatch, { label: 'Import Mermaid chart' }));\n\t\t\t\treturn { spec: controller.toJSON(), issues: read.issues };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportMermaid`,\n\t\t\tlabel: 'Copy Chart as Mermaid',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'mermaid', 'markdown', 'export'],\n\t\t\tdescription: 'Returns the chart as Mermaid text (with a round-trip comment unless meta is false).',\n\t\t\tparams: object({ meta: { type: 'boolean', description: 'Include the %% @pixerate round-trip comment (default true).' } }),\n\t\t\trun: (_ctx: unknown, params: { meta?: boolean } = {}) => ({ mermaid: chartToMermaid(controller.toJSON(), { meta: params?.meta }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportOoxml`,\n\t\t\tlabel: 'Export Chart as Office XML',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'office', 'word', 'powerpoint', 'docx', 'pptx', 'xml', 'export'],\n\t\t\tdescription: 'Returns the chart as a DrawingML chart part (c:chartSpace) and what could not be written.',\n\t\t\trun: () => chartToOoxml(controller.toJSON())\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportSvg`,\n\t\t\tlabel: 'Export Chart as SVG',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'svg', 'export', 'image'],\n\t\t\tdescription: 'Returns the chart drawn as a standalone, accessible SVG string (with <title> and <desc>).',\n\t\t\tparams: object({ width: WIDTH, height: HEIGHT }),\n\t\t\trun: (_ctx: unknown, params: { width?: number; height?: number } = {}) => ({\n\t\t\t\tsvg: chartToSvg(controller.toJSON(), { width: params?.width ?? 640, height: params?.height ?? 400 })\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}recommend`,\n\t\t\tlabel: 'Recommend Chart Types',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'recommend', 'suggest', 'type'],\n\t\t\tdescription: 'Suggests chart types for the current data (or CSV), best first, each with a reason.',\n\t\t\tparams: object({ csv: { type: 'string', description: 'CSV text to analyse instead of the current data.' } }),\n\t\t\trun: (_ctx: unknown, params: { csv?: string } = {}) => ({\n\t\t\t\trecommendations: recommendChartTypes(params?.csv !== undefined ? parseCsv(params.csv) : chartDataToTable(controller.getSpec()))\n\t\t\t})\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}checkColors`,\n\t\t\tlabel: 'Check Chart Colours',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['chart', 'colour', 'color', 'accessibility', 'colour-blind', 'contrast'],\n\t\t\tdescription: 'Checks that the series colours can be told apart (including with colour-blindness) and stand out from the background.',\n\t\t\trun: () => {\n\t\t\t\tconst s = controller.getSpec();\n\t\t\t\tconst visible = s.series.filter((x) => !x.hidden);\n\t\t\t\tconst colors = chartColorsByCategory(s.type) ? s.categories.map((_, i) => visible[0]?.pointColors?.[i] || chartSliceColor(s, i)) : visible.map((x) => chartSeriesColor(s, s.series.indexOf(x)));\n\t\t\t\treturn { colors, ...checkChartColors(colors) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}undo`,\n\t\t\tlabel: 'Undo Chart Edit',\n\t\t\tkeywords: ['chart', 'undo'],\n\t\t\tenabled: () => controller.getState().canUndo || 'Nothing to undo',\n\t\t\trun: () => ({ undone: controller.undo() })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}redo`,\n\t\t\tlabel: 'Redo Chart Edit',\n\t\t\tkeywords: ['chart', 'redo'],\n\t\t\tenabled: () => controller.getState().canRedo || 'Nothing to redo',\n\t\t\trun: () => ({ redone: controller.redo() })\n\t\t}\n\t];\n}\n","// Drag behaviour follows effectcraft-main/crates/ui-egui/src/panels/graph.rs and graph_tools.rs (the value axis\n// is frozen while a key is dragged, Shift locks to the axis that moved most, `snap_px` picks the nearest\n// candidate within a few screen pixels) and lightcraft-main's curve tests (Alt moves a tenth as far)\n// (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport type { ChartController } from './controller.js';\nimport { chartValueAtPoint, chartXAtPoint, snapChartValue } from './layout.js';\nimport { linearMap } from './scale.js';\nimport { chartFamily } from './spec.js';\nimport type { ChartScene, ChartSelection, ChartValueScale } from './types.js';\n\n/** Scene coordinates of a pointer, given the rendered element's box (the scene is scaled to fit it). */\nexport function chartClientToScene(scene: Pick<ChartScene, 'width' | 'height'>, box: { left: number; top: number; width: number; height: number }, clientX: number, clientY: number): { x: number; y: number } {\n\tconst sx = box.width ? scene.width / box.width : 1;\n\tconst sy = box.height ? scene.height / box.height : 1;\n\treturn { x: (clientX - box.left) * sx, y: (clientY - box.top) * sy };\n}\n\n/**\n * Whether a point can be dragged to a new value in this scene: bar, line, area and scatter\n * charts (not percent-stacked), scatter and bubble charts with x values (x and y), and\n * waterfall steps. Hidden series and gaps cannot be dragged.\n */\nexport function canDragChartPoint(controller: ChartController, scene: ChartScene, target: ChartSelection | undefined): target is Extract<ChartSelection, { kind: 'point' }> {\n\tif (target?.kind !== 'point' || !scene.valueScale || scene.percent) return false;\n\tconst spec = controller.getSpec();\n\tconst family = chartFamily(spec);\n\tif (family !== 'cartesian' && family !== 'xy' && family !== 'waterfall') return false;\n\tconst series = controller.getSeries(target.seriesId);\n\treturn !!series && !series.hidden && series.values[target.index] !== null;\n}\n\nexport interface ChartDragMoveOptions {\n\t/** Move a tenth as far as the pointer (fine adjustment; Alt). */\n\tfine?: boolean;\n\t/** Only change the axis the pointer has moved along most (scatter charts; Shift). */\n\tlockAxis?: boolean;\n\t/** Skip snapping to nearby values and ticks (e.g. while Ctrl / Cmd is held). */\n\tnoSnap?: boolean;\n}\n\nexport interface ChartPointDrag {\n\t/**\n\t * The value axis range when the drag started. Pass it to `layoutChart` (`valueDomain`)\n\t * until `end()` so the axis does not rescale under the pointer.\n\t */\n\treadonly valueDomain: { min: number; max: number };\n\t/** The secondary value axis range when the drag started (`layoutChart`'s `valueDomain2`). */\n\treadonly valueDomain2?: { min: number; max: number };\n\t/** The numeric x range of a scatter or bubble chart when the drag started (`xDomain`). */\n\treadonly xDomain?: { min: number; max: number };\n\t/** The point being dragged, for `layoutChart`'s `readout`. */\n\treadonly target: { seriesId: string; index: number };\n\t/** Moves the value with the pointer (scene coordinates). */\n\tmove(point: { x: number; y: number }, options?: ChartDragMoveOptions): void;\n\t/** Ends the drag (one undo step for the whole drag). */\n\tend(): void;\n\t/** Cancels the drag: the value goes back and no undo step is left (Escape). */\n\tcancel(): void;\n}\n\nexport interface ChartSnapOptions {\n\t/** Values to snap to when the pointer is within `tolerancePx` of them. */\n\tcandidates?: readonly number[];\n\t/** Screen distance that snaps (default 6). */\n\ttolerancePx?: number;\n\t/** Fallback step when no candidate is close (default: a tenth of the tick step). */\n\tstep?: number;\n\t/** The scale the value is on (default: the scene's value scale). */\n\tscale?: ChartValueScale;\n}\n\n/**\n * Snaps a dragged value: to the nearest candidate (other series at the same category, the\n * neighbouring values, zero, the start value, ticks) within `tolerancePx` screen pixels, or\n * else to a tenth of the tick step.\n */\nexport function snapChartDragValue(scene: ChartScene, value: number, options: ChartSnapOptions = {}): number {\n\tconst scale = options.scale ?? scene.valueScale;\n\tconst tolerance = options.tolerancePx ?? 6;\n\tif (scale) {\n\t\tconst px = (v: number) => linearMap(v, scale.domain, scale.range);\n\t\tconst at = px(value);\n\t\tlet best: number | null = null;\n\t\tlet bestDist = tolerance;\n\t\tfor (const c of [...(options.candidates ?? []), ...scale.ticks]) {\n\t\t\tif (!Number.isFinite(c)) continue;\n\t\t\tconst d = Math.abs(px(c) - at);\n\t\t\tif (d <= bestDist) {\n\t\t\t\tbest = c;\n\t\t\t\tbestDist = d;\n\t\t\t}\n\t\t}\n\t\tif (best !== null) return best;\n\t}\n\treturn snapChartValue(scene, value, options.step, scale?.ticks);\n}\n\n/**\n * Starts dragging a bar or point: the value follows the pointer along its value axis (and\n * along x on scatter and bubble charts), snapped to nearby values and then to a tenth of the\n * tick step (`step` overrides), and the whole drag is one undo step. Works for stacked bars\n * too (the drag changes the segment by the distance moved). Returns `null` when the target\n * cannot be dragged.\n */\nexport function startChartPointDrag(controller: ChartController, scene: ChartScene, target: ChartSelection | undefined, start: { x: number; y: number }, options: { step?: number; tolerancePx?: number } = {}): ChartPointDrag | null {\n\tif (!canDragChartPoint(controller, scene, target)) return null;\n\tconst { seriesId, index } = target;\n\tconst spec = controller.getSpec();\n\tconst series = controller.getSeries(seriesId)!;\n\tconst secondary = series.axis === 'secondary' && !!scene.valueScale2;\n\tconst scale = secondary ? scene.valueScale2! : scene.valueScale!;\n\tconst xy = chartFamily(spec) === 'xy' && !!scene.xScale;\n\tconst startValue = series.values[index] ?? 0;\n\tconst startX = series.x?.[index] ?? null;\n\tconst startAt = chartValueAtPoint(scene, start, secondary);\n\tconst startAtX = xy ? chartXAtPoint(scene, start) : undefined;\n\tif (startAt === undefined) return null;\n\t// Nearby values worth snapping to: zero, where the drag started, other series at this\n\t// category and this series' neighbours.\n\tconst candidates = [0, startValue];\n\tif (!xy) {\n\t\tfor (const s of spec.series) if (s.id !== seriesId && !s.hidden && (s.axis === 'secondary') === secondary) candidates.push(s.values[index] ?? NaN);\n\t\tcandidates.push(series.values[index - 1] ?? NaN, series.values[index + 1] ?? NaN);\n\t}\n\tcontroller.beginGesture(`drag:${seriesId}:${index}`);\n\tlet ended = false;\n\tconst [min, max] = scene.valueScale!.domain;\n\tconst label = `Drag ${series.name}`;\n\treturn {\n\t\tvalueDomain: { min, max },\n\t\t...(scene.valueScale2 ? { valueDomain2: { min: scene.valueScale2.domain[0], max: scene.valueScale2.domain[1] } } : {}),\n\t\t...(xy ? { xDomain: { min: scene.xScale!.domain[0], max: scene.xScale!.domain[1] } } : {}),\n\t\ttarget: { seriesId, index },\n\t\tmove(point, moveOptions = {}) {\n\t\t\tif (ended) return;\n\t\t\tconst at = chartValueAtPoint(scene, point, secondary);\n\t\t\tif (at === undefined) return;\n\t\t\tconst factor = moveOptions.fine ? 0.1 : 1;\n\t\t\tlet dy = (at - startAt) * factor;\n\t\t\tlet dx = 0;\n\t\t\tif (xy && startX !== null && startAtX !== undefined) {\n\t\t\t\tconst atX = chartXAtPoint(scene, point);\n\t\t\t\tif (atX !== undefined) dx = (atX - startAtX) * factor;\n\t\t\t\tif (moveOptions.lockAxis) {\n\t\t\t\t\t// Keep the axis the pointer moved further along (in pixels).\n\t\t\t\t\tif (Math.abs(point.x - start.x) >= Math.abs(point.y - start.y)) dy = 0;\n\t\t\t\t\telse dx = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst snap = (v: number, s: ChartValueScale, c: readonly number[]) => {\n\t\t\t\tif (moveOptions.noSnap) return Number(v.toPrecision(12));\n\t\t\t\tif (moveOptions.fine) {\n\t\t\t\t\tconst unit = options.step ? options.step / 10 : s.ticks.length > 1 ? (s.ticks[1] - s.ticks[0]) / 100 : undefined;\n\t\t\t\t\treturn snapChartValue(scene, v, unit, s.ticks);\n\t\t\t\t}\n\t\t\t\treturn snapChartDragValue(scene, v, { candidates: c, tolerancePx: options.tolerancePx, step: options.step, scale: s });\n\t\t\t};\n\t\t\tconst y = snap(startValue + dy, scale, candidates);\n\t\t\tif (xy && startX !== null) {\n\t\t\t\tconst x = dx !== 0 ? snap(startX + dx, scene.xScale!, [0, startX]) : startX;\n\t\t\t\tconst xs = [...(series.x ?? [])];\n\t\t\t\txs[index] = x;\n\t\t\t\tcontroller.setValue(seriesId, index, y, { label });\n\t\t\t\tif (x !== controller.getSeries(seriesId)?.x?.[index]) controller.updateSeries(seriesId, { x: xs });\n\t\t\t} else controller.setValue(seriesId, index, y, { label });\n\t\t},\n\t\tend() {\n\t\t\tif (ended) return;\n\t\t\tended = true;\n\t\t\tcontroller.endGesture();\n\t\t},\n\t\tcancel() {\n\t\t\tif (ended) return;\n\t\t\tended = true;\n\t\t\tcontroller.cancelGesture();\n\t\t}\n\t};\n}\n\nexport interface ChartKeyInput {\n\tkey: string;\n\tshiftKey?: boolean;\n\taltKey?: boolean;\n\tmetaKey?: boolean;\n\tctrlKey?: boolean;\n}\n\n/**\n * Keyboard editing on a focused chart: arrows move a point selection between categories\n * (← →) and change its value (↑ ↓, a tenth of the tick step; Shift: a whole step; Alt: a\n * hundredth), Delete / Backspace deletes the selection, Escape cancels a drag or clears the\n * selection. Returns `true` when the key was used (call `preventDefault`).\n */\nexport function handleChartKey(controller: ChartController, scene: ChartScene | null, event: ChartKeyInput): boolean {\n\tif (event.metaKey || event.ctrlKey) return false;\n\tconst { selection, spec, gesture } = controller.getState();\n\tswitch (event.key) {\n\t\tcase 'Escape':\n\t\t\tif (gesture) {\n\t\t\t\tcontroller.cancelGesture();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (!selection) return false;\n\t\t\tcontroller.select(null);\n\t\t\treturn true;\n\t\tcase 'Delete':\n\t\tcase 'Backspace':\n\t\t\tif (event.altKey || !selection || selection.kind === 'chart') return false;\n\t\t\tcontroller.deleteSelection();\n\t\t\treturn true;\n\t\tcase 'ArrowLeft':\n\t\tcase 'ArrowRight': {\n\t\t\tif (event.altKey || (selection?.kind !== 'point' && selection?.kind !== 'category')) return false;\n\t\t\tconst n = spec.categories.length;\n\t\t\tconst index = Math.max(0, Math.min(n - 1, selection.index + (event.key === 'ArrowRight' ? 1 : -1)));\n\t\t\tcontroller.select({ ...selection, index });\n\t\t\treturn true;\n\t\t}\n\t\tcase 'ArrowUp':\n\t\tcase 'ArrowDown': {\n\t\t\tif (selection?.kind !== 'point' || scene?.percent) return false;\n\t\t\tconst secondary = controller.getSeries(selection.seriesId)?.axis === 'secondary';\n\t\t\tconst ticks = (secondary ? scene?.valueScale2 : null)?.ticks ?? scene?.valueScale?.ticks ?? [];\n\t\t\tconst step = ticks.length > 1 ? ticks[1] - ticks[0] : 1;\n\t\t\tconst amount = event.shiftKey ? step : event.altKey ? step / 100 : step / 10;\n\t\t\tcontroller.nudgeValue(selection.seriesId, selection.index, amount * (event.key === 'ArrowUp' ? 1 : -1));\n\t\t\treturn true;\n\t\t}\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** A short description of the selection for an inspector heading or a screen reader. */\nexport function describeChartSelection(controller: ChartController, selection: ChartSelection | null = controller.getState().selection): string {\n\tif (!selection) return 'Nothing selected';\n\tconst spec = controller.getSpec();\n\tswitch (selection.kind) {\n\t\tcase 'chart':\n\t\t\treturn 'Chart';\n\t\tcase 'title':\n\t\t\treturn 'Title';\n\t\tcase 'subtitle':\n\t\t\treturn 'Subtitle';\n\t\tcase 'legend':\n\t\t\treturn 'Legend';\n\t\tcase 'axis':\n\t\t\treturn selection.axis === 'x' ? (chartFamily(spec) === 'xy' ? 'X axis' : 'Category axis') : selection.axis === 'y' ? 'Value axis' : 'Secondary value axis';\n\t\tcase 'series':\n\t\t\treturn `Series \"${controller.getSeries(selection.seriesId)?.name ?? selection.seriesId}\"`;\n\t\tcase 'category':\n\t\t\treturn `Category \"${spec.categories[selection.index] ?? selection.index}\"`;\n\t\tcase 'trendline': {\n\t\t\tconst series = controller.getSeries(selection.seriesId);\n\t\t\tconst line = series?.trendlines?.[selection.index];\n\t\t\treturn `${line ? line.type.replace('-', ' ') : 'Trendline'} trendline on \"${series?.name ?? selection.seriesId}\"`;\n\t\t}\n\t\tcase 'point': {\n\t\t\tconst series = controller.getSeries(selection.seriesId);\n\t\t\tconst value = series?.values[selection.index];\n\t\t\tconst x = series?.x?.[selection.index];\n\t\t\tif (x !== undefined && x !== null && chartFamily(spec) === 'xy') return `${series?.name ?? selection.seriesId}: (${x}, ${value ?? 'blank'})`;\n\t\t\treturn `${series?.name ?? selection.seriesId} · ${spec.categories[selection.index] ?? selection.index}: ${value ?? 'blank'}`;\n\t\t}\n\t}\n}\n\n/**\n * The mark under a scene point (topmost first), for hosts without DOM events and for agents\n * that drive the pointer: rects, circles, lines (within 4 px) and text boxes. Returns the\n * mark's `target`, or `{ kind: 'chart' }` over the background, or `null` outside.\n */\nexport function chartHitTest(scene: ChartScene, point: { x: number; y: number }, measure: (text: string, size: number, weight?: number) => number = (t, s, w = 400) => t.length * s * (w >= 600 ? 0.6 : 0.56)): ChartSelection | null {\n\tfor (let i = scene.marks.length - 1; i >= 0; i--) {\n\t\tconst m = scene.marks[i];\n\t\tif (!m.target || m.role === 'selection' || m.role === 'background') continue;\n\t\tlet hit = false;\n\t\tswitch (m.kind) {\n\t\t\tcase 'rect':\n\t\t\t\thit = point.x >= m.x && point.x <= m.x + m.width && point.y >= m.y && point.y <= m.y + m.height;\n\t\t\t\tbreak;\n\t\t\tcase 'circle':\n\t\t\t\thit = Math.hypot(point.x - m.cx, point.y - m.cy) <= Math.max(m.r, 4) + 2;\n\t\t\t\tbreak;\n\t\t\tcase 'line': {\n\t\t\t\tconst dx = m.x2 - m.x1;\n\t\t\t\tconst dy = m.y2 - m.y1;\n\t\t\t\tconst len2 = dx * dx + dy * dy;\n\t\t\t\tconst t = len2 ? Math.max(0, Math.min(1, ((point.x - m.x1) * dx + (point.y - m.y1) * dy) / len2)) : 0;\n\t\t\t\thit = Math.hypot(point.x - (m.x1 + t * dx), point.y - (m.y1 + t * dy)) <= 4;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'text': {\n\t\t\t\tif (m.rotate) break;\n\t\t\t\tconst w = measure(m.text, m.size, m.weight);\n\t\t\t\tconst x0 = m.anchor === 'start' ? m.x : m.anchor === 'end' ? m.x - w : m.x - w / 2;\n\t\t\t\tconst y0 = m.baseline === 'top' ? m.y : m.baseline === 'bottom' ? m.y - m.size : m.y - m.size / 2;\n\t\t\t\thit = point.x >= x0 - 2 && point.x <= x0 + w + 2 && point.y >= y0 - 2 && point.y <= y0 + m.size + 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\tif (hit) return m.target;\n\t}\n\treturn point.x >= 0 && point.y >= 0 && point.x <= scene.width && point.y <= scene.height ? { kind: 'chart' } : null;\n}\n","// The render-preview, pointer-gesture and key tools follow the conventions of the craft apps' MCP servers\n// (vectorcraft-main/crates/mcp/src/tools.rs `render_preview`, lightcraft-main `pointer_gesture`,\n// designcraft-main `key`) (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport type { AgentTool, AgentToolProvider } from '../tools/registry.js';\nimport type { JsonSchema } from '../tools/schema.js';\nimport { parseCsv } from '../spreadsheet/csv.js';\nimport { checkChartColors } from './color.js';\nimport type { ChartController, ChartSeriesPatch, ChartSpecPatch } from './controller.js';\nimport { chartHitTest, handleChartKey, startChartPointDrag } from './interaction.js';\nimport { layoutChart } from './layout.js';\nimport { chartFromMermaid, chartToMermaid } from './mermaid.js';\nimport { chartFromOoxml, chartToOoxml } from './ooxml.js';\nimport type { ChartDirector, ChartDirectorActor } from './presence.js';\nimport { CHART_COLOR_SCHEMES, CHART_LAYOUT_PRESETS } from './presets.js';\nimport { chartFromTable, recommendChartTypes } from './recommend.js';\nimport {\n\tparseChartValue,\n\tCHART_AXIS_KINDS,\n\tCHART_CURVES,\n\tCHART_LABEL_POSITIONS,\n\tCHART_LEGEND_POSITIONS,\n\tCHART_MARKERS,\n\tCHART_NUMBER_STYLES,\n\tCHART_ORIENTATIONS,\n\tCHART_SERIES_TYPES,\n\tCHART_STACKINGS,\n\tCHART_TRENDLINE_TYPES,\n\tCHART_TYPES,\n\tchartColorsByCategory,\n\tchartDataToTable,\n\tchartSeriesColor,\n\tchartSliceColor\n} from './spec.js';\nimport { AXIS, CATEGORY_REF, CHART_UPDATE_PROPERTIES, FORMAT, HEIGHT, SERIES_PROPS, SERIES_REF, TRENDLINE_PROPS, VALUE, WIDTH } from './schemas.js';\nimport { summarizeChart } from './summary.js';\nimport { chartToSvg } from './svg.js';\nimport type { ChartSelection, ChartTrendline } from './types.js';\n\ntype ParserCtor = { new (): DOMParser };\n\nexport interface ChartToolProviderOptions {\n\t/** Provider id (unique per registry). Default `chart`. */\n\tid?: string;\n\t/** Always prefix tool names with `<namespace>__`. */\n\tnamespace?: string;\n\t/**\n\t * The chart cannot be edited: write tools are hidden and `get_chart` says why. A string\n\t * is the reason (\"The report is locked\").\n\t */\n\treadOnly?: boolean | string | (() => boolean | string);\n\t/** Size used for summaries, previews and pointer gestures (default 640 × 400). */\n\tsize?: { width: number; height: number };\n\t/** Enables `import_chart_ooxml` (reading Office chart XML needs a DOMParser). Default: the global one, if any. */\n\tDOMParser?: ParserCtor;\n\t/**\n\t * Acts out `set_chart_values` and `select_chart_element` with a visible cursor (see\n\t * `ChartDirector`); each call is still one undo step. Without it, edits apply at once.\n\t */\n\tdirector?: ChartDirector;\n\t/** Who the cursor belongs to (default `{ id: 'agent', name: 'Agent' }`). */\n\tactor?: ChartDirectorActor;\n\t/** Turns SVG into an image so `render_chart` can return PNG (e.g. through a canvas). */\n\trasterize?: (svg: string, size: { width: number; height: number }) => Promise<{ data: string; mimeType: string }> | { data: string; mimeType: string };\n}\n\nconst READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;\nconst WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } as const;\nconst WRITE_IDEMPOTENT = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;\nconst DESTRUCTIVE = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false } as const;\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nfunction resolve<T>(result: { ok: boolean; message?: string } & T): T {\n\tif (!result.ok) fail(result.message ?? 'The change was rejected.');\n\treturn result;\n}\n\n/**\n * Agent tools for a chart editor, for a `ToolRegistry`: one tool per operation with strict\n * schemas. Reads (`get_chart`, `render_chart`, `check_chart_colors`, `recommend_chart`,\n * `get_chart_trendline`, `list_chart_presets`, `export_chart_mermaid`, `export_chart_ooxml`)\n * are always there; writes (data, series, categories, presentation, trendlines, presets,\n * imports, selection, pointer and key input, undo / redo) are hidden while the chart is\n * read-only. Every write is one undo step and returns what it changed.\n */\nexport function createChartToolProvider(controller: ChartController, options: ChartToolProviderOptions = {}): AgentToolProvider {\n\tconst size = options.size ?? { width: 640, height: 400 };\n\tconst readOnlyReason = (): string | null => {\n\t\tconst r = typeof options.readOnly === 'function' ? options.readOnly() : options.readOnly;\n\t\tif (!r) return null;\n\t\treturn typeof r === 'string' ? r : 'This chart is read-only.';\n\t};\n\tconst spec = () => controller.getSpec();\n\tconst seriesById = (ref: string) => {\n\t\tconst s = spec().series.find((x) => x.id === ref) ?? spec().series.find((x) => x.name === ref);\n\t\tif (!s) fail(`There is no series \"${ref}\"; expected one of ${spec().series.map((x) => `\"${x.id}\" (${x.name})`).join(', ') || '(none yet; add one with add_chart_series)'}.`);\n\t\treturn s!;\n\t};\n\tconst categoryIndex = (ref: string | number) => {\n\t\tconst categories = spec().categories;\n\t\tconst index = typeof ref === 'number' ? ref : categories.indexOf(ref);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= categories.length)\n\t\t\tfail(`There is no category ${JSON.stringify(ref)}; expected an index from 0 to ${categories.length - 1} or one of ${categories.slice(0, 20).map((c) => JSON.stringify(c)).join(', ')}.`);\n\t\treturn index;\n\t};\n\tconst table = () => chartDataToTable(spec());\n\tconst Parser = (): ParserCtor | undefined => options.DOMParser ?? (globalThis as { DOMParser?: ParserCtor }).DOMParser;\n\n\tconst getChart: AgentTool = {\n\t\tname: 'get_chart',\n\t\ttitle: 'Read the chart',\n\t\tdescription:\n\t\t\t'Returns the chart spec (type, titles, axes, legend, series with ids and settings), its data as a table (header row of series names, then one row per category), the current selection, and a summary at the given size: per-series min / max / mean / trend, the axes as drawn, layout warnings (hidden labels, thinned lines), a colour check and a plain-language description. Use the series ids and category indexes it returns with the write tools.',\n\t\tinputSchema: { type: 'object', properties: { width: WIDTH, height: HEIGHT }, additionalProperties: false },\n\t\tannotations: { title: 'Read the chart', ...READ },\n\t\thandler: ({ width = size.width, height = size.height }) => {\n\t\t\tconst reason = readOnlyReason();\n\t\t\treturn {\n\t\t\t\tspec: controller.toJSON(),\n\t\t\t\ttable: table(),\n\t\t\t\tselection: controller.getState().selection,\n\t\t\t\tsummary: summarizeChart(controller.toJSON(), { width, height }),\n\t\t\t\tissues: controller.getState().issues,\n\t\t\t\t...(reason ? { readOnly: reason } : {})\n\t\t\t};\n\t\t}\n\t};\n\n\tconst renderChart: AgentTool = {\n\t\tname: 'render_chart',\n\t\ttitle: 'Render the chart',\n\t\tdescription:\n\t\t\t'Draws the chart without changing it, to check it visually: SVG text by default, or a PNG image (format \"png\") when the host can rasterize. Look for overlapping or hidden labels; get_chart lists layout warnings without a render.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { width: WIDTH, height: HEIGHT, format: { type: 'string', enum: ['svg', 'png'], description: 'svg (default) or png (only when the host supports it).' } },\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Render the chart', ...READ },\n\t\thandler: async ({ width = size.width, height = size.height, format = 'svg' }) => {\n\t\t\tconst svg = chartToSvg(controller.toJSON(), { width, height });\n\t\t\tif (format === 'png') {\n\t\t\t\tif (!options.rasterize) fail('This host cannot rasterize charts; call render_chart with format \"svg\".');\n\t\t\t\tconst image = await options.rasterize!(svg, { width, height });\n\t\t\t\treturn { content: [{ type: 'image', data: image.data, mimeType: image.mimeType }], structuredContent: { width, height, mimeType: image.mimeType } };\n\t\t\t}\n\t\t\treturn { svg, width, height };\n\t\t}\n\t};\n\n\tconst checkColors: AgentTool = {\n\t\tname: 'check_chart_colors',\n\t\ttitle: 'Check chart colours',\n\t\tdescription:\n\t\t\t'Checks that colours can be told apart with normal vision and with protanopia, deuteranopia and tritanopia (OKLab distance after simulation), and that they stand out from the background. Checks the chart\\'s own series (or slice) colours unless colours are given. Returns the closest pair per vision, contrast ratios and problems as sentences.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcolors: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Colours to check instead of the chart\\'s (hex or rgb()).' },\n\t\t\t\tsurface: { type: 'string', description: 'Background colour (default white).' }\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Check chart colours', ...READ },\n\t\thandler: ({ colors, surface }) => {\n\t\t\tconst s = spec();\n\t\t\tconst visible = s.series.filter((x) => !x.hidden);\n\t\t\tconst own = chartColorsByCategory(s.type) ? s.categories.map((_, i) => visible[0]?.pointColors?.[i] || chartSliceColor(s, i)) : visible.map((x) => chartSeriesColor(s, s.series.indexOf(x)));\n\t\t\treturn { colors: colors ?? own, ...checkChartColors(colors ?? own, { surface }) };\n\t\t}\n\t};\n\n\tconst recommend: AgentTool = {\n\t\tname: 'recommend_chart',\n\t\ttitle: 'Recommend chart types',\n\t\tdescription:\n\t\t\t'Suggests chart types for data, best first, each with a reason: from CSV text when given, else from the chart\\'s current data. Uses the shape of the data (series count, points, dates, negative values).',\n\t\tinputSchema: { type: 'object', properties: { csv: { type: 'string', description: 'CSV or TSV text to analyse instead of the current data (first row may be series names, first column categories).' } }, additionalProperties: false },\n\t\tannotations: { title: 'Recommend chart types', ...READ },\n\t\thandler: ({ csv }) => {\n\t\t\tconst rows = csv !== undefined ? parseCsv(csv, { delimiter: csv.includes('\\t') ? '\\t' : ',' }) : table();\n\t\t\tconst recommendations = recommendChartTypes(rows);\n\t\t\tif (!recommendations.length) fail('There are no numbers to chart: give CSV with at least one numeric column.');\n\t\t\treturn { recommendations };\n\t\t}\n\t};\n\n\tconst getTrendline: AgentTool = {\n\t\tname: 'get_chart_trendline',\n\t\ttitle: 'Read a trendline fit',\n\t\tdescription: 'Returns a trendline\\'s fitted coefficients (in x for category charts, x = 1, 2, 3, …), R², equation and the number of points, or the moving-average points.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { series: SERIES_REF, index: { type: 'integer', minimum: 0, description: 'Trendline index on the series (0 = first).' } },\n\t\t\trequired: ['series', 'index'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Read a trendline fit', ...READ },\n\t\thandler: ({ series, index }) => {\n\t\t\tconst s = seriesById(series);\n\t\t\tconst line = s.trendlines?.[index];\n\t\t\tif (!line) fail(`\"${s.name}\" has no trendline ${index}; it has ${s.trendlines?.length ?? 0}.`);\n\t\t\tif (line!.type === 'moving-average') return { trendline: line, points: controller.trendlineMovingAverage(s.id, index) };\n\t\t\tconst fit = controller.trendlineFit(s.id, index);\n\t\t\tif (!fit) fail(`The ${line!.type} trendline on \"${s.name}\" cannot be fitted: it needs more points (and positive values for log, exponential and power fits).`);\n\t\t\treturn { trendline: line, coefficients: fit!.coefficients, r2: fit!.r2, equation: fit!.equation, points: fit!.points };\n\t\t}\n\t};\n\n\tconst listPresets: AgentTool = {\n\t\tname: 'list_chart_presets',\n\t\ttitle: 'List chart presets',\n\t\tdescription: 'Lists the quick layouts and colour schemes apply_chart_preset accepts, with what each changes.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'List chart presets', ...READ },\n\t\thandler: () => ({\n\t\t\tlayouts: CHART_LAYOUT_PRESETS.map(({ id, label, description }) => ({ id, label, description })),\n\t\t\tcolorSchemes: CHART_COLOR_SCHEMES.map(({ id, label, description, palette }) => ({ id, label, description, palette }))\n\t\t})\n\t};\n\n\tconst exportMermaid: AgentTool = {\n\t\tname: 'export_chart_mermaid',\n\t\ttitle: 'Export chart as Mermaid',\n\t\tdescription:\n\t\t\t'Returns the chart as Mermaid text (xychart-beta, pie or radar-beta) for Markdown or chat. With meta (default true) one \"%% @pixerate {…}\" comment keeps what Mermaid cannot express, so import_chart_mermaid gets the chart back exactly.',\n\t\tinputSchema: { type: 'object', properties: { meta: { type: 'boolean', description: 'Include the round-trip comment (default true).' } }, additionalProperties: false },\n\t\tannotations: { title: 'Export chart as Mermaid', ...READ },\n\t\thandler: ({ meta = true }) => ({ mermaid: chartToMermaid(controller.toJSON(), { meta }) })\n\t};\n\n\tconst exportOoxml: AgentTool = {\n\t\tname: 'export_chart_ooxml',\n\t\ttitle: 'Export chart as Office XML',\n\t\tdescription: 'Returns the chart as a DrawingML chart part (c:chartSpace) for Word or PowerPoint files, with what could not be written as sentences.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Export chart as Office XML', ...READ },\n\t\thandler: () => chartToOoxml(controller.toJSON())\n\t};\n\n\t// ---------------------------------------------------------------- writes\n\n\tconst updateChart: AgentTool = {\n\t\tname: 'update_chart',\n\t\ttitle: 'Change chart presentation',\n\t\tdescription:\n\t\t\t'Changes how the chart looks, as one undo step: type, titles, axes (xAxis = categories or numeric x, yAxis = values, yAxis2 = secondary values), legend, stacking, orientation, curve, points, data labels and their position, palette, donut hole, bar spacing, histogram bins, waterfall total. All-or-nothing: invalid values change nothing and come back as sentences. Returns the new spec.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: CHART_UPDATE_PROPERTIES,\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Change chart presentation', ...WRITE_IDEMPOTENT },\n\t\thandler: (args) => {\n\t\t\tif (!Object.keys(args).length) fail('Nothing to change: pass at least one field, e.g. {\"type\": \"line\"}.');\n\t\t\tresolve(controller.update(args as ChartSpecPatch));\n\t\t\treturn { spec: controller.toJSON() };\n\t\t}\n\t};\n\n\tconst setData: AgentTool = {\n\t\tname: 'set_chart_data',\n\t\ttitle: 'Replace chart data',\n\t\tdescription: 'Replaces the categories and / or the series as one undo step. Each series has one value per category (padded with gaps). Returns the data table and the series ids.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcategories: { type: 'array', items: { type: 'string' }, description: 'Category labels in order.' },\n\t\t\t\tseries: {\n\t\t\t\t\ttype: 'array',\n\t\t\t\t\tdescription: 'The new series (replaces all).',\n\t\t\t\t\titems: { type: 'object', properties: { id: { type: 'string', description: 'Stable id (optional).' }, ...SERIES_PROPS }, required: ['name', 'values'], additionalProperties: false }\n\t\t\t\t}\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Replace chart data', ...DESTRUCTIVE },\n\t\thandler: (args) => {\n\t\t\tif (!args.categories && !args.series) fail('Pass categories, series or both.');\n\t\t\tresolve(controller.setData(args as any));\n\t\t\treturn { table: table(), series: spec().series.map((s) => ({ id: s.id, name: s.name })) };\n\t\t}\n\t};\n\n\tconst setValues: AgentTool = {\n\t\tname: 'set_chart_values',\n\t\ttitle: 'Set chart values',\n\t\tdescription: 'Sets individual values as one undo step (all-or-nothing). Series by id or name, category by index or label. Returns the values as stored.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcells: {\n\t\t\t\t\ttype: 'array',\n\t\t\t\t\tminItems: 1,\n\t\t\t\t\tdescription: 'Values to set.',\n\t\t\t\t\titems: { type: 'object', properties: { series: SERIES_REF, category: CATEGORY_REF, value: VALUE }, required: ['series', 'category', 'value'], additionalProperties: false }\n\t\t\t\t}\n\t\t\t},\n\t\t\trequired: ['cells'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Set chart values', ...WRITE_IDEMPOTENT },\n\t\thandler: async ({ cells }) => {\n\t\t\tconst resolved = (cells as { series: string; category: string | number; value: unknown }[]).map((c) => ({ seriesId: seriesById(c.series).id, index: categoryIndex(c.category), value: c.value }));\n\t\t\tconst parsed = resolved.map((c) => parseChartValue(c.value));\n\t\t\tconst bad = resolved.find((_, i) => parsed[i] === undefined);\n\t\t\tif (bad) fail(`\"${String(bad.value)}\" is not a number; pass a number, numeric text or null for a gap. Nothing was changed.`);\n\t\t\tif (options.director && parsed.every((v) => typeof v === 'number')) {\n\t\t\t\tconst results = await options.director.perform(options.actor ?? { id: 'agent', name: 'Agent' }, resolved.map((c, i) => ({ kind: 'setValue' as const, seriesId: c.seriesId, index: c.index, value: parsed[i] as number })));\n\t\t\t\tconst failed = results.find((r) => !r.ok);\n\t\t\t\tif (failed && !failed.ok) fail(failed.message);\n\t\t\t} else resolve(controller.setValues(resolved));\n\t\t\treturn { cells: resolved.map((c) => ({ series: c.seriesId, category: spec().categories[c.index], index: c.index, value: controller.getSeries(c.seriesId)!.values[c.index] })) };\n\t\t}\n\t};\n\n\tconst addSeries: AgentTool = {\n\t\tname: 'add_chart_series',\n\t\ttitle: 'Add a series',\n\t\tdescription: 'Adds a series (values padded to the categories) and selects it. Returns its id and stored values.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { ...SERIES_PROPS, id: { type: 'string', description: 'Id to use (default: series-N).' }, at: { type: 'integer', minimum: 0, description: 'Position (default: last).' } },\n\t\t\trequired: ['name'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Add a series', ...WRITE },\n\t\thandler: ({ at, ...input }) => {\n\t\t\tconst clean = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== null));\n\t\t\tconst result = resolve(controller.addSeries(clean as any, { at })) as { id: string };\n\t\t\tconst s = controller.getSeries(result.id)!;\n\t\t\treturn { id: s.id, name: s.name, values: s.values };\n\t\t}\n\t};\n\n\tconst updateSeries: AgentTool = {\n\t\tname: 'update_chart_series',\n\t\ttitle: 'Change a series',\n\t\tdescription: 'Renames, recolours, hides, moves to the secondary axis or changes how a series is drawn (marker, curve, labels, format, x values, bubble sizes, point colours). null resets a field. Values change with set_chart_values. Returns the series.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { series: SERIES_REF, ...Object.fromEntries(Object.entries(SERIES_PROPS).filter(([k]) => k !== 'values')) },\n\t\t\trequired: ['series'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Change a series', ...WRITE_IDEMPOTENT },\n\t\thandler: ({ series, ...patch }) => {\n\t\t\tconst id = seriesById(series).id;\n\t\t\tif (!Object.keys(patch).length) fail('Nothing to change: pass a field such as {\"color\": \"#e8710a\"} or {\"axis\": \"secondary\"}.');\n\t\t\tresolve(controller.updateSeries(id, patch as ChartSeriesPatch));\n\t\t\treturn { series: controller.getSeries(id) };\n\t\t}\n\t};\n\n\tconst removeSeries: AgentTool = {\n\t\tname: 'remove_chart_series',\n\t\ttitle: 'Delete a series',\n\t\tdescription: 'Deletes a series and its values. Returns the remaining series ids.',\n\t\tinputSchema: { type: 'object', properties: { series: SERIES_REF }, required: ['series'], additionalProperties: false },\n\t\tannotations: { title: 'Delete a series', ...DESTRUCTIVE },\n\t\thandler: ({ series }) => {\n\t\t\tresolve(controller.removeSeries(seriesById(series).id));\n\t\t\treturn { series: spec().series.map((s) => ({ id: s.id, name: s.name })) };\n\t\t}\n\t};\n\n\tconst addCategory: AgentTool = {\n\t\tname: 'add_chart_category',\n\t\ttitle: 'Add a category',\n\t\tdescription: 'Inserts a category (a gap in every series) and returns its index.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { label: { type: 'string', description: 'Category label (default: its number).' }, at: { type: 'integer', minimum: 0, description: 'Index to insert at (default: the end).' } },\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Add a category', ...WRITE },\n\t\thandler: ({ label, at }) => {\n\t\t\tconst result = controller.addCategory(label, { at });\n\t\t\treturn { index: result.index, categories: spec().categories };\n\t\t}\n\t};\n\n\tconst removeCategory: AgentTool = {\n\t\tname: 'remove_chart_category',\n\t\ttitle: 'Delete a category',\n\t\tdescription: 'Deletes a category and its value in every series. Returns the remaining categories.',\n\t\tinputSchema: { type: 'object', properties: { category: CATEGORY_REF }, required: ['category'], additionalProperties: false },\n\t\tannotations: { title: 'Delete a category', ...DESTRUCTIVE },\n\t\thandler: ({ category }) => {\n\t\t\tresolve(controller.removeCategory(categoryIndex(category)));\n\t\t\treturn { categories: spec().categories };\n\t\t}\n\t};\n\n\tconst importCsv: AgentTool = {\n\t\tname: 'import_chart_csv',\n\t\ttitle: 'Import chart data from CSV',\n\t\tdescription:\n\t\t\t'Replaces the data with CSV or TSV text as one undo step. By default the first row holds series names and the first column categories (detected when \"auto\"). chartType \"auto\" also picks the recommended chart type (two unlabelled numeric columns become a scatter of x against y). Returns the data table, the chart type and cells that were not numbers.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcsv: { type: 'string', description: 'CSV or TSV text (tabs are detected).' },\n\t\t\t\tseriesIn: { type: 'string', enum: ['columns', 'rows'], description: 'Series run down columns (default) or along rows. Ignored with chartType \"auto\".' },\n\t\t\t\theader: { type: ['boolean', 'string'], enum: [true, false, 'auto'], description: 'The first row holds series names: true (default), false or \"auto\". Ignored with chartType \"auto\".' },\n\t\t\t\tchartType: { type: 'string', enum: ['keep', 'auto'], description: '\"keep\" (default) keeps the chart type; \"auto\" reads the table shape and picks a type.' }\n\t\t\t},\n\t\t\trequired: ['csv'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Import chart data from CSV', ...DESTRUCTIVE },\n\t\thandler: ({ csv, seriesIn, header, chartType = 'keep' }) => {\n\t\t\tif (chartType === 'auto') {\n\t\t\t\tconst rows = parseCsv(csv, { delimiter: csv.includes('\\t') ? '\\t' : ',' });\n\t\t\t\tconst built = chartFromTable(rows);\n\t\t\t\tif (!built.series.length || !built.categories.length) fail('There is no data to import: expected at least one row of numbers.');\n\t\t\t\tresolve(controller.update({ type: built.type, stacking: built.stacking, categories: built.categories, series: built.series }, { label: 'Import data' }));\n\t\t\t\treturn { type: built.type, table: table(), issues: built.issues };\n\t\t\t}\n\t\t\tconst result = resolve(controller.importCsv(csv, { seriesIn, header })) as { issues?: unknown[] };\n\t\t\treturn { type: spec().type, table: table(), issues: result.issues ?? [] };\n\t\t}\n\t};\n\n\tconst importMermaid: AgentTool = {\n\t\tname: 'import_chart_mermaid',\n\t\ttitle: 'Import a Mermaid chart',\n\t\tdescription:\n\t\t\t'Replaces the chart with Mermaid xychart-beta, pie or radar-beta text as one undo step (a \"%% @pixerate\" comment from export_chart_mermaid restores everything else). Lines that cannot be read are skipped and listed with their line numbers. Returns the spec.',\n\t\tinputSchema: { type: 'object', properties: { mermaid: { type: 'string', description: 'Mermaid text, optionally inside a ```mermaid fence.' } }, required: ['mermaid'], additionalProperties: false },\n\t\tannotations: { title: 'Import a Mermaid chart', ...DESTRUCTIVE },\n\t\thandler: ({ mermaid }) => {\n\t\t\tconst fenced = /```(?:mermaid)?\\s*\\n([\\s\\S]*?)```/.exec(mermaid);\n\t\t\tconst read = chartFromMermaid(fenced ? fenced[1] : mermaid);\n\t\t\tif (!read.family) fail(read.issues.map((i) => i.message).join(' ') || 'Expected Mermaid starting with xychart-beta, pie or radar-beta.');\n\t\t\tresolve(controller.update({ ...read.spec } as ChartSpecPatch, { label: 'Import Mermaid chart' }));\n\t\t\treturn { spec: controller.toJSON(), issues: read.issues };\n\t\t}\n\t};\n\n\tconst importOoxml: AgentTool = {\n\t\tname: 'import_chart_ooxml',\n\t\ttitle: 'Import an Office chart',\n\t\tdescription:\n\t\t\t'Replaces the chart with an Office chart part (DrawingML c:chartSpace, or chartex for waterfall, funnel, treemap, histogram and box charts) as one undo step. Returns the spec, problems, and the features the editor cannot hold.',\n\t\tinputSchema: { type: 'object', properties: { xml: { type: 'string', description: 'The chart part XML, e.g. word/charts/chart1.xml.' } }, required: ['xml'], additionalProperties: false },\n\t\tannotations: { title: 'Import an Office chart', ...DESTRUCTIVE },\n\t\thandler: ({ xml }) => {\n\t\t\tconst read = chartFromOoxml(xml, { DOMParser: Parser() });\n\t\t\tif (read.issues.some((i) => i.path === '' || i.path === 'plotArea')) fail(read.issues.map((i) => i.message).join(' '));\n\t\t\tresolve(controller.update({ ...read.spec } as ChartSpecPatch, { label: 'Import Office chart' }));\n\t\t\treturn { spec: controller.toJSON(), issues: read.issues.map((i) => i.message), unsupported: read.unsupported, lossless: read.lossless };\n\t\t}\n\t};\n\n\tconst addTrendline: AgentTool = {\n\t\tname: 'add_chart_trendline',\n\t\ttitle: 'Add a trendline',\n\t\tdescription: 'Fits a trendline to a series and draws it (unstacked bar, line, area, scatter and bubble charts). Returns its index and the fit: coefficients, R² and equation.',\n\t\tinputSchema: { type: 'object', properties: { series: SERIES_REF, ...TRENDLINE_PROPS }, required: ['series', 'type'], additionalProperties: false },\n\t\tannotations: { title: 'Add a trendline', ...WRITE },\n\t\thandler: ({ series, ...line }) => {\n\t\t\tconst s = seriesById(series);\n\t\t\tconst result = resolve(controller.addTrendline(s.id, line as ChartTrendline)) as { index: number; fit: ReturnType<ChartController['trendlineFit']> };\n\t\t\treturn { series: s.id, index: result.index, ...(result.fit ? { coefficients: result.fit.coefficients, r2: result.fit.r2, equation: result.fit.equation } : {}) };\n\t\t}\n\t};\n\n\tconst removeTrendline: AgentTool = {\n\t\tname: 'remove_chart_trendline',\n\t\ttitle: 'Delete a trendline',\n\t\tdescription: 'Deletes a trendline from a series. Returns the series\\' remaining trendlines.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { series: SERIES_REF, index: { type: 'integer', minimum: 0, description: 'Trendline index on the series (0 = first).' } },\n\t\t\trequired: ['series', 'index'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Delete a trendline', ...DESTRUCTIVE },\n\t\thandler: ({ series, index }) => {\n\t\t\tconst s = seriesById(series);\n\t\t\tresolve(controller.removeTrendline(s.id, index));\n\t\t\treturn { series: s.id, trendlines: controller.getSeries(s.id)?.trendlines ?? [] };\n\t\t}\n\t};\n\n\tconst applyPreset: AgentTool = {\n\t\tname: 'apply_chart_preset',\n\t\ttitle: 'Apply a chart style',\n\t\tdescription: 'Applies a quick layout (legend, labels and grid lines together) and / or a colour scheme as one undo step. See list_chart_presets for the names. Returns the new spec.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tlayout: { type: 'string', enum: CHART_LAYOUT_PRESETS.map((p) => p.id), description: 'Quick layout id.' },\n\t\t\t\tcolors: { type: 'string', enum: CHART_COLOR_SCHEMES.map((p) => p.id), description: 'Colour scheme id.' }\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Apply a chart style', ...WRITE_IDEMPOTENT },\n\t\thandler: ({ layout, colors }) => {\n\t\t\tresolve(controller.applyPreset({ layout, colors }));\n\t\t\treturn { spec: controller.toJSON() };\n\t\t}\n\t};\n\n\tconst transpose: AgentTool = {\n\t\tname: 'transpose_chart',\n\t\ttitle: 'Switch rows and columns',\n\t\tdescription: 'Swaps series and categories (each category becomes a series) as one undo step. Per-series colours and settings are dropped. Returns the data table.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Switch rows and columns', ...WRITE },\n\t\thandler: () => {\n\t\t\tresolve(controller.transpose());\n\t\t\treturn { table: table(), series: spec().series.map((s) => ({ id: s.id, name: s.name })) };\n\t\t}\n\t};\n\n\tconst select: AgentTool = {\n\t\tname: 'select_chart_element',\n\t\ttitle: 'Select a chart element',\n\t\tdescription: 'Selects part of the chart (as a click would), for press_chart_key and for the user to see. kind \"none\" clears the selection. Returns the selection.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tkind: { type: 'string', enum: ['none', 'chart', 'title', 'subtitle', 'legend', 'axis', 'series', 'point', 'category', 'trendline'], description: 'What to select.' },\n\t\t\t\tseries: { ...SERIES_REF, description: 'Series id or name (series, point, trendline).' },\n\t\t\t\tcategory: { ...CATEGORY_REF, description: 'Category index or label (point, category).' },\n\t\t\t\taxis: { type: 'string', enum: ['x', 'y', 'y2'], description: 'Axis (axis).' },\n\t\t\t\tindex: { type: 'integer', minimum: 0, description: 'Trendline index (trendline).' }\n\t\t\t},\n\t\t\trequired: ['kind'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Select a chart element', ...WRITE_IDEMPOTENT },\n\t\thandler: async ({ kind, series, category, axis, index }) => {\n\t\t\tlet sel: ChartSelection | null;\n\t\t\tconst need = (v: unknown, what: string) => v === undefined && fail(`kind \"${kind}\" needs ${what}.`);\n\t\t\tswitch (kind) {\n\t\t\t\tcase 'none':\n\t\t\t\t\tsel = null;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'axis':\n\t\t\t\t\tneed(axis, 'axis');\n\t\t\t\t\tsel = { kind, axis };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'series':\n\t\t\t\t\tneed(series, 'series');\n\t\t\t\t\tsel = { kind, seriesId: seriesById(series).id };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'point':\n\t\t\t\t\tneed(series, 'series');\n\t\t\t\t\tneed(category, 'category');\n\t\t\t\t\tsel = { kind, seriesId: seriesById(series).id, index: categoryIndex(category) };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'category':\n\t\t\t\t\tneed(category, 'category');\n\t\t\t\t\tsel = { kind, index: categoryIndex(category) };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'trendline':\n\t\t\t\t\tneed(series, 'series');\n\t\t\t\t\tneed(index, 'index');\n\t\t\t\t\tsel = { kind, seriesId: seriesById(series).id, index };\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsel = { kind } as ChartSelection;\n\t\t\t}\n\t\t\tif (options.director) await options.director.perform(options.actor ?? { id: 'agent', name: 'Agent' }, [{ kind: 'select', selection: sel }]);\n\t\t\telse controller.select(sel);\n\t\t\tconst now = controller.getState().selection;\n\t\t\tif (sel && !now) fail(`Nothing to select there (e.g. the chart has no ${kind} of that kind).`);\n\t\t\treturn { selection: now };\n\t\t}\n\t};\n\n\tconst drag: AgentTool = {\n\t\tname: 'drag_chart_point',\n\t\ttitle: 'Drag a chart point',\n\t\tdescription:\n\t\t\t'Drags on the chart as a pointer would, through the same code as the mouse: from a bar or point to a new position, with the same snapping (to other values, zero and ticks), fine adjustment (fine: Alt) and axis lock on scatter charts (lockAxis: Shift). Positions are 0–1 fractions of the chart\\'s width and height at the given size (use render_chart to see where marks are). One undo step. Returns what was dragged and the value before and after.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tfrom: { type: 'object', description: 'Start, as fractions of the chart (0,0 top-left).', properties: { x: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the width.' }, y: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the height.' } }, required: ['x', 'y'], additionalProperties: false },\n\t\t\t\tto: { type: 'object', description: 'End, as fractions of the chart.', properties: { x: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the width.' }, y: { type: 'number', minimum: 0, maximum: 1, description: 'Fraction of the height.' } }, required: ['x', 'y'], additionalProperties: false },\n\t\t\t\tfine: { type: 'boolean', description: 'Move a tenth as far (Alt).' },\n\t\t\t\tlockAxis: { type: 'boolean', description: 'Scatter charts: change only the axis moved along most (Shift).' },\n\t\t\t\twidth: WIDTH,\n\t\t\t\theight: HEIGHT\n\t\t\t},\n\t\t\trequired: ['from', 'to'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Drag a chart point', ...WRITE },\n\t\thandler: ({ from, to, fine, lockAxis, width = size.width, height = size.height }) => {\n\t\t\tconst scene = layoutChart(controller.toJSON(), { width, height });\n\t\t\tconst start = { x: from.x * width, y: from.y * height };\n\t\t\tconst target = chartHitTest(scene, start);\n\t\t\tif (target?.kind !== 'point') fail(`There is no bar or point at (${from.x}, ${from.y}); ${target ? `that is the ${target.kind}` : 'that is outside the chart'}. Use render_chart to find marks.`);\n\t\t\tconst t = target as Extract<ChartSelection, { kind: 'point' }>;\n\t\t\tconst before = controller.getSeries(t.seriesId)?.values[t.index] ?? null;\n\t\t\tconst session = startChartPointDrag(controller, scene, t, start);\n\t\t\tif (!session) fail('That point cannot be dragged here (percent-stacked charts, pies and gaps cannot be dragged).');\n\t\t\tsession!.move({ x: to.x * width, y: to.y * height }, { fine, lockAxis });\n\t\t\tsession!.end();\n\t\t\tconst s = controller.getSeries(t.seriesId)!;\n\t\t\treturn { series: s.id, category: spec().categories[t.index], index: t.index, before, after: s.values[t.index], ...(s.x ? { x: s.x[t.index] } : {}) };\n\t\t}\n\t};\n\n\tconst key: AgentTool = {\n\t\tname: 'press_chart_key',\n\t\ttitle: 'Press a key on the chart',\n\t\tdescription:\n\t\t\t'Sends a key to the chart as the keyboard would, acting on the selection (select_chart_element first): ← → move between categories, ↑ ↓ change the selected value by a tenth of a tick (shift: a whole tick, alt: a hundredth), Delete removes the selection, Escape clears it. Returns whether the key did anything and the new selection.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tkey: { type: 'string', enum: ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Delete', 'Backspace', 'Escape'], description: 'Key name.' },\n\t\t\t\tshift: { type: 'boolean', description: 'Hold Shift.' },\n\t\t\t\talt: { type: 'boolean', description: 'Hold Alt / Option.' }\n\t\t\t},\n\t\t\trequired: ['key'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: { title: 'Press a key on the chart', ...DESTRUCTIVE },\n\t\thandler: ({ key: k, shift, alt }) => {\n\t\t\tconst scene = layoutChart(controller.toJSON(), size);\n\t\t\tconst used = handleChartKey(controller, scene, { key: k, shiftKey: shift, altKey: alt });\n\t\t\tconst sel = controller.getState().selection;\n\t\t\tconst value = sel?.kind === 'point' ? (controller.getSeries(sel.seriesId)?.values[sel.index] ?? null) : undefined;\n\t\t\treturn { used, selection: sel, ...(value !== undefined ? { value } : {}) };\n\t\t}\n\t};\n\n\tconst undo: AgentTool = {\n\t\tname: 'undo_chart',\n\t\ttitle: 'Undo a chart edit',\n\t\tdescription: 'Undoes the last chart edit. Returns whether something was undone and what the next undo would be.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Undo a chart edit', ...WRITE },\n\t\thandler: () => {\n\t\t\tconst label = controller.getState().undoLabel;\n\t\t\tconst undone = controller.undo();\n\t\t\treturn { undone, ...(undone ? { label } : {}), next: controller.getState().undoLabel || null };\n\t\t}\n\t};\n\n\tconst redo: AgentTool = {\n\t\tname: 'redo_chart',\n\t\ttitle: 'Redo a chart edit',\n\t\tdescription: 'Redoes the last undone chart edit. Returns whether something was redone.',\n\t\tinputSchema: { type: 'object', properties: {}, additionalProperties: false },\n\t\tannotations: { title: 'Redo a chart edit', ...WRITE },\n\t\thandler: () => {\n\t\t\tconst label = controller.getState().redoLabel;\n\t\t\tconst redone = controller.redo();\n\t\t\treturn { redone, ...(redone ? { label } : {}) };\n\t\t}\n\t};\n\n\tconst reads = [getChart, renderChart, checkColors, recommend, getTrendline, listPresets, exportMermaid, exportOoxml];\n\tconst writes = [updateChart, setData, setValues, addSeries, updateSeries, removeSeries, addCategory, removeCategory, importCsv, importMermaid, addTrendline, removeTrendline, applyPreset, transpose, select, drag, key, undo, redo];\n\n\treturn {\n\t\tid: options.id ?? 'chart',\n\t\tnamespace: options.namespace,\n\t\ttools: () => {\n\t\t\tif (readOnlyReason()) return reads;\n\t\t\treturn [...reads, ...writes.slice(0, 10), ...(Parser() ? [importOoxml] : []), ...writes.slice(10)];\n\t\t},\n\t\tsubscribe: (notify) => {\n\t\t\t// Re-announce when read-only state may have changed.\n\t\t\tlet last = readOnlyReason();\n\t\t\treturn controller.subscribe(() => {\n\t\t\t\tconst now = readOnlyReason();\n\t\t\t\tif (now !== last) {\n\t\t\t\t\tlast = now;\n\t\t\t\t\tnotify();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n}\n","// Streaming follows Ursula's MermaidStreamingView and src/graph/view.ts (`blendLayout`: marks are matched by id,\n// new ones appear at their target, missing ones drop out; layouts are adopted on a throttle and the scale is held\n// steady until the source is complete).\nimport { chartFromMermaid } from './mermaid.js';\nimport { normalizeChartSpec } from './spec.js';\nimport type { ChartIssue, ChartMark, ChartScene, ChartSpec } from './types.js';\n\n/**\n * Reads JSON that is still arriving: closes open strings, arrays and objects and drops a\n * dangling key or comma, so `{\"type\":\"bar\",\"series\":[{\"name\":\"A\",\"values\":[1,2` reads as far\n * as it goes. Returns `undefined` when nothing usable has arrived yet.\n */\nexport function parsePartialChartJson(text: string): unknown {\n\tconst src = text.trim();\n\tif (!src) return undefined;\n\ttry {\n\t\treturn JSON.parse(src);\n\t} catch {\n\t\t// fall through\n\t}\n\tconst stack: string[] = [];\n\tlet inString = false;\n\tlet escaped = false;\n\tlet out = '';\n\tfor (const ch of src) {\n\t\tout += ch;\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (ch === '\\\\') escaped = true;\n\t\t\telse if (ch === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"') inString = true;\n\t\telse if (ch === '{' || ch === '[') stack.push(ch === '{' ? '}' : ']');\n\t\telse if (ch === '}' || ch === ']') stack.pop();\n\t}\n\tif (inString) out += '\"';\n\t// Drop what cannot end a value: a trailing comma, colon, key without value or partial literal.\n\tfor (let attempt = 0; attempt < 6; attempt++) {\n\t\tconst trimmed = out.replace(/\\s+$/, '');\n\t\tconst candidate = trimmed + [...stack].reverse().join('');\n\t\ttry {\n\t\t\treturn JSON.parse(candidate);\n\t\t} catch {\n\t\t\tconst next = trimmed\n\t\t\t\t.replace(/,\\s*$/, '')\n\t\t\t\t.replace(/(?:,|\\{)\\s*\"[^\"]*\"\\s*:?\\s*$/, (m) => (m.trim().startsWith('{') ? '{' : ''))\n\t\t\t\t.replace(/:\\s*$/, ': null')\n\t\t\t\t.replace(/(?<=[\\[,:]\\s*)(-|tr?u?|fa?l?s?|nu?l?)$/, '')\n\t\t\t\t.replace(/(?<=[\\[,:]\\s*)(-?\\d+\\.)$/, (m) => m.slice(0, -1));\n\t\t\tif (next === trimmed) break;\n\t\t\tout = next;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport type ChartStreamFormat = 'auto' | 'mermaid' | 'json';\n\nexport interface ChartStreamResult {\n\t/** The chart as far as it has arrived, or `null` before anything can be drawn. */\n\tspec: ChartSpec | null;\n\tissues: ChartIssue[];\n\t/**\n\t * The value range to lay out with while incomplete: it only grows, so the axis does not\n\t * jump as values arrive. `null` once complete (the chart's own scale takes over).\n\t */\n\tvalueDomain: { min: number; max: number } | null;\n}\n\n/**\n * Turns a chart source that is still being written (Mermaid or a JSON spec, e.g. streamed\n * from a model) into drawable specs. Series appear once their values start, axis bounds only\n * grow until `complete`, and parse problems are reported only once the source is complete.\n */\nexport class ChartStream {\n\tprivate lo = Infinity;\n\tprivate hi = -Infinity;\n\tprivate last: ChartSpec | null = null;\n\n\tconstructor(private readonly format: ChartStreamFormat = 'auto') {}\n\n\t/** Reads the source so far. `complete` when nothing more will arrive. */\n\tupdate(source: string, complete = false): ChartStreamResult {\n\t\tconst text = source.replace(/^\\s*```(?:mermaid|json)?\\s*\\n?/, '').replace(/```\\s*$/, '');\n\t\tconst format = this.format === 'auto' ? (/^\\s*[[{]/.test(text) ? 'json' : 'mermaid') : this.format;\n\t\tlet spec: ChartSpec | null = null;\n\t\tlet issues: ChartIssue[] = [];\n\t\tif (format === 'json') {\n\t\t\tconst value = complete ? safeParse(text) : parsePartialChartJson(text);\n\t\t\tif (value !== undefined) {\n\t\t\t\tconst read = normalizeChartSpec(value);\n\t\t\t\tspec = read.spec;\n\t\t\t\tissues = complete ? read.issues : [];\n\t\t\t}\n\t\t} else {\n\t\t\tconst read = chartFromMermaid(text, { partial: !complete });\n\t\t\tif (read.family) {\n\t\t\t\tspec = read.spec;\n\t\t\t\tissues = complete ? read.issues : [];\n\t\t\t}\n\t\t}\n\t\tif (spec && !spec.series.some((s) => s.values.some((v) => v !== null))) spec = complete ? spec : this.last;\n\t\tif (spec) this.last = spec;\n\t\tif (spec) {\n\t\t\tfor (const s of spec.series) for (const v of s.values) if (v !== null && Number.isFinite(v)) (this.lo = Math.min(this.lo, v)), (this.hi = Math.max(this.hi, v));\n\t\t}\n\t\tconst valueDomain = !complete && Number.isFinite(this.lo) && this.hi > this.lo ? { min: Math.min(0, this.lo), max: this.hi } : null;\n\t\treturn { spec, issues, valueDomain };\n\t}\n\n\t/** Forgets the axis bounds (a new source). */\n\treset(): void {\n\t\tthis.lo = Infinity;\n\t\tthis.hi = -Infinity;\n\t\tthis.last = null;\n\t}\n}\n\nfunction safeParse(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn parsePartialChartJson(text);\n\t}\n}\n\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\n\n/** Paths with the same commands blend number by number; others switch at the end. */\nfunction blendPath(a: string, b: string, t: number): string {\n\tconst na = a.match(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g);\n\tconst nb = b.match(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g);\n\tif (!na || !nb || na.length !== nb.length || a.replace(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g, '#') !== b.replace(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g, '#')) return t < 1 ? a : b;\n\tlet i = 0;\n\treturn b.replace(/-?\\d*\\.?\\d+(?:e-?\\d+)?/g, () => {\n\t\tconst v = mix(Number(na[i]), Number(nb[i]), t);\n\t\ti++;\n\t\treturn String(Math.round(v * 100) / 100);\n\t});\n}\n\n/**\n * A scene between two scenes, for animating changes (streamed data arriving, an agent's\n * edit): marks are matched by `key`; numbers and same-shaped paths move from `from` to `to`;\n * new marks fade in and marks that are gone are dropped. `t` runs from 0 to 1.\n */\nexport function blendChartScenes(from: ChartScene | null, to: ChartScene, t: number): ChartScene {\n\tif (!from || t >= 1) return to;\n\tconst k = Math.max(0, Math.min(1, t));\n\tconst before = new Map(from.marks.map((m) => [m.key, m]));\n\tconst marks: ChartMark[] = to.marks.map((m) => {\n\t\tconst a = before.get(m.key);\n\t\tif (!a || a.kind !== m.kind) return { ...m, opacity: (m.opacity ?? 1) * k };\n\t\tswitch (m.kind) {\n\t\t\tcase 'rect': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, x: mix(p.x, m.x, k), y: mix(p.y, m.y, k), width: mix(p.width, m.width, k), height: mix(p.height, m.height, k) };\n\t\t\t}\n\t\t\tcase 'circle': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, cx: mix(p.cx, m.cx, k), cy: mix(p.cy, m.cy, k), r: mix(p.r, m.r, k) };\n\t\t\t}\n\t\t\tcase 'line': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, x1: mix(p.x1, m.x1, k), y1: mix(p.y1, m.y1, k), x2: mix(p.x2, m.x2, k), y2: mix(p.y2, m.y2, k) };\n\t\t\t}\n\t\t\tcase 'text': {\n\t\t\t\tconst p = a as typeof m;\n\t\t\t\treturn { ...m, x: mix(p.x, m.x, k), y: mix(p.y, m.y, k) };\n\t\t\t}\n\t\t\tcase 'path':\n\t\t\t\treturn { ...m, d: blendPath((a as typeof m).d, m.d, k) };\n\t\t}\n\t});\n\treturn { ...to, marks };\n}\n\n/** Ease-out cubic, for tweens. */\nexport const easeChartTween = (t: number) => 1 - Math.pow(1 - Math.max(0, Math.min(1, t)), 3);\n","// Agent \"performances\" follow Ursula's remote control (src/remote/commands.ts `planCommand`, src/react/remote/director.ts,\n// presence.ts, clock.ts): a pure planner turns a command into cursor steps, a director acts them out per actor and\n// commits each command as one undo step, and the clock is injectable so performances are repeatable in tests.\nimport type { ChartController, ChartSpecPatch } from './controller.js';\nimport { linearMap } from './scale.js';\nimport type { ChartScene, ChartSelection, ChartSpec } from './types.js';\n\nexport interface ChartPresenceActor {\n\tid: string;\n\tname: string;\n\tcolor: string;\n\t/** Cursor position in scene coordinates. */\n\tx: number;\n\ty: number;\n\t/** The button is down (dragging). */\n\tpressed: boolean;\n\t/** A short note shown next to the cursor (what the agent is doing). */\n\tmessage?: string;\n}\n\nexport interface ChartPresenceState {\n\tactors: readonly ChartPresenceActor[];\n}\n\n/** Cursor positions and notes of agents acting on a chart, for an overlay. */\nexport class ChartPresence {\n\tprivate state: ChartPresenceState = { actors: [] };\n\tprivate readonly listeners = new Set<(state: ChartPresenceState) => void>();\n\n\tgetState = (): ChartPresenceState => this.state;\n\n\tsubscribe = (listener: (state: ChartPresenceState) => void): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\t/** Adds or changes an actor. */\n\tset(actor: Pick<ChartPresenceActor, 'id'> & Partial<ChartPresenceActor>): void {\n\t\tconst current = this.state.actors.find((a) => a.id === actor.id);\n\t\tconst next: ChartPresenceActor = { name: actor.id, color: CHART_PRESENCE_COLORS[this.state.actors.length % CHART_PRESENCE_COLORS.length], x: 0, y: 0, pressed: false, ...current, ...actor };\n\t\tthis.state = { actors: current ? this.state.actors.map((a) => (a.id === actor.id ? next : a)) : [...this.state.actors, next] };\n\t\tthis.listeners.forEach((l) => l(this.state));\n\t}\n\n\tremove(id: string): void {\n\t\tif (!this.state.actors.some((a) => a.id === id)) return;\n\t\tthis.state = { actors: this.state.actors.filter((a) => a.id !== id) };\n\t\tthis.listeners.forEach((l) => l(this.state));\n\t}\n}\n\nexport const CHART_PRESENCE_COLORS: readonly string[] = ['#7c3aed', '#db2777', '#0891b2', '#ea580c', '#16a34a'];\n\n/** Time for performances: real timers, or an instant clock for tests and recordings. */\nexport interface ChartClock {\n\tnow(): number;\n\twait(ms: number): Promise<void>;\n}\n\nexport const realChartClock: ChartClock = {\n\tnow: () => Date.now(),\n\twait: (ms) => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)))\n};\n\n/** A clock whose waits finish at once while its time still advances (repeatable performances). */\nexport function createInstantChartClock(start = 0): ChartClock & { elapsed(): number } {\n\tlet t = start;\n\treturn {\n\t\tnow: () => t,\n\t\twait: async (ms) => {\n\t\t\tt += Math.max(0, ms);\n\t\t},\n\t\telapsed: () => t - start\n\t};\n}\n\n/** What an agent asks for. Each command commits as one undo step. */\nexport type ChartAgentCommand =\n\t| { kind: 'setValue'; seriesId: string; index: number; value: number; note?: string }\n\t| { kind: 'select'; selection: ChartSelection | null; note?: string }\n\t| { kind: 'update'; patch: ChartSpecPatch; label?: string; note?: string }\n\t| { kind: 'say'; text: string };\n\nexport type ChartPerformanceStep =\n\t| { type: 'move'; to: { x: number; y: number }; ms: number }\n\t| { type: 'say'; text: string; ms: number }\n\t| { type: 'press' }\n\t| { type: 'drag'; to: { x: number; y: number }; ms: number; from: number; value: number }\n\t| { type: 'release' }\n\t| { type: 'commit' };\n\n/** Where a point or bar sits in the scene (its top for bars), or null when it is not drawn. */\nexport function chartPointAnchor(scene: ChartScene, seriesId: string, index: number): { x: number; y: number } | null {\n\tconst mark = scene.marks.find((m) => (m.role === 'bar' || m.role === 'point') && m.target?.kind === 'point' && m.target.seriesId === seriesId && m.target.index === index);\n\tif (!mark) return null;\n\tif (mark.kind === 'rect') return { x: mark.x + mark.width / 2, y: mark.y };\n\tif (mark.kind === 'circle') return { x: mark.cx, y: mark.cy };\n\treturn null;\n}\n\nconst anchorFor = (scene: ChartScene, role: string) => {\n\tconst m = scene.marks.find((x) => x.role === role);\n\tif (!m) return null;\n\tif (m.kind === 'text') return { x: m.x, y: m.y };\n\tif (m.kind === 'rect') return { x: m.x + m.width / 2, y: m.y + m.height / 2 };\n\tif (m.kind === 'line') return { x: (m.x1 + m.x2) / 2, y: (m.y1 + m.y2) / 2 };\n\treturn null;\n};\n\n/**\n * Plans how an agent acts out a command on the chart: cursor moves, a drag along the value\n * axis for a value change (its end at the new value), a note, then a commit. Pure: the same\n * scene and command give the same steps.\n */\nexport function planChartCommand(spec: ChartSpec, scene: ChartScene, command: ChartAgentCommand, speed = 1): ChartPerformanceStep[] {\n\tconst ms = (n: number) => Math.round(n / Math.max(0.1, speed));\n\tconst steps: ChartPerformanceStep[] = [];\n\tconst note = 'note' in command && command.note ? command.note : undefined;\n\tif (note) steps.push({ type: 'say', text: note, ms: ms(500) });\n\tswitch (command.kind) {\n\t\tcase 'say':\n\t\t\tsteps.push({ type: 'say', text: command.text, ms: ms(900) });\n\t\t\treturn steps;\n\t\tcase 'setValue': {\n\t\t\tconst at = chartPointAnchor(scene, command.seriesId, command.index);\n\t\t\tconst series = spec.series.find((s) => s.id === command.seriesId);\n\t\t\tconst from = series?.values[command.index] ?? 0;\n\t\t\tconst scale = series?.axis === 'secondary' ? (scene.valueScale2 ?? scene.valueScale) : scene.valueScale;\n\t\t\tif (at && scale) {\n\t\t\t\tconst px = linearMap(command.value, scale.domain, scale.range);\n\t\t\t\tconst to = scale.axis === 'y' ? { x: at.x, y: px } : { x: px, y: at.y };\n\t\t\t\tsteps.push({ type: 'move', to: at, ms: ms(380) }, { type: 'press' }, { type: 'drag', to, ms: ms(520), from, value: command.value }, { type: 'release' });\n\t\t\t} else steps.push({ type: 'drag', to: { x: scene.plot.x + scene.plot.width / 2, y: scene.plot.y + scene.plot.height / 2 }, ms: ms(200), from, value: command.value });\n\t\t\tsteps.push({ type: 'commit' });\n\t\t\treturn steps;\n\t\t}\n\t\tcase 'select': {\n\t\t\tconst sel = command.selection;\n\t\t\tlet to: { x: number; y: number } | null = null;\n\t\t\tif (sel?.kind === 'point') to = chartPointAnchor(scene, sel.seriesId, sel.index);\n\t\t\telse if (sel) {\n\t\t\t\tconst m = scene.marks.find((x) => x.target && JSON.stringify(x.target) === JSON.stringify(sel));\n\t\t\t\tif (m?.kind === 'text') to = { x: m.x, y: m.y };\n\t\t\t\telse if (m?.kind === 'rect') to = { x: m.x + m.width / 2, y: m.y + m.height / 2 };\n\t\t\t\telse if (m?.kind === 'circle') to = { x: m.cx, y: m.cy };\n\t\t\t}\n\t\t\tif (to) steps.push({ type: 'move', to, ms: ms(380) }, { type: 'press' }, { type: 'release' });\n\t\t\tsteps.push({ type: 'commit' });\n\t\t\treturn steps;\n\t\t}\n\t\tcase 'update': {\n\t\t\tconst keys = Object.keys(command.patch);\n\t\t\tconst role = keys.includes('title') ? 'title' : keys.includes('legend') ? 'legend-label' : keys.some((k) => k === 'xAxis') ? 'axis' : keys.some((k) => k === 'yAxis' || k === 'yAxis2') ? 'tick-label' : null;\n\t\t\tconst to = (role && anchorFor(scene, role)) || { x: scene.plot.x + scene.plot.width / 2, y: scene.plot.y + 12 };\n\t\t\tsteps.push({ type: 'move', to, ms: ms(380) }, { type: 'press' }, { type: 'release' }, { type: 'commit' });\n\t\t\treturn steps;\n\t\t}\n\t}\n}\n\nexport interface ChartDirectorOptions {\n\t/** The scene as currently drawn (for cursor targets), e.g. the canvas' last layout. */\n\tscene: () => ChartScene;\n\tclock?: ChartClock;\n\t/** 1 = natural speed; 2 = twice as fast. */\n\tspeed?: number;\n\t/** Hide each actor's cursor this long after its last command (ms, default 1500; 0 keeps it). */\n\tlinger?: number;\n}\n\nexport interface ChartDirectorActor {\n\tid: string;\n\tname?: string;\n\tcolor?: string;\n}\n\nexport type ChartPerformanceResult = { ok: true; command: ChartAgentCommand } | { ok: false; command: ChartAgentCommand; message: string };\n\n/**\n * Acts out agent commands on a chart: each actor's cursor moves to the target, drags values\n * into place (the chart updates live) and the command commits as one undo step, while the\n * user keeps editing. Commands queue per actor; a command whose target was deleted meanwhile\n * fails with a sentence instead of editing something else.\n */\nexport class ChartDirector {\n\tprivate readonly queues = new Map<string, Promise<unknown>>();\n\tprivate readonly clock: ChartClock;\n\tprivate calls = 0;\n\n\tconstructor(\n\t\tprivate readonly controller: ChartController,\n\t\treadonly presence: ChartPresence,\n\t\tprivate readonly options: ChartDirectorOptions\n\t) {\n\t\tthis.clock = options.clock ?? realChartClock;\n\t}\n\n\t/** Acts out `commands` in order for `actor`. Resolves with one result per command. */\n\tperform(actor: ChartDirectorActor, commands: readonly ChartAgentCommand[]): Promise<ChartPerformanceResult[]> {\n\t\tconst prev = this.queues.get(actor.id) ?? Promise.resolve();\n\t\tconst run = prev.then(async () => {\n\t\t\tconst results: ChartPerformanceResult[] = [];\n\t\t\tthis.presence.set({ id: actor.id, ...(actor.name ? { name: actor.name } : {}), ...(actor.color ? { color: actor.color } : {}) });\n\t\t\t// Everything one call changes is one undo step.\n\t\t\tthis.controller.beginGesture(`agent:${actor.id}:${++this.calls}`);\n\t\t\ttry {\n\t\t\t\tfor (const command of commands) results.push(await this.performOne(actor.id, command));\n\t\t\t} finally {\n\t\t\t\tthis.controller.endGesture();\n\t\t\t\tthis.presence.set({ id: actor.id, message: undefined, pressed: false });\n\t\t\t}\n\t\t\tconst linger = this.options.linger ?? 1500;\n\t\t\tif (linger > 0) {\n\t\t\t\tawait this.clock.wait(linger);\n\t\t\t\tif (this.queues.get(actor.id) === run) this.presence.remove(actor.id);\n\t\t\t}\n\t\t\treturn results;\n\t\t});\n\t\tthis.queues.set(actor.id, run.catch(() => undefined));\n\t\treturn run;\n\t}\n\n\tprivate stale(command: ChartAgentCommand): string | null {\n\t\tconst spec = this.controller.getSpec();\n\t\tif (command.kind === 'setValue') {\n\t\t\tconst s = spec.series.find((x) => x.id === command.seriesId);\n\t\t\tif (!s) return `The series \"${command.seriesId}\" no longer exists.`;\n\t\t\tif (command.index < 0 || command.index >= spec.categories.length) return `Category ${command.index} no longer exists.`;\n\t\t\tif (!Number.isFinite(command.value)) return 'The value must be a finite number.';\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate async move(id: string, from: { x: number; y: number }, to: { x: number; y: number }, ms: number, each?: (t: number) => void) {\n\t\tconst frames = Math.max(1, Math.round(ms / 16));\n\t\tfor (let f = 1; f <= frames; f++) {\n\t\t\tconst t = f / frames;\n\t\t\tconst e = 1 - Math.pow(1 - t, 3);\n\t\t\tthis.presence.set({ id, x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e });\n\t\t\teach?.(e);\n\t\t\tawait this.clock.wait(ms / frames);\n\t\t}\n\t}\n\n\tprivate async performOne(id: string, command: ChartAgentCommand): Promise<ChartPerformanceResult> {\n\t\tconst stale = this.stale(command);\n\t\tif (stale) return { ok: false, command, message: stale };\n\t\tconst steps = planChartCommand(this.controller.getSpec(), this.options.scene(), command, this.options.speed);\n\t\tconst where = () => {\n\t\t\tconst a = this.presence.getState().actors.find((x) => x.id === id)!;\n\t\t\treturn { x: a.x, y: a.y };\n\t\t};\n\t\t{\n\t\t\tfor (const step of steps) {\n\t\t\t\tswitch (step.type) {\n\t\t\t\t\tcase 'say':\n\t\t\t\t\t\tthis.presence.set({ id, message: step.text });\n\t\t\t\t\t\tawait this.clock.wait(step.ms);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'move':\n\t\t\t\t\t\tawait this.move(id, where(), step.to, step.ms);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'press':\n\t\t\t\t\t\tthis.presence.set({ id, pressed: true });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'release':\n\t\t\t\t\t\tthis.presence.set({ id, pressed: false });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'drag': {\n\t\t\t\t\t\tif (command.kind !== 'setValue') break;\n\t\t\t\t\t\t// The value follows the cursor; the whole drag is one undo step.\n\t\t\t\t\t\tconst stale2 = this.stale(command);\n\t\t\t\t\t\tif (stale2) return { ok: false, command, message: stale2 };\n\t\t\t\t\t\tconst label = `${this.presence.getState().actors.find((a) => a.id === id)?.name ?? 'Agent'}: edit value`;\n\t\t\t\t\t\tawait this.move(id, where(), step.to, step.ms, (e) => {\n\t\t\t\t\t\t\tconst v = step.from + (step.value - step.from) * e;\n\t\t\t\t\t\t\tthis.controller.setValue(command.seriesId, command.index, Number(v.toPrecision(12)), { label });\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.controller.setValue(command.seriesId, command.index, step.value, { label });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'commit': {\n\t\t\t\t\t\tif (command.kind === 'select') this.controller.select(command.selection);\n\t\t\t\t\t\telse if (command.kind === 'update') {\n\t\t\t\t\t\t\tconst result = this.controller.update(command.patch, command.label ? { label: command.label } : {});\n\t\t\t\t\t\t\tif (!result.ok) return { ok: false, command, message: result.message };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, command };\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,QAAQ,CAAC,MAAe,MAAM,QAAQ,MAAM,UAAa,OAAO,CAAC,EAAE,KAAK,MAAM;AACpF,IAAM,SAAS,CAAC,MAAe,MAAM,CAAC,KAAK,gBAAgB,CAAC,MAAM;AAO3D,SAAS,kBAAkB,MAA8D;AAC/F,QAAM,OAAO,KAAK,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AACxD,QAAM,SAAS,KAAK;AACpB,QAAM,QAAQ,KAAK,IAAI,GAAG,GAAG,KAAK,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC;AACtD,QAAM,OAAO,CAAC,G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