basalt-ui 2.9.1 → 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 (82) hide show
  1. package/CHANGELOG.md +61 -38
  2. package/MIGRATING.md +34 -12
  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 +9 -6
  6. package/dist/charts/BandStrip.d.ts.map +1 -1
  7. package/dist/charts/BandStrip.js +8 -8
  8. package/dist/charts/CartesianChart.d.ts +3 -0
  9. package/dist/charts/CartesianChart.d.ts.map +1 -1
  10. package/dist/charts/CartesianChart.js +13 -6
  11. package/dist/charts/DualPanel.d.ts.map +1 -1
  12. package/dist/charts/DualPanel.js +20 -15
  13. package/dist/charts/Heatmap.d.ts +33 -3
  14. package/dist/charts/Heatmap.d.ts.map +1 -1
  15. package/dist/charts/Heatmap.js +111 -68
  16. package/dist/charts/MirroredBars.d.ts +16 -5
  17. package/dist/charts/MirroredBars.d.ts.map +1 -1
  18. package/dist/charts/MirroredBars.js +46 -9
  19. package/dist/charts/Sparkline.d.ts +12 -0
  20. package/dist/charts/Sparkline.d.ts.map +1 -1
  21. package/dist/charts/Sparkline.js +68 -5
  22. package/dist/charts/band-fold.d.ts +13 -0
  23. package/dist/charts/band-fold.d.ts.map +1 -1
  24. package/dist/charts/band-fold.js +11 -1
  25. package/dist/charts/compile.d.ts +4 -1
  26. package/dist/charts/compile.d.ts.map +1 -1
  27. package/dist/charts/compile.js +22 -14
  28. package/dist/charts/heatmap-fill.d.ts +15 -0
  29. package/dist/charts/heatmap-fill.d.ts.map +1 -0
  30. package/dist/charts/heatmap-fill.js +13 -0
  31. package/dist/charts/host.d.ts +5 -1
  32. package/dist/charts/host.d.ts.map +1 -1
  33. package/dist/charts/host.js +37 -1
  34. package/dist/charts/index.d.ts +1 -1
  35. package/dist/charts/index.d.ts.map +1 -1
  36. package/dist/charts/legend.d.ts +2 -0
  37. package/dist/charts/legend.d.ts.map +1 -1
  38. package/dist/charts/legend.js +14 -10
  39. package/dist/charts/marks.d.ts +1 -1
  40. package/dist/charts/marks.d.ts.map +1 -1
  41. package/dist/charts/marks.js +28 -13
  42. package/dist/charts/panel.d.ts +7 -1
  43. package/dist/charts/panel.d.ts.map +1 -1
  44. package/dist/charts/panel.js +9 -4
  45. package/dist/charts/plot-context.d.ts +42 -0
  46. package/dist/charts/plot-context.d.ts.map +1 -0
  47. package/dist/charts/plot-context.js +64 -0
  48. package/dist/charts/scales.d.ts +3 -1
  49. package/dist/charts/scales.d.ts.map +1 -1
  50. package/dist/charts/scales.js +23 -5
  51. package/dist/charts/types.d.ts +36 -4
  52. package/dist/charts/types.d.ts.map +1 -1
  53. package/dist/controls/enum-filter.d.ts +4 -1
  54. package/dist/controls/enum-filter.d.ts.map +1 -1
  55. package/dist/controls/enum-filter.js +2 -1
  56. package/dist/controls/number-filter.d.ts.map +1 -1
  57. package/dist/controls/number-filter.js +2 -0
  58. package/dist/tokens/core.d.ts +6 -0
  59. package/dist/tokens/core.d.ts.map +1 -1
  60. package/dist/tokens/core.js +5 -3
  61. package/llms.txt +17 -8
  62. package/package.json +1 -1
  63. package/src/charts/BandStrip.tsx +19 -20
  64. package/src/charts/CartesianChart.tsx +16 -4
  65. package/src/charts/DualPanel.tsx +21 -16
  66. package/src/charts/Heatmap.tsx +181 -76
  67. package/src/charts/MirroredBars.tsx +71 -18
  68. package/src/charts/Sparkline.tsx +106 -5
  69. package/src/charts/band-fold.ts +32 -0
  70. package/src/charts/compile.ts +26 -14
  71. package/src/charts/heatmap-fill.ts +19 -0
  72. package/src/charts/host.tsx +59 -0
  73. package/src/charts/index.ts +1 -1
  74. package/src/charts/legend.tsx +21 -12
  75. package/src/charts/marks.ts +31 -14
  76. package/src/charts/panel.tsx +18 -5
  77. package/src/charts/plot-context.ts +109 -0
  78. package/src/charts/scales.ts +33 -5
  79. package/src/charts/types.ts +36 -4
  80. package/src/controls/enum-filter.tsx +5 -1
  81. package/src/controls/number-filter.tsx +6 -1
  82. package/src/tokens/core.ts +10 -3
@@ -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
  }
@@ -9,7 +9,7 @@
9
9
  * configure — its zero IS the baseline.
10
10
  *
11
11
  * ABSENCE is a state a reader cannot decode from either axis, so it is drawn across the full height
12
- * of both panes in one flat `--vx-neutral` fill: a `getAbsentFraction` share of a bar's width that no
12
+ * of both panes in one flat fill (`--vx-neutral`, or the `absentState` entry's colour): a `getAbsentFraction` share of a bar's width that no
13
13
  * source sample covers. A bar that measured zero draws nothing; an absent one draws neutral.
14
14
  */
15
15
  import { decorative } from '@tanstack/charts/mark/decorative'
@@ -26,7 +26,7 @@ import { barMark, emphasis } from './marks'
26
26
  import { PanelRung, chartHeightOf, paneX, paneY, rowsOf } from './panel'
27
27
  import type { PaneBuilder, PanelInput, PanelPlan } from './panel'
28
28
  import { xScaleFor } from './scales'
29
- import { foldBands } from './band-fold'
29
+ import { foldBands, resolveNamedState } from './band-fold'
30
30
  import { rowX } from './types'
31
31
  import type { CartesianChartProps, ChartSeries, ChartX, PlotRow } from './types'
32
32
 
@@ -46,12 +46,16 @@ export type MirroredBarPane = {
46
46
  }
47
47
 
48
48
  /** A bar series. Any entry that is neither pane is legend-only (give it `getValue: () => null`). */
49
- export type MirroredBarsSeries<T> = Pick<
49
+ export type MirroredBarsSeries<T, K extends string = string> = Pick<
50
50
  ChartSeries<T>,
51
- 'key' | 'label' | 'color' | 'getValue' | 'formatValue' | 'tooltip' | 'legend' | 'role' | 'note'
52
- >
51
+ 'label' | 'color' | 'getValue' | 'formatValue' | 'tooltip' | 'legend' | 'role' | 'note'
52
+ > & {
53
+ key: K
54
+ /** Read for the `absentState` entry only (its fill and swatch); the panes draw at full colour. */
55
+ fillOpacity?: number | undefined
56
+ }
53
57
 
54
- export type MirroredBarsProps<T, X extends ChartX = ChartX> = Pick<
58
+ export type MirroredBarsProps<T, X extends ChartX = ChartX, K extends string = string> = Pick<
55
59
  CartesianChartProps<T, X>,
56
60
  | 'ariaLabel'
57
61
  | 'data'
@@ -66,15 +70,22 @@ export type MirroredBarsProps<T, X extends ChartX = ChartX> = Pick<
66
70
  | 'style'
67
71
  > & {
68
72
  /** The single source of colours, legend entries and tooltip rows. */
69
- series: readonly MirroredBarsSeries<T>[]
73
+ series: readonly MirroredBarsSeries<T, K>[]
70
74
  /** Drawn above the baseline. */
71
75
  up: MirroredBarPane
72
76
  /** Drawn below the baseline. */
73
77
  down: MirroredBarPane
74
78
  /** The up pane's share of the height. Default 0.35: the pair is usually asymmetric. */
75
79
  upFraction?: number | undefined
76
- /** 0..1 of a bar's width that no source sample covers, drawn neutral across both panes. */
80
+ /** 0..1 of a bar's width that no source sample covers, drawn across both panes. */
77
81
  getAbsentFraction?: ((d: T) => number) | undefined
82
+ /**
83
+ * The `series` key that names the absent share: its colour fills it and its legend entry labels
84
+ * it (give it `getValue: () => null`, it is legend-only). `BandStrip.absentState`'s shape. Its
85
+ * colour must differ from every measured series', not only by alpha. Default: a flat
86
+ * `--vx-neutral` with no legend entry. A key naming no entry throws.
87
+ */
88
+ absentState?: K | undefined
78
89
  /** Per-datum bar opacity: a real but qualified measurement (a short bucket) drawn dimmer. */
79
90
  getBarOpacity?: ((d: T) => number) | undefined
80
91
  /**
@@ -122,18 +133,42 @@ function assertPaneKey<T>(
122
133
  )
123
134
  }
124
135
 
125
- export function MirroredBars<T, X extends ChartX = ChartX>(
126
- props: MirroredBarsProps<T, X>,
136
+ export function MirroredBars<T, X extends ChartX = ChartX, K extends string = string>(
137
+ props: MirroredBarsProps<T, X, K>,
127
138
  ): ReactElement {
128
- const { data, x, series, up, down, upFraction = DEFAULT_UP_FRACTION, ...more } = props
129
- const { getAbsentFraction, getBarOpacity, fold: foldConfig, cursorResolution = 'leading' } = more
130
- const { getAbsentFraction: _a, getBarOpacity: _b, fold: _f, cursorResolution: _c, ...rung } = more
139
+ const {
140
+ data,
141
+ x,
142
+ series,
143
+ up,
144
+ down,
145
+ upFraction = DEFAULT_UP_FRACTION,
146
+ getAbsentFraction,
147
+ getBarOpacity,
148
+ fold: foldConfig,
149
+ cursorResolution = 'leading',
150
+ absentState,
151
+ ...rung
152
+ } = props
131
153
  const { formatX } = rung
132
154
 
155
+ const absentKey = resolveNamedState(
156
+ 'MirroredBars',
157
+ 'absentState',
158
+ absentState,
159
+ series.map((s) => s.key),
160
+ )
133
161
  const bars = useMemo<ChartSeries<T>[]>(
134
- () => series.map((s) => ({ ...s, mark: 'bar' as const })),
135
- [series],
162
+ () =>
163
+ series.map((s) => ({
164
+ ...s,
165
+ mark: 'bar' as const,
166
+ // A pane draws at full colour, so its swatch must not claim an opacity the plot lacks.
167
+ ...(s.key !== absentKey && { fillOpacity: undefined }),
168
+ })),
169
+ [series, absentKey],
136
170
  )
171
+ const absentEntry = bars.find((s) => s.key === absentKey)
137
172
 
138
173
  const plan = useCallback(
139
174
  ({ hidden, highlighted, width }: PanelInput): PanelPlan<T> => {
@@ -148,6 +183,12 @@ export function MirroredBars<T, X extends ChartX = ChartX>(
148
183
  : data
149
184
  const model = xScaleFor<X>(drawn.map(x), true)
150
185
  const visible = visibleSeries(bars, hidden)
186
+ // A legend-hidden absent entry gives its share back to the measured bar, as `BandStrip`
187
+ // does; with no entry the share is always drawn, flat neutral.
188
+ const absentOn = !absentEntry || visible.includes(absentEntry)
189
+ const absentFill = absentEntry
190
+ ? alpha(absentEntry.color, absentEntry.fillOpacity ?? 1)
191
+ : VX.neutral
151
192
  const upOn = visible.includes(upSeries)
152
193
  const downOn = visible.includes(downSeries)
153
194
  const format = (v: ChartValue): string => (formatX ? formatX(v as X) : defaultFormatX(v))
@@ -176,7 +217,7 @@ export function MirroredBars<T, X extends ChartX = ChartX>(
176
217
  // A partly-absent bar is painted by rects on the plot-fraction scale, so its measured share
177
218
  // is narrower than its band; the bar itself stays as the (transparent) focus target.
178
219
  const left = (row: PlotRow<T, X>): number => (model.fraction(row.x) ?? 0) - bandWidth / 2
179
- const absent = (d: T): number => clamp01(getAbsentFraction?.(d))
220
+ const absent = (d: T): number => (absentOn ? clamp01(getAbsentFraction?.(d)) : 0)
180
221
  const measured = rows.filter(
181
222
  (r) => r.y !== null && absent(r.datum) > 0 && absent(r.datum) < 1,
182
223
  )
@@ -233,7 +274,7 @@ export function MirroredBars<T, X extends ChartX = ChartX>(
233
274
  y1: () => 0,
234
275
  y2: () => max,
235
276
  xScale: 'zx',
236
- fill: VX.neutral,
277
+ fill: absentFill,
237
278
  inset: 0,
238
279
  }),
239
280
  ),
@@ -282,7 +323,19 @@ export function MirroredBars<T, X extends ChartX = ChartX>(
282
323
  },
283
324
  }
284
325
  },
285
- [data, x, bars, up, down, upFraction, getAbsentFraction, getBarOpacity, foldConfig, formatX],
326
+ [
327
+ data,
328
+ x,
329
+ bars,
330
+ up,
331
+ down,
332
+ upFraction,
333
+ getAbsentFraction,
334
+ getBarOpacity,
335
+ foldConfig,
336
+ formatX,
337
+ absentEntry,
338
+ ],
286
339
  )
287
340
 
288
341
  return (