basalt-ui 2.10.0 → 2.11.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 (65) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/MIGRATING.md +27 -13
  3. package/agent/rules/basalt-charts.md +2 -2
  4. package/agent/skills/basalt-charts/SKILL.md +16 -17
  5. package/dist/charts/BandStrip.d.ts +3 -2
  6. package/dist/charts/BandStrip.d.ts.map +1 -1
  7. package/dist/charts/CartesianChart.d.ts +3 -0
  8. package/dist/charts/CartesianChart.d.ts.map +1 -1
  9. package/dist/charts/CartesianChart.js +9 -3
  10. package/dist/charts/DualPanel.d.ts.map +1 -1
  11. package/dist/charts/DualPanel.js +20 -15
  12. package/dist/charts/Heatmap.d.ts +33 -3
  13. package/dist/charts/Heatmap.d.ts.map +1 -1
  14. package/dist/charts/Heatmap.js +111 -68
  15. package/dist/charts/Sparkline.d.ts +12 -0
  16. package/dist/charts/Sparkline.d.ts.map +1 -1
  17. package/dist/charts/Sparkline.js +68 -5
  18. package/dist/charts/band-fold.d.ts +7 -0
  19. package/dist/charts/band-fold.d.ts.map +1 -1
  20. package/dist/charts/compile.d.ts +4 -1
  21. package/dist/charts/compile.d.ts.map +1 -1
  22. package/dist/charts/compile.js +22 -14
  23. package/dist/charts/heatmap-fill.d.ts +15 -0
  24. package/dist/charts/heatmap-fill.d.ts.map +1 -0
  25. package/dist/charts/heatmap-fill.js +13 -0
  26. package/dist/charts/host.d.ts +5 -1
  27. package/dist/charts/host.d.ts.map +1 -1
  28. package/dist/charts/host.js +37 -1
  29. package/dist/charts/index.d.ts +1 -1
  30. package/dist/charts/index.d.ts.map +1 -1
  31. package/dist/charts/marks.d.ts +1 -1
  32. package/dist/charts/marks.d.ts.map +1 -1
  33. package/dist/charts/marks.js +28 -13
  34. package/dist/charts/panel.d.ts +7 -1
  35. package/dist/charts/panel.d.ts.map +1 -1
  36. package/dist/charts/panel.js +9 -4
  37. package/dist/charts/plot-context.d.ts +42 -0
  38. package/dist/charts/plot-context.d.ts.map +1 -0
  39. package/dist/charts/plot-context.js +64 -0
  40. package/dist/charts/scales.d.ts +3 -1
  41. package/dist/charts/scales.d.ts.map +1 -1
  42. package/dist/charts/scales.js +23 -5
  43. package/dist/charts/types.d.ts +31 -5
  44. package/dist/charts/types.d.ts.map +1 -1
  45. package/dist/tokens/core.d.ts +6 -0
  46. package/dist/tokens/core.d.ts.map +1 -1
  47. package/dist/tokens/core.js +5 -3
  48. package/llms.txt +12 -4
  49. package/package.json +1 -1
  50. package/src/charts/BandStrip.tsx +2 -5
  51. package/src/charts/CartesianChart.tsx +13 -2
  52. package/src/charts/DualPanel.tsx +21 -16
  53. package/src/charts/Heatmap.tsx +181 -76
  54. package/src/charts/Sparkline.tsx +106 -5
  55. package/src/charts/band-fold.ts +11 -0
  56. package/src/charts/compile.ts +26 -14
  57. package/src/charts/heatmap-fill.ts +19 -0
  58. package/src/charts/host.tsx +59 -0
  59. package/src/charts/index.ts +1 -1
  60. package/src/charts/marks.ts +31 -14
  61. package/src/charts/panel.tsx +18 -5
  62. package/src/charts/plot-context.ts +109 -0
  63. package/src/charts/scales.ts +33 -5
  64. package/src/charts/types.ts +31 -5
  65. package/src/tokens/core.ts +10 -3
package/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # basalt-ui v2.10.0
1
+ # basalt-ui v2.11.0
2
2
  # Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets
3
3
  #
4
4
  # Entry points: use the exact import specifier below; do not guess.
@@ -13,7 +13,7 @@
13
13
  # A subpath's `Install:` line is its required peers; `OptionalPeers:` are import()-only, install on use.
14
14
 
15
15
  Package: basalt-ui
16
- Version: 2.10.0
16
+ Version: 2.11.0
17
17
 
18
18
  ## basalt-ui
19
19
  Import: import { ... } from 'basalt-ui'
@@ -238,6 +238,7 @@ Signature: BandStrip(props: BandStripProps<T, X, K>): ReactElement<unknown, stri
238
238
  data: readonly T[]
239
239
  x: (d: T) => X
240
240
  xTicks?: number | readonly X[]
241
+ xDomain?: readonly [X, X]
241
242
  formatX?: ((x: X) => string)
242
243
  legend?: false | ChartLegendConfig
243
244
  height?: number | ResponsiveChartHeight
@@ -245,7 +246,7 @@ Signature: BandStrip(props: BandStripProps<T, X, K>): ReactElement<unknown, stri
245
246
  cursorGroup?: string
246
247
  cursorResolution?: CursorResolution
247
248
  tooltip?: false | ChartTooltipConfig<T, X>
248
- states: readonly (Pick<ChartSeries<T>, "label" | "legend" | "toolti…
249
+ states: readonly (NamedChartState & { formatValue?: ((d: T) => stri…
249
250
  getBand: (d: T) => BandSpan
250
251
  fold?: BandFold<T>
251
252
  absentState?: K
@@ -258,6 +259,7 @@ Signature: Bars(props: BarsProps<T, X>): ReactElement<unknown, string | JSXEleme
258
259
  y?: AxisConfig<T>
259
260
  y2?: AxisConfig<T>
260
261
  xTicks?: number | readonly X[]
262
+ xDomain?: readonly [X, X]
261
263
  formatX?: ((x: X) => string)
262
264
  zones?: readonly ZoneSpec[]
263
265
  xZones?: readonly XZoneSpec<X>[]
@@ -283,6 +285,7 @@ Signature: CartesianChart(props: CartesianChartProps<T, X>): ReactElement<unknow
283
285
  y?: AxisConfig<T>
284
286
  y2?: AxisConfig<T>
285
287
  xTicks?: number | readonly X[]
288
+ xDomain?: readonly [X, X]
286
289
  formatX?: ((x: X) => string)
287
290
  zones?: readonly ZoneSpec[]
288
291
  xZones?: readonly XZoneSpec<X>[]
@@ -341,7 +344,7 @@ Signature: DualPanel(props: DualPanelProps<T, X>): ReactElement<unknown, string
341
344
  fillBetween?: { from: string; to: string; fill: string; aboveFill?: strin…
342
345
  bar: DualPanelBar<T>
343
346
  topFraction?: number
344
- Signature: Heatmap(props: HeatmapProps<T>): ReactElement<unknown, string | JSXElementConstructor<any>>
347
+ Signature: Heatmap(props: HeatmapProps<T, K>): ReactElement<unknown, string | JSXElementConstructor<any>>
345
348
  className?: string
346
349
  style?: CSSProperties
347
350
  ariaLabel: string
@@ -354,6 +357,9 @@ Signature: Heatmap(props: HeatmapProps<T>): ReactElement<unknown, string | JSXEl
354
357
  color?: string
355
358
  domain?: readonly [number, number]
356
359
  formatValue?: ((v: number) => string)
360
+ formatLegend?: ((v: number) => string)
361
+ getState?: ((d: T) => K | undefined)
362
+ states?: readonly HeatmapState<K>[]
357
363
  formatRow?: ((row: string) => string)
358
364
  formatCol?: ((col: string) => string)
359
365
  legend?: false | { label?: string | undefined; }
@@ -371,6 +377,7 @@ Signature: Lines(props: LinesProps<T, X>): ReactElement<unknown, string | JSXEle
371
377
  y?: AxisConfig<T>
372
378
  y2?: AxisConfig<T>
373
379
  xTicks?: number | readonly X[]
380
+ xDomain?: readonly [X, X]
374
381
  formatX?: ((x: X) => string)
375
382
  zones?: readonly ZoneSpec[]
376
383
  xZones?: readonly XZoneSpec<X>[]
@@ -422,6 +429,7 @@ Signature: StackedArea(props: StackedAreaProps<T, X>): ReactElement<unknown, str
422
429
  data: readonly T[]
423
430
  x: (d: T) => X
424
431
  xTicks?: number | readonly X[]
432
+ xDomain?: readonly [X, X]
425
433
  formatX?: ((x: X) => string)
426
434
  zones?: readonly ZoneSpec[]
427
435
  xZones?: readonly XZoneSpec<X>[]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "2.10.0",
3
+ "version": "2.11.0",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
@@ -21,7 +21,7 @@ import { NON_FINITE } from '../format/shared'
21
21
  import { VX, alpha } from '../tokens'
22
22
  import { CartesianRung } from './CartesianChart'
23
23
  import { groupsOf, resolveNamedState } from './band-fold'
24
- import type { Group } from './band-fold'
24
+ import type { Group, NamedChartState } from './band-fold'
25
25
  import { emphasis } from './marks'
26
26
  import { rowX } from './types'
27
27
  import type {
@@ -35,10 +35,7 @@ import type {
35
35
  } from './types'
36
36
 
37
37
  /** A state a strip can draw. A band has no number to plot, so `formatValue` reads the datum. */
38
- export type BandStripSeries<T> = Pick<
39
- ChartSeries<T>,
40
- 'key' | 'label' | 'color' | 'tooltip' | 'legend' | 'note' | 'fillOpacity'
41
- > & {
38
+ export type BandStripSeries<T> = NamedChartState & {
42
39
  /**
43
40
  * The tooltip row's value for a band in this state. `null` is an ABSENT reading and renders an
44
41
  * em dash; omit the function when the state's name is the whole reading ("Not measured").
@@ -11,6 +11,8 @@ import type { CSSProperties, ReactElement, ReactNode } from 'react'
11
11
  import { useInChartCard } from './card-context'
12
12
  import { compileCartesian, refLegendSeries } from './compile'
13
13
  import type { CartesianDefinition } from './compile'
14
+ import { samePlots } from './plot-context'
15
+ import type { PlotSizes } from './plot-context'
14
16
  import { ChartEngine, idPrefixOf } from './host'
15
17
  import { ChartLegend, legendEntries } from './legend'
16
18
  import { INITIAL_WIDTH, useChartSize } from './sizing'
@@ -69,6 +71,8 @@ export type ShellContext = {
69
71
  coarse: boolean
70
72
  /** The measured width; 0 unless the shell was asked to track it (`byWidth`). */
71
73
  width: number
74
+ /** The plot area of each pane the engine last laid out; `null` until it has. */
75
+ plot: PlotSizes | null
72
76
  }
73
77
 
74
78
  export type ChartShellProps<T> = Pick<
@@ -99,9 +103,15 @@ export function ChartShell<T>(props: ChartShellProps<T>): ReactElement {
99
103
  // Unmeasured (the server, the first client frame) is the regular class, as the engine's
100
104
  // `initialWidth` is.
101
105
  const width = byWidth ? measured || INITIAL_WIDTH : 0
106
+ // The engine lays the plot out AFTER `marks` runs, so a chart whose marks read the plot size
107
+ // (and only that chart) takes it from the layout and recompiles once.
108
+ const [plot, setPlot] = useState<PlotSizes | null>(null)
109
+ const onPlot = useCallback((next: PlotSizes) => {
110
+ setPlot((prev) => (samePlots(prev, next) ? prev : next))
111
+ }, [])
102
112
  const definition = useMemo(
103
- () => compile({ chartId, hidden, highlighted, coarse, width }),
104
- [compile, chartId, hidden, highlighted, coarse, width],
113
+ () => compile({ chartId, hidden, highlighted, coarse, width, plot }),
114
+ [compile, chartId, hidden, highlighted, coarse, width, plot],
105
115
  )
106
116
 
107
117
  // ── legend: micro has none, compact shows dots, regular and wide show chips (CSS, § 9.6) ──────
@@ -153,6 +163,7 @@ export function ChartShell<T>(props: ChartShellProps<T>): ReactElement {
153
163
  height={height}
154
164
  idPrefix={idPrefixOf(chartId)}
155
165
  coarse={coarse}
166
+ onPlot={onPlot}
156
167
  />
157
168
  ) : (
158
169
  <ChartPlaceholder state={state} height={height} />
@@ -18,10 +18,11 @@ import { defaultFormatX, defaultNumberFormat, engineRow, seriesRow, visibleSerie
18
18
  import { barMark, emphasis, lineMark, markersOf, thinFill } from './marks'
19
19
  import { PanelRung, chartHeightOf, paneX, paneY, rowsOf } from './panel'
20
20
  import type { PaneBuilder, PanelInput, PanelPlan } from './panel'
21
+ import { plotContext } from './plot-context'
21
22
  import type { SignedSeries } from './legend'
22
23
  import { xScaleFor } from './scales'
23
24
  import { rowX } from './types'
24
- import type { CartesianChartProps, ChartSeries, PlotContext, PlotRow } from './types'
25
+ import type { CartesianChartProps, ChartSeries, PlotRow } from './types'
25
26
 
26
27
  // ── DualPanel ───────────────────────────────────────────────────────────────────────────────────
27
28
 
@@ -228,23 +229,27 @@ export function DualPanel<T, X extends Date | number = Date | number>(
228
229
  }
229
230
  }
230
231
 
231
- const topPane: PaneBuilder = ({ width, height: h }) => {
232
+ const topPane: PaneBuilder = ({ width, height: h, plot: access }) => {
232
233
  const cls = resolveContainerClass(width)
233
- const plot: PlotContext<T, Date | number> = {
234
- rows: (key) => {
235
- const s = lines.find((l) => l.key === key)
236
- if (!s) throw new Error(`[basalt] DualPanel: no series "${key}"`)
237
- return rows(s)
234
+ const plot = plotContext<T, Date | number>(
235
+ {
236
+ rows: (key) => {
237
+ const s = lines.find((l) => l.key === key)
238
+ if (!s) throw new Error(`[basalt] DualPanel: no series "${key}"`)
239
+ return rows(s)
240
+ },
241
+ visible,
242
+ highlighted,
243
+ containerClass: cls,
244
+ width,
245
+ height: h,
246
+ data,
247
+ y2: undefined,
248
+ yDomain: topDomain,
249
+ y2Domain: undefined,
238
250
  },
239
- visible,
240
- highlighted,
241
- containerClass: cls,
242
- width,
243
- height: h,
244
- y2: undefined,
245
- yDomain: topDomain,
246
- y2Domain: undefined,
247
- }
251
+ access,
252
+ )
248
253
  return {
249
254
  marks: [
250
255
  ...(fill
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * `Heatmap` — a band × band matrix of `cell` marks (`docs/V2-SPEC.md` § 9.3). Intensity is ABSOLUTE:
3
3
  * the color scale spans `domain` (default `[0, max]`), never each row's own range, so two grids on
4
- * one page read against the same ink. A cell with no datum, or a `null` value, is ABSENT: a flat
5
- * `--vx-neutral` fill, no hatch. There is no cursor and no crosshair — the tooltip is per cell, its
6
- * rows are `tooltip.rows(d)` data.
4
+ * one page read against the same ink. A cell with a datum but a `null` value is ABSENT: a flat
5
+ * `--vx-neutral` fill, no hatch; a cell the consumer names a `states` entry for (failed, idle, …)
6
+ * draws that state's flat fill instead, legended next to the gradient. A position with NO datum is
7
+ * inert: it paints the absent fill and answers no pointer — no tooltip, no snap to a neighbour.
8
+ * There is no cursor and no crosshair — the tooltip is per cell, its rows are `tooltip.rows(d)` data.
7
9
  */
8
10
  import { colorGradientLegend } from '@tanstack/charts/legend'
9
- import { decorative } from '@tanstack/charts/mark/decorative'
10
11
  import { cell } from '@tanstack/charts/rect'
11
12
  import { scaleBand } from '@tanstack/charts/scales/band'
12
13
  import { tooltip as tooltipHost } from '@tanstack/charts/tooltip'
@@ -20,14 +21,28 @@ import { alpha, VX } from '../tokens'
20
21
  import { resolveContainerClass } from '../tokens/size-classes'
21
22
  import { engineRow, strideTicks } from './compile'
22
23
  import type { CartesianDefinition } from './compile'
24
+ import { resolveNamedState } from './band-fold'
25
+ import type { NamedChartState } from './band-fold'
26
+ import { ABSENT_OPACITY, RAMP_LEVELS, RAMP_OPACITIES } from './heatmap-fill'
23
27
  import { ChartEngine, idPrefixOf } from './host'
28
+ import { ChartLegend } from './legend'
24
29
  import { useCoarsePointer } from '../common/use-media-query'
25
30
  import { HEIGHT_MAX, HEIGHT_MIN } from './box'
26
31
  import { ChartPlaceholder, resolveChartState } from './state'
27
32
  import { AXIS_LINE, CHART_THEME } from './theme'
28
- import type { ChartState, ChartTooltipRow, ResponsiveChartHeight } from './types'
33
+ import type { ChartSeries, ChartState, ChartTooltipRow, ResponsiveChartHeight } from './types'
29
34
 
30
- export type HeatmapProps<T> = BasaltProps & {
35
+ /**
36
+ * A named cell state, the same base `BandStrip`'s `states` use (`NamedChartState`): `color` and
37
+ * `fillOpacity` (default 1) are its flat fill, `label` its legend entry and tooltip reading, `note`
38
+ * a muted qualifier after the label in the legend, `legend: false` keeps it out of the legend.
39
+ * `tooltip` is omitted: a cell's tooltip always names its state, so there is no row to hide.
40
+ */
41
+ export type HeatmapState<K extends string = string> = Omit<NamedChartState, 'key' | 'tooltip'> & {
42
+ key: K
43
+ }
44
+
45
+ export type HeatmapProps<T, K extends string = string> = BasaltProps & {
31
46
  /** The accessible name. Required. */
32
47
  ariaLabel: string
33
48
  data: readonly T[]
@@ -44,15 +59,42 @@ export type HeatmapProps<T> = BasaltProps & {
44
59
  color?: string | undefined
45
60
  /** The value range the color scale spans. Default `[0, max]` of the data. */
46
61
  domain?: readonly [number, number] | undefined
47
- /** Tooltip, legend-end and `aria` value format. Default: the number as-is. */
62
+ /** Tooltip value format. Default: the number as-is. */
48
63
  formatValue?: ((v: number) => string) | undefined
64
+ /**
65
+ * The gradient legend's two end labels. Default: `formatValue`. The engine labels only the ends
66
+ * (a 240px ramp), so a unit-bearing `formatValue` ("50.0% below fastest hour") overlaps its
67
+ * neighbour there — pass a compact form ("50%") when the tooltip's reads long.
68
+ */
69
+ formatLegend?: ((v: number) => string) | undefined
70
+ /**
71
+ * The state a datum is in, a `states` key, or `undefined` for the plain value ramp. A stated cell
72
+ * draws its state's flat fill whatever its value, and — not being a measurement — does NOT
73
+ * contribute to the default `[0, max]` domain; pass `domain` to pin it. Memoize it: a new
74
+ * function recompiles the chart.
75
+ */
76
+ getState?: ((d: T) => K | undefined) | undefined
77
+ /**
78
+ * The named states `getState` may return, legended after the gradient (hidden with
79
+ * `legend={false}`). Without `getState` they draw and legend nothing.
80
+ */
81
+ states?: readonly HeatmapState<K>[] | undefined
49
82
  /** Band tick and tooltip header labels. Default: the band key. */
50
83
  formatRow?: ((row: string) => string) | undefined
51
84
  formatCol?: ((col: string) => string) | undefined
52
85
  /** `false` hides the gradient legend; `label` titles it. */
53
86
  legend?: false | { label?: string | undefined } | undefined
54
87
  /** Rows after the value row, per cell (a sample count, a failure reason). Called with the datum. */
55
- tooltip?: (false | { rows?: ((d: T) => readonly ChartTooltipRow[]) | undefined }) | undefined
88
+ tooltip?:
89
+ | (
90
+ | false
91
+ | {
92
+ rows?: ((d: T) => readonly ChartTooltipRow[]) | undefined
93
+ /** The value row's label. Default "Value". */
94
+ valueLabel?: string | undefined
95
+ }
96
+ )
97
+ | undefined
56
98
  /** A fixed height, or one per container class. Default: by row count (160–420px). */
57
99
  height?: number | ResponsiveChartHeight | undefined
58
100
  /** Fill the parent's height instead. Overrides `height`. CSS-owned like every other kind's box
@@ -62,28 +104,47 @@ export type HeatmapProps<T> = BasaltProps & {
62
104
  state?: ChartState | undefined
63
105
  }
64
106
 
65
- /** Intensity steps: quantized, so the gradient legend and the cells are the same ramp. */
66
- const LEVELS = 8
67
- const MIN_LEVEL = 0.14
68
107
  const ROW_PITCH = 26
69
108
  const CHROME = 64
70
109
  const CELL_INSET = 1
71
110
 
72
111
  /** One grid position. `id` is its row-major index: the mark key, so no row/col pair can collide. */
73
- type Cell<T> = { id: number; row: string; col: string; value: number | null; datum: T | undefined }
112
+ type Cell<T, K extends string> = {
113
+ id: number
114
+ row: string
115
+ col: string
116
+ value: number | null
117
+ datum: T | undefined
118
+ state: K | undefined
119
+ }
74
120
 
75
121
  const identityLabel = (band: string): string => band
76
122
 
77
123
  const firstSeen = (keys: Iterable<string>): string[] => [...new Set(keys)]
78
124
 
79
- const ramp = (color: string): string[] =>
80
- Array.from({ length: LEVELS }, (_, i) =>
81
- alpha(color, MIN_LEVEL + ((1 - MIN_LEVEL) * i) / (LEVELS - 1)),
82
- )
125
+ const ramp = (color: string): string[] => RAMP_OPACITIES.map((a) => alpha(color, a))
126
+
127
+ const noneHidden: ReadonlySet<string> = new Set()
128
+ const noop = (): void => {}
129
+
130
+ const noStates: readonly never[] = []
131
+
132
+ /** The value row of a cell's tooltip: its state's label, "No data", or the formatted value. */
133
+ function valueRows<K extends string>(
134
+ c: Cell<unknown, K>,
135
+ named: HeatmapState<K> | undefined,
136
+ label: string,
137
+ formatValue: (v: number) => string,
138
+ pointColor: string | undefined,
139
+ ): ChartTooltipRow[] {
140
+ if (named) return [{ label, value: named.label, color: named.color }]
141
+ if (c.value === null) return [{ label, value: 'No data' }]
142
+ return [{ label, value: formatValue(c.value), ...(pointColor && { color: pointColor }) }]
143
+ }
83
144
 
84
145
  const fillStyle: CSSProperties = { position: 'relative', height: '100%', minHeight: HEIGHT_MIN }
85
146
 
86
- export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
147
+ export function Heatmap<T, K extends string = string>(props: HeatmapProps<T, K>): ReactElement {
87
148
  const {
88
149
  ariaLabel,
89
150
  data,
@@ -93,6 +154,9 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
93
154
  color = VX.line,
94
155
  domain,
95
156
  formatValue = String,
157
+ formatLegend = formatValue,
158
+ getState,
159
+ states = noStates,
96
160
  formatRow = identityLabel,
97
161
  formatCol = identityLabel,
98
162
  legend,
@@ -108,7 +172,9 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
108
172
  const showLegend = legend !== false
109
173
  const legendLabel = legend === false ? undefined : legend?.label
110
174
  const showTooltip = tooltip !== false
111
- const tooltipRows = tooltip === false ? undefined : tooltip?.rows
175
+ const tooltipConfig = tooltip === false ? undefined : tooltip
176
+ const tooltipRows = tooltipConfig?.rows
177
+ const valueLabel = tooltipConfig?.valueLabel ?? 'Value'
112
178
  const rows = useMemo(() => props.rows ?? firstSeen(data.map(getRow)), [props.rows, data, getRow])
113
179
  const cols = useMemo(() => props.cols ?? firstSeen(data.map(getCol)), [props.cols, data, getCol])
114
180
  const statedHeight =
@@ -116,6 +182,10 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
116
182
  const coarse = useCoarsePointer()
117
183
  const boxHeight = matchHeight ? 'fill' : statedHeight
118
184
 
185
+ // Resolved per datum below; a key naming nothing throws in dev, paints the ramp in production.
186
+ const stateKeys = useMemo(() => states.map((s) => s.key), [states])
187
+ const stateByKey = useMemo(() => new Map(states.map((s) => [s.key, s])), [states])
188
+
119
189
  const definition = useMemo<CartesianDefinition>(() => {
120
190
  const byBand = new Map<string, Map<string, T>>()
121
191
  for (const d of data) {
@@ -124,18 +194,34 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
124
194
  inRow.set(getCol(d), d)
125
195
  byBand.set(row, inRow)
126
196
  }
127
- // One pass: split the grid into measured, absent-with-a-datum and absent-with-none.
128
- const present: Cell<T>[] = []
129
- const absentWithDatum: Cell<T>[] = []
130
- const absentEmpty: Cell<T>[] = []
197
+ // One pass: split the grid into measured, stated, absent-with-a-datum and absent-with-none.
198
+ const present: Cell<T, K>[] = []
199
+ const stated = new Map<K, Cell<T, K>[]>()
200
+ const absentWithDatum: Cell<T, K>[] = []
201
+ const absentEmpty: Cell<T, K>[] = []
131
202
  let max = 0
132
203
  for (const [r, row] of rows.entries()) {
133
204
  for (const [c, col] of cols.entries()) {
134
205
  const datum = byBand.get(row)?.get(col)
135
206
  const raw = datum === undefined ? null : getValue(datum)
136
207
  const value = raw !== null && Number.isFinite(raw) ? raw : null
137
- const cellAt: Cell<T> = { id: r * cols.length + c, row, col, datum, value }
138
- if (value !== null) {
208
+ const stateKey =
209
+ datum === undefined || getState === undefined
210
+ ? undefined
211
+ : resolveNamedState('Heatmap', 'Heatmap.getState', getState(datum), stateKeys)
212
+ const cellAt: Cell<T, K> = {
213
+ id: r * cols.length + c,
214
+ row,
215
+ col,
216
+ datum,
217
+ value,
218
+ state: stateKey,
219
+ }
220
+ if (stateKey !== undefined) {
221
+ const bucket = stated.get(stateKey) ?? []
222
+ bucket.push(cellAt)
223
+ stated.set(stateKey, bucket)
224
+ } else if (value !== null) {
139
225
  present.push(cellAt)
140
226
  max = Math.max(max, value)
141
227
  } else if (datum === undefined) absentEmpty.push(cellAt)
@@ -147,7 +233,28 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
147
233
  const scale = scaleQuantize<string>()
148
234
  .domain([lo, hi > lo ? hi : lo + 1])
149
235
  .range(ramp(color))
150
- const header = (c: Cell<T>): string => `${formatRow(c.row)} · ${formatCol(c.col)}`
236
+ const header = (c: Cell<T, K>): string => `${formatRow(c.row)} · ${formatCol(c.col)}`
237
+ // One builder for every cell mark; `paint` is the fill (flat, or the ramp's `color` channel).
238
+ const cellMark = (id: string, group: Cell<T, K>[], paint: Record<string, unknown>) =>
239
+ cell(group, { id, x: 'col', y: 'row', inset: CELL_INSET, key: 'id', ...paint })
240
+ const tooltipOptions = showTooltip
241
+ ? {
242
+ use: tooltipHost,
243
+ portal,
244
+ content: (points: readonly ChartPoint[]) => {
245
+ const point = points[0]
246
+ const c = point?.datum as Cell<T, K> | undefined
247
+ // A position with no datum is hit-tested (so it never snaps to a neighbour) but inert.
248
+ if (!point || !c || c.datum === undefined) return { rows: [] }
249
+ const named = c.state === undefined ? undefined : stateByKey.get(c.state)
250
+ const rows = [
251
+ ...valueRows(c, named, valueLabel, formatValue, point.color),
252
+ ...(tooltipRows?.(c.datum) ?? []),
253
+ ]
254
+ return { title: header(c), rows: rows.map(engineRow) }
255
+ },
256
+ }
257
+ : (false as const)
151
258
 
152
259
  return {
153
260
  chart: ({ width }: ChartBuildContext): StoredChartSpec => {
@@ -159,33 +266,18 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
159
266
  thin: true,
160
267
  }
161
268
  const marks = [
162
- decorative(
163
- cell(absentEmpty, {
164
- id: 'absent-empty',
165
- x: 'col',
166
- y: 'row',
167
- fill: VX.neutral,
168
- fillOpacity: 0.12,
169
- inset: CELL_INSET,
170
- }),
171
- ),
172
- cell(absentWithDatum, {
173
- id: 'absent',
174
- x: 'col',
175
- y: 'row',
176
- fill: VX.neutral,
177
- fillOpacity: 0.12,
178
- inset: CELL_INSET,
179
- key: 'id',
180
- }),
181
- cell(present, {
182
- id: 'cells',
183
- x: 'col',
184
- y: 'row',
185
- color: 'value',
186
- inset: CELL_INSET,
187
- key: 'id',
269
+ // Inert, not decorative: it must still win the hit test, so a pointer over an empty
270
+ // position lands on THIS cell (whose tooltip is empty) instead of snapping to a neighbour.
271
+ cellMark('absent-empty', absentEmpty, { fill: VX.neutral, fillOpacity: ABSENT_OPACITY }),
272
+ cellMark('absent', absentWithDatum, { fill: VX.neutral, fillOpacity: ABSENT_OPACITY }),
273
+ ...[...stated].map(([key, group]) => {
274
+ const named = stateByKey.get(key)
275
+ return cellMark(`state:${key}`, group, {
276
+ fill: named?.color ?? VX.neutral,
277
+ ...(named?.fillOpacity !== undefined && { fillOpacity: named.fillOpacity }),
278
+ })
188
279
  }),
280
+ cellMark('cells', present, { color: 'value' }),
189
281
  ]
190
282
  return {
191
283
  marks,
@@ -215,8 +307,8 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
215
307
  scale,
216
308
  ...(showLegend && {
217
309
  legend: colorGradientLegend({
218
- steps: LEVELS,
219
- format: formatValue,
310
+ steps: RAMP_LEVELS,
311
+ format: formatLegend,
220
312
  placement: 'bottom',
221
313
  ...(legendLabel !== undefined && { label: legendLabel }),
222
314
  }),
@@ -225,29 +317,7 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
225
317
  theme: CHART_THEME,
226
318
  }
227
319
  },
228
- tooltip: showTooltip
229
- ? {
230
- use: tooltipHost,
231
- portal,
232
- content: (points: readonly ChartPoint[]) => {
233
- const point = points[0]
234
- const c = point?.datum as Cell<T> | undefined
235
- if (!point || !c) return { rows: [] }
236
- const extra = c.datum === undefined ? [] : (tooltipRows?.(c.datum) ?? [])
237
- const value: readonly ChartTooltipRow[] =
238
- c.value === null
239
- ? [{ label: 'Value', value: 'No data' }]
240
- : [
241
- {
242
- label: 'Value',
243
- value: formatValue(c.value),
244
- ...(point.color && { color: point.color }),
245
- },
246
- ]
247
- return { title: header(c), rows: [...value, ...extra].map(engineRow) }
248
- },
249
- }
250
- : false,
320
+ tooltip: tooltipOptions,
251
321
  }
252
322
  }, [
253
323
  data,
@@ -259,6 +329,11 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
259
329
  color,
260
330
  domain,
261
331
  formatValue,
332
+ formatLegend,
333
+ getState,
334
+ stateKeys,
335
+ stateByKey,
336
+ valueLabel,
262
337
  formatRow,
263
338
  formatCol,
264
339
  legendLabel,
@@ -267,6 +342,24 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
267
342
  tooltipRows,
268
343
  ])
269
344
 
345
+ // Legend-only series (`getValue` is always null). Without `getState` the states are never
346
+ // drawn, so they are never legended either.
347
+ const legendSeries = useMemo<ChartSeries<T>[]>(
348
+ () =>
349
+ getState === undefined
350
+ ? []
351
+ : states.map((s) => ({
352
+ key: s.key,
353
+ label: s.label,
354
+ color: s.color,
355
+ mark: 'bar' as const,
356
+ ...(s.fillOpacity !== undefined && { fillOpacity: s.fillOpacity }),
357
+ ...(s.legend !== undefined && { legend: s.legend }),
358
+ ...(s.note !== undefined && { note: s.note }),
359
+ getValue: () => null,
360
+ })),
361
+ [states, getState],
362
+ )
270
363
  const resolved = resolveChartState(state)
271
364
  return (
272
365
  <div
@@ -285,6 +378,18 @@ export function Heatmap<T>(props: HeatmapProps<T>): ReactElement {
285
378
  ) : (
286
379
  <ChartPlaceholder state={state} height={boxHeight} />
287
380
  )}
381
+ {showLegend && legendSeries.length > 0 && (
382
+ <ChartLegend
383
+ series={legendSeries}
384
+ hidden={noneHidden}
385
+ mode="chips"
386
+ groups={false}
387
+ toggle={false}
388
+ onToggle={noop}
389
+ onHighlight={noop}
390
+ concealed={resolved !== null}
391
+ />
392
+ )}
288
393
  </div>
289
394
  )
290
395
  }