basalt-ui 2.10.0 → 2.11.1

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 (78) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/MIGRATING.md +36 -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 +21 -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/Lines.d.ts.map +1 -1
  16. package/dist/charts/Lines.js +7 -45
  17. package/dist/charts/MirroredBars.js +2 -2
  18. package/dist/charts/Sparkline.d.ts +12 -0
  19. package/dist/charts/Sparkline.d.ts.map +1 -1
  20. package/dist/charts/Sparkline.js +68 -5
  21. package/dist/charts/band-fold.d.ts +7 -0
  22. package/dist/charts/band-fold.d.ts.map +1 -1
  23. package/dist/charts/compile.d.ts +4 -1
  24. package/dist/charts/compile.d.ts.map +1 -1
  25. package/dist/charts/compile.js +43 -19
  26. package/dist/charts/heatmap-fill.d.ts +15 -0
  27. package/dist/charts/heatmap-fill.d.ts.map +1 -0
  28. package/dist/charts/heatmap-fill.js +13 -0
  29. package/dist/charts/host.d.ts +5 -1
  30. package/dist/charts/host.d.ts.map +1 -1
  31. package/dist/charts/host.js +37 -1
  32. package/dist/charts/index.d.ts +1 -1
  33. package/dist/charts/index.d.ts.map +1 -1
  34. package/dist/charts/labels.d.ts +34 -0
  35. package/dist/charts/labels.d.ts.map +1 -0
  36. package/dist/charts/labels.js +63 -0
  37. package/dist/charts/marks.d.ts +8 -1
  38. package/dist/charts/marks.d.ts.map +1 -1
  39. package/dist/charts/marks.js +50 -13
  40. package/dist/charts/panel.d.ts +7 -1
  41. package/dist/charts/panel.d.ts.map +1 -1
  42. package/dist/charts/panel.js +9 -4
  43. package/dist/charts/plot-context.d.ts +42 -0
  44. package/dist/charts/plot-context.d.ts.map +1 -0
  45. package/dist/charts/plot-context.js +64 -0
  46. package/dist/charts/scales.d.ts +6 -1
  47. package/dist/charts/scales.d.ts.map +1 -1
  48. package/dist/charts/scales.js +28 -8
  49. package/dist/charts/ticks.d.ts +12 -0
  50. package/dist/charts/ticks.d.ts.map +1 -0
  51. package/dist/charts/ticks.js +42 -0
  52. package/dist/charts/types.d.ts +39 -5
  53. package/dist/charts/types.d.ts.map +1 -1
  54. package/dist/tokens/core.d.ts +6 -0
  55. package/dist/tokens/core.d.ts.map +1 -1
  56. package/dist/tokens/core.js +5 -3
  57. package/llms.txt +12 -4
  58. package/package.json +1 -1
  59. package/src/charts/BandStrip.tsx +2 -5
  60. package/src/charts/CartesianChart.tsx +13 -2
  61. package/src/charts/DualPanel.tsx +22 -16
  62. package/src/charts/Heatmap.tsx +181 -76
  63. package/src/charts/Lines.tsx +11 -57
  64. package/src/charts/MirroredBars.tsx +2 -2
  65. package/src/charts/Sparkline.tsx +106 -5
  66. package/src/charts/band-fold.ts +11 -0
  67. package/src/charts/compile.ts +60 -20
  68. package/src/charts/heatmap-fill.ts +19 -0
  69. package/src/charts/host.tsx +59 -0
  70. package/src/charts/index.ts +1 -1
  71. package/src/charts/labels.ts +118 -0
  72. package/src/charts/marks.ts +72 -14
  73. package/src/charts/panel.tsx +18 -5
  74. package/src/charts/plot-context.ts +109 -0
  75. package/src/charts/scales.ts +41 -11
  76. package/src/charts/ticks.ts +61 -0
  77. package/src/charts/types.ts +39 -5
  78. 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
  }
@@ -5,35 +5,31 @@
5
5
  * reference lines, `y2`, legend, cursor and tooltip are the rung's.
6
6
  *
7
7
  * At the wide class with ≤ 3 plotted lines and no `y2`, each line also carries an end label; the
8
- * legend still names every series (and still toggles them).
8
+ * legend still names every series (and still toggles them). A label that would not fit between its
9
+ * last point and the plot's right edge ends at the point instead, above it. Before the engine has
10
+ * measured the plot (the server HTML, the first client frame) the room is read off the frame, which
11
+ * is wider by the axis gutters; the measured render corrects it.
9
12
  */
10
13
  import { areaY } from '@tanstack/charts/area'
11
14
  import { differenceY } from '@tanstack/charts/difference'
12
15
  import { decorative } from '@tanstack/charts/mark/decorative'
13
- import { text } from '@tanstack/charts/text'
14
16
  import { useCallback } from 'react'
15
17
  import type { ReactElement } from 'react'
16
- import { VX } from '../tokens'
17
18
  import { CartesianRung } from './CartesianChart'
18
19
  import { areaGradientId } from './compile'
19
20
  import { chartCurve } from './curves'
20
- import { drawnRows, lineMark, markersOf, yScaleOf } from './marks'
21
+ import { endLabelMarks, endLabelPlan } from './labels'
22
+ import { drawnRows, lineMark, loneDots, markersOf, yScaleOf } from './marks'
21
23
  import { rowX } from './types'
22
24
  import type {
23
25
  CartesianChartProps,
24
26
  ChartMarks,
25
- ChartSeries,
26
27
  ChartX,
27
28
  PlotContext,
28
29
  PlotRow,
29
30
  Threshold,
30
31
  } from './types'
31
32
 
32
- const MAX_END_LABELS = 3
33
- /** Below this vertical gap two end labels would collide; then none is drawn. */
34
- const END_LABEL_MIN_GAP = 13
35
- const END_LABEL_DX = 6
36
-
37
33
  export type LinesProps<T, X extends ChartX = ChartX> = Omit<CartesianChartProps<T, X>, 'marks'> & {
38
34
  /**
39
35
  * Fills between the first visible series and a value, on one side of it. Unavailable on a string
@@ -44,46 +40,6 @@ export type LinesProps<T, X extends ChartX = ChartX> = Omit<CartesianChartProps<
44
40
 
45
41
  const hasValue = <T, X extends ChartX>(r: PlotRow<T, X>): boolean => r.y !== null
46
42
 
47
- function endLabels<T, X extends ChartX>(
48
- plot: PlotContext<T, X>,
49
- lines: readonly ChartSeries<T>[],
50
- ): ChartMarks {
51
- if (plot.containerClass !== 'wide' || plot.y2 !== undefined) return []
52
- if (lines.length === 0 || lines.length > MAX_END_LABELS) return []
53
- const last = lines.flatMap((s) => {
54
- const row = plot.rows(s.key).findLast(hasValue)
55
- return row ? [{ s, row }] : []
56
- })
57
- // Collision check in pixels from the plot height: labels that would overlap are not drawn at all.
58
- // No `y2` here (returned above), so every label reads the left domain.
59
- const domain = plot.yDomain
60
- const ys = last.map(({ row }) => {
61
- if (row.y === null) return Number.NaN
62
- return ((row.y - domain[0]) / (domain[1] - domain[0] || 1)) * plot.height
63
- })
64
- const sorted = ys.toSorted((a, b) => a - b)
65
- if (
66
- sorted.some(
67
- (y, i) => Number.isNaN(y) || (i > 0 && y - (sorted[i - 1] as number) < END_LABEL_MIN_GAP),
68
- )
69
- )
70
- return []
71
- return last.map(({ s, row }) =>
72
- decorative(
73
- text([row], {
74
- id: `${s.key}-end-label`,
75
- x: rowX,
76
- y: 'y',
77
- text: () => s.label,
78
- fill: s.color,
79
- fontSize: VX.text.micro,
80
- anchor: 'start',
81
- dx: END_LABEL_DX,
82
- }),
83
- ),
84
- )
85
- }
86
-
87
43
  export function Lines<T, X extends ChartX = ChartX>(props: LinesProps<T, X>): ReactElement {
88
44
  const { thresholds, ...rest } = props
89
45
  const { series } = props
@@ -134,15 +90,13 @@ export function Lines<T, X extends ChartX = ChartX>(props: LinesProps<T, X>): Re
134
90
  )
135
91
  }
136
92
  for (const s of plot.visible) {
93
+ const yScale = yScaleOf(plot, s)
137
94
  out.push(lineMark(plot, s))
138
- out.push(...markersOf(s, plot.rows(s.key), yScaleOf(plot, s)))
95
+ out.push(...loneDots(s, drawnRows(plot, s), yScale, plot.highlighted))
96
+ out.push(...markersOf(s, plot.rows(s.key), yScale))
139
97
  }
140
- out.push(
141
- ...endLabels(
142
- plot,
143
- plotted.filter((s) => s.role !== 'reference'),
144
- ),
145
- )
98
+ const labelled = plotted.filter((s) => s.role !== 'reference')
99
+ out.push(...endLabelMarks(endLabelPlan(plot, labelled)))
146
100
  return out
147
101
  },
148
102
  [series, thresholds],
@@ -181,7 +181,7 @@ export function MirroredBars<T, X extends ChartX = ChartX, K extends string = st
181
181
  foldConfig.merge,
182
182
  )
183
183
  : data
184
- const model = xScaleFor<X>(drawn.map(x), true)
184
+ const model = xScaleFor<X>(drawn.map(x), 'flush')
185
185
  const visible = visibleSeries(bars, hidden)
186
186
  // A legend-hidden absent entry gives its share back to the measured bar, as `BandStrip`
187
187
  // does; with no entry the share is always drawn, flat neutral.
@@ -196,7 +196,7 @@ export function MirroredBars<T, X extends ChartX = ChartX, K extends string = st
196
196
  const downMax = paneMax(down, downSeries, drawn, downOn)
197
197
  const bandWidth = 2 * model.halfStep * BAND_FILL
198
198
  // One instance per pane: the engine sets a scale's range, and the panes' plots differ in width.
199
- const bandScale = () => xScaleFor<X>(drawn.map(x), true).scale
199
+ const bandScale = () => xScaleFor<X>(drawn.map(x), 'flush').scale
200
200
 
201
201
  const pane =
202
202
  (
@@ -48,6 +48,11 @@ type Point = { i: number; v: number | null }
48
48
  const LINE_WIDTH = 1.6
49
49
  const DOT_R = 2.5
50
50
  const BAR_GAP = 0.15
51
+ // Pixel policy of the self-pooling (`poolSparkline`): the densest a series may draw.
52
+ const LINE_PX_PER_POINT = 1
53
+ const BAR_PX_PER_BAR = 2
54
+ /** First, last and one min/max pair: the fewest points a pooled line can hold. */
55
+ const LINE_POOL_MIN = 4
51
56
 
52
57
  const finite = (v: number): number | null => (Number.isFinite(v) ? v : null)
53
58
 
@@ -63,16 +68,112 @@ function extent(rows: readonly Point[]): readonly [number, number] | null {
63
68
  return lo <= hi ? [lo, hi] : null
64
69
  }
65
70
 
66
- function compileSparkline(
71
+ /** A row with its value proven finite, so no cast carries it through the pooling. */
72
+ type Sample = { row: Point; v: number }
73
+ const sampleOf = (row: Point): Sample | null => (row.v === null ? null : { row, v: row.v })
74
+
75
+ /** `rows` cut into `count` consecutive buckets of near-equal length (empty ones dropped). */
76
+ function buckets(rows: readonly Point[], count: number): Point[][] {
77
+ const size = rows.length / count
78
+ return Array.from({ length: count }, (_, b) =>
79
+ rows.slice(Math.round(b * size), Math.round((b + 1) * size)),
80
+ ).filter((bucket) => bucket.length > 0)
81
+ }
82
+
83
+ /** One maximal stretch of finite rows inside a bucket. */
84
+ type Run = { first: Sample; lo: Sample; hi: Sample; last: Sample; afterGap: boolean }
85
+
86
+ /** A run's rows in index order: its min and max, plus the edge that touches a gap, so the gap
87
+ * stays exactly where the input had it. */
88
+ function runRows(run: Run, beforeGap: boolean): Point[] {
89
+ const keep = [
90
+ run.lo,
91
+ run.hi,
92
+ ...(run.afterGap ? [run.first] : []),
93
+ ...(beforeGap ? [run.last] : []),
94
+ ]
95
+ const byIndex = new Map(keep.map((k) => [k.row.i, k.row]))
96
+ return [...byIndex.values()].toSorted((a, b) => a.i - b.i)
97
+ }
98
+
99
+ /**
100
+ * A line, pooled: the first and last rows, and each bucket's min and max between them. A null
101
+ * row is a gap and is never pooled across: a run is closed at every null, one null row (at the
102
+ * gap's first index) stands for the whole gap, and the finite rows beside it are kept.
103
+ */
104
+ function poolLine(rows: readonly Point[], cap: number): readonly Point[] {
105
+ const first = rows[0]
106
+ const last = rows.at(-1)
107
+ if (first === undefined || last === undefined) return rows
108
+ if (cap < LINE_POOL_MIN) return [first, last]
109
+ const out: Point[] = [first]
110
+ const endsInGap = (): boolean => out.at(-1)?.v === null
111
+ for (const bucket of buckets(rows.slice(1, -1), Math.floor(cap / 2) - 1)) {
112
+ let run: Run | undefined
113
+ for (const row of bucket) {
114
+ const s = sampleOf(row)
115
+ if (s === null) {
116
+ if (run !== undefined) out.push(...runRows(run, true))
117
+ run = undefined
118
+ if (!endsInGap()) out.push(row)
119
+ continue
120
+ }
121
+ run =
122
+ run === undefined
123
+ ? { first: s, lo: s, hi: s, last: s, afterGap: endsInGap() }
124
+ : { ...run, lo: s.v < run.lo.v ? s : run.lo, hi: s.v > run.hi.v ? s : run.hi, last: s }
125
+ }
126
+ if (run !== undefined) out.push(...runRows(run, false))
127
+ }
128
+ return last.v === null && endsInGap() ? out : [...out, last]
129
+ }
130
+
131
+ /** Bars, pooled: the first and last rows and one bar per bucket between them, the value furthest
132
+ * from zero; a bucket of nulls is one null bar. Re-indexed 0..n-1 (a band x). */
133
+ function poolBar(rows: readonly Point[], cap: number): readonly Point[] {
134
+ const first = rows[0]
135
+ const last = rows.at(-1)
136
+ if (first === undefined || last === undefined) return rows
137
+ const furthest = (group: readonly Point[]): number | null =>
138
+ group.reduce<number | null>((best, r) => {
139
+ if (r.v === null) return best
140
+ return best === null || Math.abs(r.v) > Math.abs(best) ? r.v : best
141
+ }, null)
142
+ if (cap < 2) return [{ i: 0, v: furthest(rows) }]
143
+ const values =
144
+ cap === 2
145
+ ? [first.v, last.v]
146
+ : [first.v, ...buckets(rows.slice(1, -1), cap - 2).map(furthest), last.v]
147
+ return values.map((v, i) => ({ i, v }))
148
+ }
149
+
150
+ /**
151
+ * Pools a series to what `width` px can show, so the caller never sizes it: at most one point
152
+ * per `LINE_PX_PER_POINT` (min/max-preserving) or one bar per `BAR_PX_PER_BAR`. A series at or
153
+ * under its cap is returned as is, so a short series draws exactly as before; `width <= 0`
154
+ * (unmeasured) pools nothing. A line is never pooled below its two endpoints.
155
+ */
156
+ export function poolSparkline(
67
157
  rows: readonly Point[],
158
+ width: number,
159
+ mark: 'line' | 'bar',
160
+ ): readonly Point[] {
161
+ const cap = Math.floor(width / (mark === 'bar' ? BAR_PX_PER_BAR : LINE_PX_PER_POINT))
162
+ if (width <= 0 || rows.length <= Math.max(cap, mark === 'bar' ? 1 : 2)) return rows
163
+ return mark === 'bar' ? poolBar(rows, cap) : poolLine(rows, cap)
164
+ }
165
+
166
+ function compileSparkline(
167
+ source: readonly Point[],
68
168
  [lo, hi]: readonly [number, number],
69
169
  mark: 'line' | 'bar',
70
170
  color: string,
71
171
  emphasisColor: string | null,
72
172
  ): CartesianDefinition {
73
- const last = rows.at(-1)
74
173
  return {
75
- chart: () => {
174
+ chart: ({ width }) => {
175
+ const rows = poolSparkline(source, width, mark)
176
+ const last = rows.at(-1)
76
177
  if (mark === 'bar') {
77
178
  return {
78
179
  marks: [
@@ -104,7 +205,7 @@ function compileSparkline(
104
205
  // A flat or single-point series needs an extent; 10% air keeps the stroke inside the box.
105
206
  const pad = (hi - lo) * 0.1 || 1
106
207
  // Half a dot of air at each end, in index units, so the last-point dot is not clipped.
107
- const xPad = emphasisColor === null ? 0 : (rows.length - 1) * 0.04 || 0.5
208
+ const xPad = emphasisColor === null ? 0 : (source.length - 1) * 0.04 || 0.5
108
209
  return {
109
210
  marks: [
110
211
  lineY(rows, {
@@ -125,7 +226,7 @@ function compileSparkline(
125
226
  ],
126
227
  scales: {
127
228
  x: {
128
- scale: scaleLinear().domain([-xPad, Math.max(rows.length - 1, 1) + xPad]),
229
+ scale: scaleLinear().domain([-xPad, Math.max(source.length - 1, 1) + xPad]),
129
230
  axis: false as const,
130
231
  },
131
232
  y: { scale: scaleLinear().domain([lo - pad, hi + pad]), axis: false as const },