basalt-ui 1.14.0 → 1.16.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 (176) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +38 -2
  4. package/agent/rules/basalt-charts.md +279 -108
  5. package/agent/rules/basalt-mantine.md +4 -2
  6. package/agent/skills/basalt-charts/SKILL.md +114 -64
  7. package/agent/skills/basalt-design/SKILL.md +4 -3
  8. package/agent/templates/CLAUDE-block.md.tpl +9 -6
  9. package/configs/oxlint-plugin.js +152 -0
  10. package/configs/oxlint-plugin.test.ts +107 -0
  11. package/configs/oxlint.json +2 -0
  12. package/dist/charts/cursor/resolve.d.ts +33 -0
  13. package/dist/charts/cursor/resolve.d.ts.map +1 -0
  14. package/dist/charts/cursor/resolve.js +61 -0
  15. package/dist/charts/cursor/resolve.test.d.ts +2 -0
  16. package/dist/charts/cursor/resolve.test.d.ts.map +1 -0
  17. package/dist/charts/cursor/scope.d.ts +17 -0
  18. package/dist/charts/cursor/scope.d.ts.map +1 -0
  19. package/dist/charts/cursor/scope.js +20 -0
  20. package/dist/charts/cursor/store.d.ts +31 -0
  21. package/dist/charts/cursor/store.d.ts.map +1 -0
  22. package/dist/charts/cursor/store.js +25 -0
  23. package/dist/charts/cursor/store.test.d.ts +2 -0
  24. package/dist/charts/cursor/store.test.d.ts.map +1 -0
  25. package/dist/charts/hooks/useChartCursor.d.ts +39 -0
  26. package/dist/charts/hooks/useChartCursor.d.ts.map +1 -0
  27. package/dist/charts/hooks/useChartCursor.js +104 -0
  28. package/dist/charts/hooks/useChartSize.d.ts +8 -4
  29. package/dist/charts/hooks/useChartSize.d.ts.map +1 -1
  30. package/dist/charts/index.d.ts +16 -13
  31. package/dist/charts/index.d.ts.map +1 -1
  32. package/dist/charts/index.js +38 -19
  33. package/dist/charts/kinds/Bars.d.ts +45 -54
  34. package/dist/charts/kinds/Bars.d.ts.map +1 -1
  35. package/dist/charts/kinds/Bars.js +235 -392
  36. package/dist/charts/kinds/Bars.test.d.ts +2 -0
  37. package/dist/charts/kinds/Bars.test.d.ts.map +1 -0
  38. package/dist/charts/kinds/Donut.d.ts +5 -4
  39. package/dist/charts/kinds/Donut.d.ts.map +1 -1
  40. package/dist/charts/kinds/Donut.js +17 -14
  41. package/dist/charts/kinds/DualPanel.d.ts +13 -0
  42. package/dist/charts/kinds/DualPanel.d.ts.map +1 -1
  43. package/dist/charts/kinds/DualPanel.js +185 -92
  44. package/dist/charts/kinds/DualPanel.test.d.ts +2 -0
  45. package/dist/charts/kinds/DualPanel.test.d.ts.map +1 -0
  46. package/dist/charts/kinds/Heatmap.d.ts +15 -11
  47. package/dist/charts/kinds/Heatmap.d.ts.map +1 -1
  48. package/dist/charts/kinds/Heatmap.js +38 -22
  49. package/dist/charts/kinds/MultiLine.d.ts +27 -35
  50. package/dist/charts/kinds/MultiLine.d.ts.map +1 -1
  51. package/dist/charts/kinds/MultiLine.js +122 -235
  52. package/dist/charts/kinds/MultiLine.test.d.ts +2 -0
  53. package/dist/charts/kinds/MultiLine.test.d.ts.map +1 -0
  54. package/dist/charts/kinds/StackedArea.d.ts +21 -10
  55. package/dist/charts/kinds/StackedArea.d.ts.map +1 -1
  56. package/dist/charts/kinds/StackedArea.js +74 -132
  57. package/dist/charts/kinds/ZonedLine.d.ts +24 -40
  58. package/dist/charts/kinds/ZonedLine.d.ts.map +1 -1
  59. package/dist/charts/kinds/ZonedLine.js +104 -184
  60. package/dist/charts/kinds/ZonedLine.test.d.ts +2 -0
  61. package/dist/charts/kinds/ZonedLine.test.d.ts.map +1 -0
  62. package/dist/charts/layout/auto-margin.d.ts +60 -0
  63. package/dist/charts/layout/auto-margin.d.ts.map +1 -0
  64. package/dist/charts/layout/auto-margin.js +37 -0
  65. package/dist/charts/layout/auto-margin.test.d.ts +2 -0
  66. package/dist/charts/layout/auto-margin.test.d.ts.map +1 -0
  67. package/dist/charts/primitives/CartesianChart.d.ts +161 -0
  68. package/dist/charts/primitives/CartesianChart.d.ts.map +1 -0
  69. package/dist/charts/primitives/CartesianChart.js +359 -0
  70. package/dist/charts/primitives/CartesianChart.test.d.ts +2 -0
  71. package/dist/charts/primitives/CartesianChart.test.d.ts.map +1 -0
  72. package/dist/charts/primitives/ChartFrame.d.ts +16 -5
  73. package/dist/charts/primitives/ChartFrame.d.ts.map +1 -1
  74. package/dist/charts/primitives/ChartFrame.js +17 -2
  75. package/dist/charts/primitives/ChartLegend.d.ts +15 -1
  76. package/dist/charts/primitives/ChartLegend.d.ts.map +1 -1
  77. package/dist/charts/primitives/ChartLegend.js +25 -3
  78. package/dist/charts/primitives/ChartLegend.test.d.ts +2 -0
  79. package/dist/charts/primitives/ChartLegend.test.d.ts.map +1 -0
  80. package/dist/charts/primitives/ChartTooltip.d.ts +16 -16
  81. package/dist/charts/primitives/ChartTooltip.d.ts.map +1 -1
  82. package/dist/charts/primitives/ChartTooltip.js +45 -19
  83. package/dist/charts/primitives/HoverOverlay.d.ts +19 -4
  84. package/dist/charts/primitives/HoverOverlay.d.ts.map +1 -1
  85. package/dist/charts/primitives/HoverOverlay.js +22 -1
  86. package/dist/charts/primitives/XZoneRects.d.ts +54 -0
  87. package/dist/charts/primitives/XZoneRects.d.ts.map +1 -0
  88. package/dist/charts/primitives/XZoneRects.js +65 -0
  89. package/dist/charts/primitives/XZoneRects.test.d.ts +2 -0
  90. package/dist/charts/primitives/XZoneRects.test.d.ts.map +1 -0
  91. package/dist/charts/series.d.ts +28 -3
  92. package/dist/charts/series.d.ts.map +1 -1
  93. package/dist/charts/series.js +5 -2
  94. package/dist/charts/series.test.d.ts +2 -0
  95. package/dist/charts/series.test.d.ts.map +1 -0
  96. package/dist/charts/utils/measure-text.d.ts +25 -0
  97. package/dist/charts/utils/measure-text.d.ts.map +1 -0
  98. package/dist/charts/utils/measure-text.js +64 -0
  99. package/dist/charts/utils/measure-text.test.d.ts +2 -0
  100. package/dist/charts/utils/measure-text.test.d.ts.map +1 -0
  101. package/dist/content/fence-block.d.ts.map +1 -1
  102. package/dist/surfaces.d.ts +1 -1
  103. package/dist/surfaces.d.ts.map +1 -1
  104. package/dist/surfaces.js +1 -1
  105. package/dist/tokens/chart-margin.test.d.ts +2 -0
  106. package/dist/tokens/chart-margin.test.d.ts.map +1 -0
  107. package/dist/tokens/index.d.ts +29 -0
  108. package/dist/tokens/index.d.ts.map +1 -1
  109. package/dist/tokens/index.js +10 -0
  110. package/dist/tokens/palette.d.ts +4 -0
  111. package/dist/tokens/palette.d.ts.map +1 -1
  112. package/dist/tokens/palette.js +3 -0
  113. package/llms.txt +3 -3
  114. package/package.json +1 -1
  115. package/src/charts/cursor/resolve.test.ts +61 -0
  116. package/src/charts/cursor/resolve.ts +102 -0
  117. package/src/charts/cursor/scope.tsx +32 -0
  118. package/src/charts/cursor/store.test.ts +46 -0
  119. package/src/charts/cursor/store.ts +53 -0
  120. package/src/charts/hooks/useChartCursor.ts +163 -0
  121. package/src/charts/hooks/useChartSize.ts +8 -4
  122. package/src/charts/index.ts +35 -14
  123. package/src/charts/kinds/Bars.test.tsx +98 -0
  124. package/src/charts/kinds/Bars.tsx +350 -467
  125. package/src/charts/kinds/Donut.tsx +31 -23
  126. package/src/charts/kinds/DualPanel.test.tsx +131 -0
  127. package/src/charts/kinds/DualPanel.tsx +301 -135
  128. package/src/charts/kinds/Heatmap.tsx +72 -47
  129. package/src/charts/kinds/MultiLine.test.tsx +37 -0
  130. package/src/charts/kinds/MultiLine.tsx +171 -290
  131. package/src/charts/kinds/StackedArea.tsx +116 -175
  132. package/src/charts/kinds/ZonedLine.test.tsx +37 -0
  133. package/src/charts/kinds/ZonedLine.tsx +149 -255
  134. package/src/charts/layout/auto-margin.test.ts +42 -0
  135. package/src/charts/layout/auto-margin.ts +110 -0
  136. package/src/charts/primitives/CartesianChart.test.tsx +160 -0
  137. package/src/charts/primitives/CartesianChart.tsx +598 -0
  138. package/src/charts/primitives/ChartFrame.test.tsx +33 -0
  139. package/src/charts/primitives/ChartFrame.tsx +40 -4
  140. package/src/charts/primitives/ChartLegend.test.tsx +78 -0
  141. package/src/charts/primitives/ChartLegend.tsx +52 -2
  142. package/src/charts/primitives/ChartTooltip.tsx +67 -37
  143. package/src/charts/primitives/HoverOverlay.tsx +39 -3
  144. package/src/charts/primitives/XZoneRects.test.tsx +123 -0
  145. package/src/charts/primitives/XZoneRects.tsx +132 -0
  146. package/src/charts/series.test.ts +112 -0
  147. package/src/charts/series.ts +33 -5
  148. package/src/charts/utils/measure-text.test.ts +36 -0
  149. package/src/charts/utils/measure-text.ts +109 -0
  150. package/src/content/fence-block.tsx +2 -3
  151. package/src/surfaces.ts +2 -1
  152. package/src/theme/spacing.test.ts +2 -0
  153. package/src/tokens/chart-margin.test.ts +39 -0
  154. package/src/tokens/density.test.ts +1 -0
  155. package/src/tokens/index.ts +36 -0
  156. package/src/tokens/palette.ts +3 -0
  157. package/dist/charts/hooks/useChartTooltip.d.ts +0 -13
  158. package/dist/charts/hooks/useChartTooltip.d.ts.map +0 -1
  159. package/dist/charts/hooks/useChartTooltip.js +0 -26
  160. package/dist/charts/hooks/useHoverSync.d.ts +0 -46
  161. package/dist/charts/hooks/useHoverSync.d.ts.map +0 -1
  162. package/dist/charts/hooks/useHoverSync.js +0 -75
  163. package/dist/charts/hover-context.d.ts +0 -21
  164. package/dist/charts/hover-context.d.ts.map +0 -1
  165. package/dist/charts/hover-context.js +0 -12
  166. package/dist/charts/hover-sync.d.ts +0 -14
  167. package/dist/charts/hover-sync.d.ts.map +0 -1
  168. package/dist/charts/hover-sync.js +0 -17
  169. package/dist/charts/primitives/ResponsiveChart.d.ts +0 -45
  170. package/dist/charts/primitives/ResponsiveChart.d.ts.map +0 -1
  171. package/dist/charts/primitives/ResponsiveChart.js +0 -24
  172. package/src/charts/hooks/useChartTooltip.ts +0 -31
  173. package/src/charts/hooks/useHoverSync.ts +0 -152
  174. package/src/charts/hover-context.ts +0 -28
  175. package/src/charts/hover-sync.tsx +0 -37
  176. package/src/charts/primitives/ResponsiveChart.tsx +0 -64
@@ -0,0 +1,598 @@
1
+ import { GridRows } from '@visx/grid'
2
+ import { Group } from '@visx/group'
3
+ import { scaleLinear, scalePoint } from '@visx/scale'
4
+ import { useMemo, useRef, useState } from 'react'
5
+ import type { ReactNode } from 'react'
6
+ import { VX } from '../../tokens'
7
+ import type { ChartMargin } from '../../tokens'
8
+ import { useChartCursor } from '../hooks/useChartCursor'
9
+ import { autoMargin, probeAxisLabels } from '../layout/auto-margin'
10
+ import { deriveTooltipRows } from '../series'
11
+ import type { ChartLegendConfig, ChartSeries } from '../series'
12
+ import { padAutoLower } from '../utils/domain'
13
+ import { fmtAxisDate } from '../utils/format'
14
+ import { smartTicks, smartTicksEvery } from '../utils/ticks'
15
+ import { AxisBottomDate, AxisLeftNumeric, AxisRightNumeric } from './Axes'
16
+ import { ChartFrame, resolveLegend } from './ChartFrame'
17
+ import { ChartTooltipFloat, TooltipBody, TooltipHeader, TooltipRow } from './ChartTooltip'
18
+ import { Crosshair, SeriesDot } from './Crosshair'
19
+ import { HoverOverlay } from './HoverOverlay'
20
+ import { XZoneRects } from './XZoneRects'
21
+ import type { XZoneSpec } from './XZoneRects'
22
+ import { ZoneRects } from './ZoneRects'
23
+ import type { ZoneSpec } from './ZoneRects'
24
+
25
+ type LinearScale = ReturnType<typeof scaleLinear<number>>
26
+ type PointScale = ReturnType<typeof scalePoint<string>>
27
+
28
+ const DEFAULT_TICKS = 5
29
+ const DEFAULT_AUTO_PAD = 1.1
30
+
31
+ /** One y-axis, fully described. Collapses the removed `yDomain` / `yAutoMaxFloor` / `yAutoMinCeil` /
32
+ * `yAutoPad` / `numTicksY` / `formatYTick` prop soup into a single object per axis. */
33
+ export type AxisConfig<T> = {
34
+ /**
35
+ * `'auto'` (default) derives the domain from the VISIBLE series; a tuple fixes it; a function
36
+ * computes it from the data — the seam a stacked chart uses to sum its bands. The function also
37
+ * receives the visible series, so a stacked domain SHRINKS when the legend toggles a band off
38
+ * (summing `props.series` there would leave a permanent gap above the stack).
39
+ */
40
+ domain?:
41
+ | [number, number]
42
+ | 'auto'
43
+ | ((data: readonly T[], visible: readonly ChartSeries<T>[]) => [number, number])
44
+ /** When 'auto': the upper bound is at least this. */
45
+ autoMaxFloor?: number
46
+ /** When 'auto': the lower bound is at most this. Default 0 (forced zero baseline). `Infinity`
47
+ * pads down from the raw data minimum instead. */
48
+ autoMinCeil?: number
49
+ /** When 'auto': padding multiplier applied away from the data. Default 1.1. */
50
+ autoPad?: number
51
+ ticks?: number
52
+ /** Tick + tooltip formatter for this axis. Defaults to d3's own tick format. */
53
+ format?: (v: number) => string
54
+ /** Horizontal grid rules. Default: on for the left axis, off for the right. */
55
+ grid?: boolean
56
+ /**
57
+ * Round the scale's domain outward to nice tick values (d3's `scale.nice()`). Threaded to BOTH
58
+ * `probeAxisLabels` (measurement) and the real `scaleLinear` (rendering) — they must agree, or
59
+ * the measured margin is computed from ticks the axis never paints.
60
+ *
61
+ * Default `false`, deliberately: flipping the default would move the domain of every
62
+ * already-migrated chart. Opt in per axis.
63
+ */
64
+ nice?: boolean
65
+ }
66
+
67
+ /** Handed to `prependRows`/`extraRows` alongside the hovered datum — the same `visible`/`hidden`
68
+ * the plot itself draws from, so a hand-authored row can't structurally desync from legend
69
+ * toggling. */
70
+ export type CartesianTooltipRowContext<T> = {
71
+ visible: readonly ChartSeries<T>[]
72
+ hidden: ReadonlySet<string>
73
+ }
74
+
75
+ export type CartesianTooltipConfig<T> = {
76
+ /**
77
+ * Default true — the tooltip tracks the pointer. Set false to ANCHOR it to the crosshair at the
78
+ * plot's top edge instead, which reads better across a column of charts sharing one cursor
79
+ * (every tooltip then lines up on the same x). Anchoring costs one `getBoundingClientRect` per
80
+ * hovered frame, which is why following stays the default.
81
+ */
82
+ follow?: boolean
83
+ /** Right-aligned badge in the tooltip header (e.g. a status label). */
84
+ label?: (d: T) => { text: string; color: string } | null
85
+ /** Rows rendered BEFORE the derived per-series rows (a total, a context line). The second
86
+ * argument carries the same `visible`/`hidden` the plot draws from, so a hand-authored row
87
+ * stays in sync with legend toggling instead of naming a series the plot no longer draws. */
88
+ prependRows?: (d: T, ctx: CartesianTooltipRowContext<T>) => ReactNode
89
+ /** Rows appended after the derived per-series rows. Same `ctx` as {@link prependRows}. */
90
+ extraRows?: (d: T, ctx: CartesianTooltipRowContext<T>) => ReactNode
91
+ }
92
+
93
+ /** Everything a mark renderer needs. Handed to `CartesianChart`'s child on every render. */
94
+ export type PlotContext<T> = {
95
+ data: readonly T[]
96
+ /** Series minus the ones the legend has toggled off — draw THESE, not `props.series`. */
97
+ visible: ChartSeries<T>[]
98
+ hidden: ReadonlySet<string>
99
+ xScale: PointScale
100
+ yScale: LinearScale
101
+ /** Present only when a `y2` axis is configured. */
102
+ y2Scale: LinearScale | null
103
+ xMax: number
104
+ yMax: number
105
+ margin: ChartMargin
106
+ /** The point the shared cursor currently rests on, or null. */
107
+ cursorPoint: T | null
108
+ /** Series key the legend is hovering, for mark dimming. */
109
+ highlighted: string | null
110
+ }
111
+
112
+ export type CartesianChartProps<T> = {
113
+ data: T[]
114
+ /** Stable id — identifies this chart as the cursor's source. */
115
+ chartId: string
116
+ /** Extracts the x-domain key (a date or category string) from a point. */
117
+ getX: (d: T) => string
118
+ /** The single source of truth for marks, legend entries, and tooltip rows. */
119
+ series: ChartSeries<T>[]
120
+ y?: AxisConfig<T>
121
+ /** Passing `y2` is what makes the chart dual-axis: it draws the right axis and widens the
122
+ * right margin by measurement. Series opt in with `axis: 'right'`. */
123
+ y2?: AxisConfig<T>
124
+ /** Exact number of x ticks. Default: as many as fit (`smartTicks`). */
125
+ xTicks?: number
126
+ /** X tick label formatter. Default `fmtAxisDate` (DD.MM). */
127
+ formatX?: (key: string) => string
128
+ /** Value-range bands on the left scale, drawn behind the marks. */
129
+ zones?: ZoneSpec[]
130
+ /** X-range bands (time windows), drawn behind the marks. */
131
+ xZones?: XZoneSpec[]
132
+ refLines?: { value: number; color: string; dashed?: boolean; axis?: 'left' | 'right' }[]
133
+ height?: number
134
+ aspectRatio?: number
135
+ fill?: boolean
136
+ legend?: ChartLegendConfig | false
137
+ /** `false` disables the tooltip entirely (and with it the crosshair dots). */
138
+ tooltip?: CartesianTooltipConfig<T> | false
139
+ /** Per-side overrides of the measured margins — the escape hatch, applied last. */
140
+ margin?: Partial<ChartMargin>
141
+ /**
142
+ * Where this series' crosshair dot sits, as a value in the axis domain. Defaults to
143
+ * `series.getValue`, which is correct for every unstacked chart. A STACKED chart must override
144
+ * it with the cumulative band top — otherwise its dots sit at each band's raw value, off the
145
+ * line the reader is actually looking at.
146
+ */
147
+ cursorValue?: (
148
+ point: T,
149
+ series: ChartSeries<T>,
150
+ visible: readonly ChartSeries<T>[],
151
+ ) => number | null
152
+ ariaLabel?: string
153
+ isPending?: boolean
154
+ /** Draw ONLY the marks. Everything around them is the primitive's job. */
155
+ children: (ctx: PlotContext<T>) => ReactNode
156
+ }
157
+
158
+ /**
159
+ * Resolve one axis' `[min, max]` from its {@link AxisConfig} and the VISIBLE series. Exported for
160
+ * testing and for a hand-composed kind that needs the same auto-domain law `CartesianChart`
161
+ * applies (rather than reinventing the padding rules per chart).
162
+ */
163
+ export function resolveAxisDomain<T>(
164
+ cfg: AxisConfig<T> | undefined,
165
+ data: readonly T[],
166
+ series: readonly ChartSeries<T>[],
167
+ /**
168
+ * Values that must stay inside the plot even though no series reports them — the bounds of the
169
+ * zones and reference lines pinned to THIS axis. Without them a target zone or a stretch-goal
170
+ * ref line sitting past the data silently clips, which is precisely the case those overlays
171
+ * exist for. Infinite bounds ("top/bottom of axis") are ignored: they clamp to the domain by
172
+ * definition and would otherwise blow it up.
173
+ */
174
+ extraBounds: readonly number[] = [],
175
+ ): [number, number] {
176
+ const domain = cfg?.domain ?? 'auto'
177
+ if (Array.isArray(domain)) return domain
178
+ if (typeof domain === 'function') return domain(data, series)
179
+
180
+ let min = Infinity
181
+ let max = -Infinity
182
+ for (const d of data) {
183
+ for (const s of series) {
184
+ const v = s.getValue(d)
185
+ if (v === null) continue
186
+ if (v < min) min = v
187
+ if (v > max) max = v
188
+ }
189
+ }
190
+ for (const v of extraBounds) {
191
+ if (!Number.isFinite(v)) continue
192
+ if (v < min) min = v
193
+ if (v > max) max = v
194
+ }
195
+ if (min === Infinity) return [0, cfg?.autoMaxFloor ?? 1]
196
+
197
+ const pad = cfg?.autoPad ?? DEFAULT_AUTO_PAD
198
+ const ceil = cfg?.autoMinCeil ?? 0
199
+ // Pad AWAY from zero, never by multiplying: `max * pad` on an all-negative series moves the
200
+ // upper bound further negative (`-5 * 1.1 = -5.5`), i.e. past the data, clipping the largest
201
+ // value out of the plot. Mirrors `padAutoLower`'s reasoning for the lower bound.
202
+ const paddedMax = max > 0 ? max * pad : max < 0 ? max / pad : 0
203
+ const upper = Math.max(paddedMax, cfg?.autoMaxFloor ?? -Infinity)
204
+ const lower = padAutoLower(Math.min(min, ceil), pad)
205
+ // A flat series (every value identical, the all-zero case included) collapses to `[n, n]`,
206
+ // which is a scale with no extent: every point maps to the same pixel and the line renders as a
207
+ // dot on the axis. Give it the same usable baseline the empty-data branch above gets.
208
+ if (lower === upper) return [Math.min(lower, 0), upper === 0 ? 1 : upper * pad]
209
+ return [lower, upper]
210
+ }
211
+
212
+ /**
213
+ * The cartesian chart primitive — the rung that was missing between `ChartFrame` and raw visx
214
+ * (`docs/CHARTS-SPEC.md` §2).
215
+ *
216
+ * It owns, once, everything every chart repeated: measured margins, both y scales and their
217
+ * domains, the x scale and its tick thinning, grid, zones, axes, the shared cursor, the crosshair
218
+ * and its per-series dots, the hover/keyboard overlay, and the derived tooltip. The child draws
219
+ * marks and nothing else, so two charts cannot drift apart in any of those layers — that identity
220
+ * IS the consistency guarantee.
221
+ *
222
+ * Margins are MEASURED from the labels that will actually be painted, so a wide tick label widens
223
+ * its own gutter instead of clipping or needing a hand-tuned `margin` prop.
224
+ */
225
+ export function CartesianChart<T>({
226
+ data,
227
+ chartId,
228
+ getX,
229
+ series,
230
+ y,
231
+ y2,
232
+ xTicks,
233
+ formatX = fmtAxisDate,
234
+ zones,
235
+ xZones,
236
+ refLines,
237
+ height,
238
+ aspectRatio,
239
+ fill,
240
+ legend,
241
+ tooltip,
242
+ margin: marginOverride,
243
+ cursorValue,
244
+ ariaLabel,
245
+ isPending,
246
+ children,
247
+ }: CartesianChartProps<T>): ReactNode {
248
+ const [highlighted, setHighlighted] = useState<string | null>(null)
249
+
250
+ return (
251
+ <ChartFrame
252
+ series={series}
253
+ chartId={chartId}
254
+ {...(height !== undefined && { height })}
255
+ {...(aspectRatio !== undefined && { aspectRatio })}
256
+ {...(fill !== undefined && { fill })}
257
+ {...(ariaLabel !== undefined && { ariaLabel })}
258
+ {...(isPending !== undefined && { isPending })}
259
+ legend={resolveLegend(legend, { highlighted, onHighlight: setHighlighted })}
260
+ >
261
+ {(plot) => (
262
+ <CartesianPlot
263
+ data={data}
264
+ chartId={chartId}
265
+ getX={getX}
266
+ series={series}
267
+ {...(y !== undefined && { y })}
268
+ {...(y2 !== undefined && { y2 })}
269
+ {...(xTicks !== undefined && { xTicks })}
270
+ formatX={formatX}
271
+ {...(zones !== undefined && { zones })}
272
+ {...(xZones !== undefined && { xZones })}
273
+ {...(refLines !== undefined && { refLines })}
274
+ {...(tooltip !== undefined && { tooltip })}
275
+ {...(marginOverride !== undefined && { marginOverride })}
276
+ {...(cursorValue !== undefined && { cursorValue })}
277
+ {...(ariaLabel !== undefined && { ariaLabel })}
278
+ plot={plot}
279
+ highlighted={highlighted}
280
+ >
281
+ {children}
282
+ </CartesianPlot>
283
+ )}
284
+ </ChartFrame>
285
+ )
286
+ }
287
+
288
+ type CartesianPlotProps<T> = Omit<
289
+ CartesianChartProps<T>,
290
+ 'height' | 'aspectRatio' | 'fill' | 'legend' | 'isPending' | 'margin'
291
+ > & {
292
+ plot: { width: number; height: number; hidden: ReadonlySet<string> }
293
+ highlighted: string | null
294
+ marginOverride?: Partial<ChartMargin>
295
+ }
296
+
297
+ /** Split from {@link CartesianChart} so scale + margin work runs only once the frame has resolved
298
+ * a non-empty plot rect (and so the hook order never depends on that rect). */
299
+ function CartesianPlot<T>({
300
+ data,
301
+ chartId,
302
+ getX,
303
+ series,
304
+ y,
305
+ y2,
306
+ xTicks,
307
+ formatX = fmtAxisDate,
308
+ zones,
309
+ xZones,
310
+ refLines,
311
+ tooltip,
312
+ marginOverride,
313
+ cursorValue,
314
+ ariaLabel,
315
+ plot,
316
+ highlighted,
317
+ children,
318
+ }: CartesianPlotProps<T>): ReactNode {
319
+ const { hidden } = plot
320
+
321
+ const visible = useMemo(() => series.filter((s) => !hidden.has(s.key)), [series, hidden])
322
+ const leftSeries = useMemo(() => visible.filter((s) => s.axis !== 'right'), [visible])
323
+ const rightSeries = useMemo(() => visible.filter((s) => s.axis === 'right'), [visible])
324
+
325
+ // Honest deps on the accessors, deliberately: a ref would keep the scales, ticks and margins
326
+ // keyed on `data` alone, and then swapping which field `getX` reads (a field picker over the
327
+ // same rows) would render marks through a new accessor against stale scales. The re-render this
328
+ // costs is narrower than it looks — a cursor move re-renders `CartesianPlot` without changing
329
+ // its props, so hover frames reuse these memos regardless.
330
+ const keys = useMemo(() => data.map(getX), [data, getX])
331
+
332
+ // ── Pass 1: domains + tick labels, both independent of the pixel range ──────────────────────
333
+ // This is what breaks the margin/scale circularity: a linear scale's tick VALUES depend only on
334
+ // its domain, so the labels can be measured before the plot rect exists.
335
+ // Overlay bounds per axis — see `resolveAxisDomain`'s `extraBounds`.
336
+ const [leftBounds, rightBounds] = useMemo(() => {
337
+ const left: number[] = []
338
+ const right: number[] = []
339
+ for (const z of zones ?? []) (z.axisSide === 'right' ? right : left).push(z.from, z.to)
340
+ for (const l of refLines ?? []) (l.axis === 'right' ? right : left).push(l.value)
341
+ return [left, right]
342
+ }, [zones, refLines])
343
+
344
+ const leftDomain = useMemo(
345
+ () => resolveAxisDomain(y, data, leftSeries, leftBounds),
346
+ [y, data, leftSeries, leftBounds],
347
+ )
348
+ const rightDomain = useMemo(
349
+ () => (y2 === undefined ? null : resolveAxisDomain(y2, data, rightSeries, rightBounds)),
350
+ [y2, data, rightSeries, rightBounds],
351
+ )
352
+
353
+ const leftTicks = y?.ticks ?? DEFAULT_TICKS
354
+ const rightTicks = y2?.ticks ?? DEFAULT_TICKS
355
+
356
+ const { labels: leftLabels, format: leftFormat } = useMemo(
357
+ () =>
358
+ probeAxisLabels({
359
+ domain: leftDomain,
360
+ ticks: leftTicks,
361
+ nice: y?.nice ?? false,
362
+ ...(y?.format !== undefined && { format: y.format }),
363
+ }),
364
+ [leftDomain, leftTicks, y?.format, y?.nice],
365
+ )
366
+
367
+ const { labels: rightLabels, format: rightFormat } = useMemo(
368
+ () =>
369
+ rightDomain === null
370
+ ? { labels: [], format: (v: number) => String(v) }
371
+ : probeAxisLabels({
372
+ domain: rightDomain,
373
+ ticks: rightTicks,
374
+ nice: y2?.nice ?? false,
375
+ ...(y2?.format !== undefined && { format: y2.format }),
376
+ }),
377
+ [rightDomain, rightTicks, y2?.format, y2?.nice],
378
+ )
379
+
380
+ const xLabels = useMemo(() => keys.map(formatX), [keys, formatX])
381
+
382
+ const margin = useMemo(
383
+ () =>
384
+ autoMargin({
385
+ left: leftLabels,
386
+ right: rightLabels,
387
+ bottom: xLabels,
388
+ ...(marginOverride !== undefined && { override: marginOverride }),
389
+ }),
390
+ [leftLabels, rightLabels, xLabels, marginOverride],
391
+ )
392
+
393
+ // ── Pass 2: the real scales, now that the plot rect is known ────────────────────────────────
394
+ const xMax = Math.max(plot.width - margin.left - margin.right, 0)
395
+ const yMax = Math.max(plot.height - margin.top - margin.bottom, 0)
396
+
397
+ const xScale = useMemo(
398
+ () => scalePoint<string>({ domain: keys, range: [0, xMax], padding: 0.5 }),
399
+ [keys, xMax],
400
+ )
401
+ const yScale = useMemo(
402
+ () =>
403
+ scaleLinear<number>({
404
+ domain: leftDomain,
405
+ range: [yMax, 0],
406
+ ...(y?.nice === true && { nice: true }),
407
+ }),
408
+ [leftDomain, yMax, y?.nice],
409
+ )
410
+ const y2Scale = useMemo(
411
+ () =>
412
+ rightDomain === null
413
+ ? null
414
+ : scaleLinear<number>({
415
+ domain: rightDomain,
416
+ range: [yMax, 0],
417
+ ...(y2?.nice === true && { nice: true }),
418
+ }),
419
+ [rightDomain, yMax, y2?.nice],
420
+ )
421
+
422
+ const tickValues = useMemo(
423
+ () => (xTicks === undefined ? smartTicks(keys, xMax) : smartTicksEvery(keys, xTicks)),
424
+ [keys, xMax, xTicks],
425
+ )
426
+
427
+ const cursor = useChartCursor<T>({
428
+ data,
429
+ chartId,
430
+ getKey: getX,
431
+ xScale,
432
+ marginLeft: margin.left,
433
+ })
434
+
435
+ const svgRef = useRef<SVGSVGElement>(null)
436
+ const tooltipEnabled = tooltip !== false
437
+ const tooltipCfg = tooltip === false ? undefined : tooltip
438
+ const point = cursor.point
439
+ const cursorX = point === null ? null : (xScale(getX(point)) ?? null)
440
+ const badge = tooltipCfg?.label === undefined || point === null ? null : tooltipCfg.label(point)
441
+
442
+ // Each series falls back to ITS OWN axis's tick format, so a right-axis value is never
443
+ // formatted with the left axis's rules (an explicit per-series `formatValue` still wins).
444
+ const tooltipSeries = useMemo(
445
+ () =>
446
+ visible.map((s) =>
447
+ s.formatValue === undefined
448
+ ? { ...s, formatValue: s.axis === 'right' ? rightFormat : leftFormat }
449
+ : s,
450
+ ),
451
+ [visible, leftFormat, rightFormat],
452
+ )
453
+
454
+ const rows =
455
+ tooltipEnabled && point !== null ? deriveTooltipRows(tooltipSeries, point, leftFormat) : []
456
+
457
+ // Anchored mode resolves the crosshair's plot-local x into viewport space; following mode uses
458
+ // the pointer position `useChartCursor` already recorded.
459
+ const anchorX =
460
+ tooltipCfg?.follow === false && point !== null && cursorX !== null ? cursorX : null
461
+ const svgRect = anchorX === null ? undefined : svgRef.current?.getBoundingClientRect()
462
+ const tooltipAnchor =
463
+ svgRect === undefined || anchorX === null
464
+ ? cursor.anchor
465
+ : { x: svgRect.left + margin.left + anchorX, y: svgRect.top + margin.top }
466
+
467
+ const ctx: PlotContext<T> = {
468
+ data,
469
+ visible,
470
+ hidden,
471
+ xScale,
472
+ yScale,
473
+ y2Scale,
474
+ xMax,
475
+ yMax,
476
+ margin,
477
+ cursorPoint: point,
478
+ highlighted,
479
+ }
480
+
481
+ return (
482
+ <>
483
+ <svg ref={svgRef} width={plot.width} height={plot.height}>
484
+ <Group left={margin.left} top={margin.top}>
485
+ {(y?.grid ?? true) && (
486
+ <GridRows scale={yScale} width={xMax} stroke={VX.grid} numTicks={leftTicks} />
487
+ )}
488
+ {xZones !== undefined && <XZoneRects zones={xZones} height={yMax} xScale={xScale} />}
489
+ {zones !== undefined && (
490
+ <ZoneRects zones={zones} width={xMax} leftScale={yScale} rightScale={y2Scale} />
491
+ )}
492
+
493
+ {children(ctx)}
494
+
495
+ {refLines?.map((line) => {
496
+ const scale = line.axis === 'right' && y2Scale !== null ? y2Scale : yScale
497
+ return (
498
+ <line
499
+ key={`${line.axis ?? 'left'}-${line.value}`}
500
+ x1={0}
501
+ x2={xMax}
502
+ y1={scale(line.value)}
503
+ y2={scale(line.value)}
504
+ stroke={line.color}
505
+ strokeWidth={1}
506
+ strokeDasharray={line.dashed === true ? VX.dashArray : undefined}
507
+ />
508
+ )
509
+ })}
510
+
511
+ {tooltipEnabled && point !== null && cursorX !== null && (
512
+ <>
513
+ <Crosshair x={cursorX} top={0} bottom={yMax} />
514
+ {visible.map((s) => {
515
+ // A dot on a bar is noise — the hovered column is already marked by the crosshair,
516
+ // and the dot would land inside the fill rather than on an edge a reader tracks.
517
+ if (s.mark === 'bar') return null
518
+ const value =
519
+ cursorValue === undefined ? s.getValue(point) : cursorValue(point, s, visible)
520
+ if (value === null) return null
521
+ const scale = s.axis === 'right' && y2Scale !== null ? y2Scale : yScale
522
+ const marker = s.getMarker?.(point)
523
+ return (
524
+ <SeriesDot
525
+ key={s.key}
526
+ cx={cursorX}
527
+ cy={scale(value)}
528
+ color={marker?.color ?? s.color}
529
+ {...(marker?.r !== undefined && { r: marker.r })}
530
+ />
531
+ )
532
+ })}
533
+ </>
534
+ )}
535
+
536
+ <AxisLeftNumeric
537
+ scale={yScale}
538
+ numTicks={leftTicks}
539
+ tickFormat={(v) => leftFormat(Number(v))}
540
+ />
541
+ {y2Scale !== null && (
542
+ <AxisRightNumeric
543
+ scale={y2Scale}
544
+ left={xMax}
545
+ numTicks={rightTicks}
546
+ tickFormat={(v) => rightFormat(Number(v))}
547
+ />
548
+ )}
549
+ <AxisBottomDate
550
+ top={yMax}
551
+ scale={xScale}
552
+ tickValues={tickValues}
553
+ tickFormat={(v) => formatX(String(v))}
554
+ />
555
+
556
+ <HoverOverlay
557
+ width={xMax}
558
+ height={yMax}
559
+ onMove={cursor.onPointerMove}
560
+ onLeave={cursor.onPointerLeave}
561
+ onKeyDown={cursor.onKeyDown}
562
+ onBlur={cursor.onBlur}
563
+ valueMax={Math.max(data.length - 1, 0)}
564
+ {...(point !== null && {
565
+ valueNow: data.indexOf(point),
566
+ valueText: formatX(getX(point)),
567
+ })}
568
+ {...(ariaLabel !== undefined && { ariaLabel })}
569
+ />
570
+ </Group>
571
+ </svg>
572
+
573
+ {tooltipEnabled && cursor.isSource && point !== null && (
574
+ <ChartTooltipFloat anchor={tooltipAnchor}>
575
+ <TooltipHeader
576
+ date={getX(point)}
577
+ {...(badge !== null && { label: badge.text, labelColor: badge.color })}
578
+ />
579
+ <TooltipBody>
580
+ {tooltipCfg?.prependRows?.(point, { visible, hidden })}
581
+ {rows.map((row) => (
582
+ <TooltipRow
583
+ key={row.key}
584
+ color={row.color}
585
+ label={row.label}
586
+ value={row.value}
587
+ shape={row.shape}
588
+ dashed={row.dashed}
589
+ {...(row.strokeWidth !== undefined && { strokeWidth: row.strokeWidth })}
590
+ />
591
+ ))}
592
+ {tooltipCfg?.extraRows?.(point, { visible, hidden })}
593
+ </TooltipBody>
594
+ </ChartTooltipFloat>
595
+ )}
596
+ </>
597
+ )
598
+ }
@@ -65,3 +65,36 @@ describe('a non-pending ChartFrame is unaffected — the legend and body both re
65
65
  expect(markup).not.toContain('aria-busy')
66
66
  })
67
67
  })
68
+
69
+ const twoSeries: SeriesStyle[] = [
70
+ { key: 'a', label: 'Series A', color: '#000', mark: 'line' },
71
+ { key: 'b', label: 'Series B', color: '#111', mark: 'bar' },
72
+ ]
73
+
74
+ describe('legend toggling', () => {
75
+ test('a multi-series legend is interactive by default', () => {
76
+ const markup = renderToStaticMarkup(<ChartFrame series={twoSeries}>{() => <svg />}</ChartFrame>)
77
+ expect(markup).toContain('aria-pressed="true"')
78
+ })
79
+
80
+ test('a single-series legend is not — hiding the only series a chart draws is never useful', () => {
81
+ const markup = renderToStaticMarkup(<ChartFrame series={series}>{() => <svg />}</ChartFrame>)
82
+ expect(markup).not.toContain('aria-pressed')
83
+ })
84
+
85
+ test('`toggle: false` opts out even with several series', () => {
86
+ const markup = renderToStaticMarkup(
87
+ <ChartFrame series={twoSeries} legend={{ toggle: false }}>
88
+ {() => <svg />}
89
+ </ChartFrame>,
90
+ )
91
+ expect(markup).not.toContain('aria-pressed')
92
+ })
93
+
94
+ test('the child receives the (initially empty) hidden set', () => {
95
+ const markup = renderToStaticMarkup(
96
+ <ChartFrame series={twoSeries}>{({ hidden }) => <svg>size:{hidden.size}</svg>}</ChartFrame>,
97
+ )
98
+ expect(markup).toContain('size:0')
99
+ })
100
+ })