basalt-ui 2.23.0 → 2.24.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 (107) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/MIGRATING.md +225 -12
  3. package/agent/agents/basalt-design-reviewer.md +2 -2
  4. package/agent/skills/basalt-design/SKILL.md +1 -1
  5. package/agent/skills/basalt-design/references/catalogue.md +22 -19
  6. package/agent/skills/basalt-design/references/states.md +39 -0
  7. package/dist/charts/Bars.d.ts.map +1 -1
  8. package/dist/charts/Bars.js +17 -2
  9. package/dist/charts/CartesianChart.d.ts.map +1 -1
  10. package/dist/charts/CartesianChart.js +7 -3
  11. package/dist/charts/Sparkline.d.ts.map +1 -1
  12. package/dist/charts/Sparkline.js +32 -6
  13. package/dist/charts/StackedArea.d.ts.map +1 -1
  14. package/dist/charts/StackedArea.js +5 -1
  15. package/dist/charts/chart-legend.module.css +16 -0
  16. package/dist/charts/compile.d.ts +2 -0
  17. package/dist/charts/compile.d.ts.map +1 -1
  18. package/dist/charts/compile.js +47 -3
  19. package/dist/charts/legend.d.ts +0 -6
  20. package/dist/charts/legend.d.ts.map +1 -1
  21. package/dist/charts/legend.js +87 -35
  22. package/dist/charts/sparkline.module.css +59 -6
  23. package/dist/charts/sparkline.module.css.d.ts +1 -0
  24. package/dist/charts/state.js +1 -1
  25. package/dist/charts/types.d.ts +11 -0
  26. package/dist/charts/types.d.ts.map +1 -1
  27. package/dist/cli/shot/measure.js +19 -23
  28. package/dist/dashboard/bar-list.module.css +3 -15
  29. package/dist/dashboard/empty-state.d.ts.map +1 -1
  30. package/dist/dashboard/meter-model.d.ts +30 -1
  31. package/dist/dashboard/meter-model.d.ts.map +1 -1
  32. package/dist/dashboard/meter-model.js +74 -5
  33. package/dist/dashboard/meter-parts.d.ts +8 -1
  34. package/dist/dashboard/meter-parts.d.ts.map +1 -1
  35. package/dist/dashboard/meter-parts.js +64 -21
  36. package/dist/dashboard/meter.d.ts +8 -1
  37. package/dist/dashboard/meter.d.ts.map +1 -1
  38. package/dist/dashboard/meter.js +14 -3
  39. package/dist/dashboard/meter.module.css +42 -2
  40. package/dist/dashboard/meter.module.css.d.ts +4 -0
  41. package/dist/dashboard/query-state.d.ts +7 -3
  42. package/dist/dashboard/query-state.d.ts.map +1 -1
  43. package/dist/dashboard/query-state.js +14 -6
  44. package/dist/dashboard/section.d.ts +2 -1
  45. package/dist/dashboard/section.d.ts.map +1 -1
  46. package/dist/dashboard/section.module.css +12 -0
  47. package/dist/dashboard/settings-section.d.ts +1 -1
  48. package/dist/dashboard/settings-section.d.ts.map +1 -1
  49. package/dist/dashboard/settings-section.js +3 -3
  50. package/dist/dashboard/stat-card.module.css +24 -10
  51. package/dist/dashboard/stat-group.module.css +8 -0
  52. package/dist/dashboard/stat-strip.d.ts +3 -2
  53. package/dist/dashboard/stat-strip.d.ts.map +1 -1
  54. package/dist/dashboard/stat-strip.js +83 -73
  55. package/dist/dashboard/stat-strip.module.css +22 -38
  56. package/dist/dashboard/stat-strip.module.css.d.ts +1 -0
  57. package/dist/dashboard/widget-header.d.ts.map +1 -1
  58. package/dist/dashboard/widget-header.js +19 -1
  59. package/dist/dashboard/widget-header.module.css +6 -0
  60. package/dist/guard/index.d.ts +2 -2
  61. package/dist/guard/index.d.ts.map +1 -1
  62. package/dist/guard/index.js +1 -12
  63. package/dist/table/data-table.js +1 -1
  64. package/dist/theme/controls.module.css +7 -2
  65. package/dist/theme/index.d.ts.map +1 -1
  66. package/dist/theme/index.js +7 -5
  67. package/dist/tokens/palette.d.ts +2 -2
  68. package/dist/tokens/palette.d.ts.map +1 -1
  69. package/dist/tokens/palette.js +2 -2
  70. package/llms.txt +3 -2
  71. package/package.json +1 -1
  72. package/src/charts/Bars.tsx +29 -2
  73. package/src/charts/CartesianChart.tsx +7 -3
  74. package/src/charts/Sparkline.tsx +66 -21
  75. package/src/charts/StackedArea.tsx +12 -1
  76. package/src/charts/chart-legend.module.css +16 -0
  77. package/src/charts/compile.ts +84 -2
  78. package/src/charts/legend.tsx +70 -3
  79. package/src/charts/sparkline.module.css +59 -6
  80. package/src/charts/sparkline.module.css.d.ts +1 -0
  81. package/src/charts/state.tsx +1 -1
  82. package/src/charts/types.ts +9 -0
  83. package/src/cli/shot/measure.ts +27 -27
  84. package/src/dashboard/bar-list.module.css +3 -15
  85. package/src/dashboard/empty-state.tsx +4 -2
  86. package/src/dashboard/meter-model.ts +124 -7
  87. package/src/dashboard/meter-parts.tsx +127 -31
  88. package/src/dashboard/meter.module.css +42 -2
  89. package/src/dashboard/meter.module.css.d.ts +4 -0
  90. package/src/dashboard/meter.tsx +22 -3
  91. package/src/dashboard/query-state.tsx +19 -8
  92. package/src/dashboard/section.module.css +12 -0
  93. package/src/dashboard/section.tsx +2 -1
  94. package/src/dashboard/settings-section.tsx +4 -4
  95. package/src/dashboard/stat-card.module.css +24 -10
  96. package/src/dashboard/stat-group.module.css +8 -0
  97. package/src/dashboard/stat-strip.module.css +22 -38
  98. package/src/dashboard/stat-strip.module.css.d.ts +1 -0
  99. package/src/dashboard/stat-strip.tsx +63 -43
  100. package/src/dashboard/widget-header.module.css +6 -0
  101. package/src/dashboard/widget-header.tsx +28 -1
  102. package/src/guard/index.ts +3 -14
  103. package/src/table/data-table.tsx +1 -1
  104. package/src/theme/__snapshots__/plain-theme.test.ts.snap +6 -6
  105. package/src/theme/controls.module.css +7 -2
  106. package/src/theme/index.ts +7 -5
  107. package/src/tokens/palette.ts +2 -2
@@ -12,7 +12,7 @@ import { ruleY } from '@tanstack/charts/rule'
12
12
  import { scaleBand } from '@tanstack/charts/scales/band'
13
13
  import { scaleLinear } from '@tanstack/charts/scales/linear'
14
14
  import { text } from '@tanstack/charts/text'
15
- import { useId, useMemo, useState } from 'react'
15
+ import { useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
16
16
  import type { CSSProperties, FocusEvent, KeyboardEvent, PointerEvent, ReactElement } from 'react'
17
17
  import { cx } from '../common/props'
18
18
  import type { BasaltProps } from '../common/props'
@@ -20,6 +20,7 @@ import { VX, alpha } from '../tokens'
20
20
  import type { CartesianDefinition } from './compile'
21
21
  import { chartCurve } from './curves'
22
22
  import { barMark } from './marks'
23
+ import { VisualSlotContext } from '../dashboard/visual-slot'
23
24
  import { bucketDay, dayGranular, defaultNumberFormat } from './compile'
24
25
  import { referenceLabelPlacement } from './ref-label'
25
26
  import { readoutClock, readoutDay } from './chart-dates'
@@ -74,7 +75,7 @@ type Point = { i: number; v: number | null }
74
75
  const LINE_WIDTH = 1.5
75
76
  const DOT_R = 2.5
76
77
  const BAR_GAP = 0.15
77
- /** Air between the hovered point and the readout chip beside it, px. */
78
+ /** Air between the hovered point and a bare sparkline's readout chip beside it, px. */
78
79
  const READOUT_GAP = 8
79
80
  /** Air round a line's plot, px (the engine's plot margin): the end marker stays inside the svg box,
80
81
  * so it clears the 2px focus outline round it. A bar plot is flush. */
@@ -94,7 +95,7 @@ const DAY_MS = 86_400_000
94
95
  const finite = (v: number): number | null => (Number.isFinite(v) ? v : null)
95
96
 
96
97
  /** The readout's moment per point of `{ at }` data: the day when the points are a day or more apart,
97
- * else the hour (with the day once they span several). `undefined` for plain values. */
98
+ * else the hour (with the day once they cross midnight). `undefined` for plain values. */
98
99
  function momentsOf(data: SparklineProps['data']): readonly (string | undefined)[] | undefined {
99
100
  const dates: (Date | null)[] = []
100
101
  for (const d of data) {
@@ -111,12 +112,14 @@ function momentsOf(data: SparklineProps['data']): readonly (string | undefined)[
111
112
  if (day < lo) lo = day
112
113
  if (day > hi) hi = day
113
114
  }
114
- const oneDay = lo === hi
115
+ // Hourly points inside one UTC day name the hour alone; a window that crosses midnight (24 points
116
+ // from 12:00 on, or 25 from 12:00 to 12:00) names the day with each hour, so no clock repeats bare.
117
+ const clockOnly = lo === hi
115
118
  const byDay = dayGranular(known)
116
119
  return dates.map((d) => {
117
120
  if (d === null) return undefined
118
121
  if (byDay) return readoutDay(bucketDay(d))
119
- return oneDay ? readoutClock(d) : `${readoutDay(d)} ${readoutClock(d)}`
122
+ return clockOnly ? readoutClock(d) : `${readoutDay(d)} ${readoutClock(d)}`
120
123
  })
121
124
  }
122
125
 
@@ -386,6 +389,20 @@ function meanOf(rows: readonly Point[]): number {
386
389
  return sum / n
387
390
  }
388
391
 
392
+ /**
393
+ * A readout never loses its date to an ellipsis: when the one-line chip overflows its box it first
394
+ * tightens (`data-tight`: no air round the dot), then stacks (`data-stacked`: the date on its own
395
+ * line). Set on the node, so a measure never re-renders.
396
+ */
397
+ function fitReadout(node: HTMLElement): void {
398
+ const overflows = (): boolean => node.scrollWidth > node.clientWidth
399
+ node.removeAttribute('data-tight')
400
+ node.removeAttribute('data-stacked')
401
+ if (!overflows()) return
402
+ node.setAttribute('data-tight', '')
403
+ if (overflows()) node.setAttribute('data-stacked', '')
404
+ }
405
+
389
406
  export function Sparkline(props: SparklineProps): ReactElement {
390
407
  const {
391
408
  ariaLabel,
@@ -406,10 +423,12 @@ export function Sparkline(props: SparklineProps): ReactElement {
406
423
  style,
407
424
  } = props
408
425
  const id = useId()
426
+ const hosted = useContext(VisualSlotContext) !== null
409
427
  // Two sources, so a pointer leaving a focused chart hands the readout back to the focused point.
410
428
  const [hover, setHover] = useState<number | null>(null)
411
429
  const [keyed, setKeyed] = useState<number | null>(null)
412
430
  const active = hover ?? keyed
431
+ const readoutRef = useRef<HTMLOutputElement>(null)
413
432
  const model = useMemo(() => {
414
433
  const rows: Point[] = data.map((d, i) => ({
415
434
  i,
@@ -474,7 +493,7 @@ export function Sparkline(props: SparklineProps): ReactElement {
474
493
  }
475
494
 
476
495
  const inset = mark === 'line' ? LINE_INSET : 0
477
- const layerStyle: CSSProperties = { inset }
496
+ const layerStyle: CSSProperties = { inset, ['--basalt-spark-inset' as string]: `${inset}px` }
478
497
  const value = active === null ? null : (rows?.[active]?.v ?? null)
479
498
  const at =
480
499
  interactive && active !== null && value !== null
@@ -488,27 +507,47 @@ export function Sparkline(props: SparklineProps): ReactElement {
488
507
  label: labels?.[active] ?? model.moments?.[active],
489
508
  }
490
509
  : null
491
- // Beside the point, on the roomier side, and on the half of the box away from it: the chip never
492
- // covers the dot or the host's text, and stays inside the box whatever clips above it.
510
+ // Hosted (a host that reserves a line above the plot): the chip slides with the point (`left` and
511
+ // `translate` take one fraction), inside the box at either edge whatever its width, and the
512
+ // stylesheet lifts it above the plot. Bare: beside the point, on the roomier side and on the half of
513
+ // the box away from it, so the chip covers neither the dot nor anything the host draws round it.
493
514
  const beside = at === null ? null : at.fx > 0.5 ? 'left' : 'right'
515
+ // The chip's fit depends on its text and (bare) its side, not on the pointer's every tick.
516
+ const shown = at !== null
517
+ useLayoutEffect(() => {
518
+ if (readoutRef.current !== null) fitReadout(readoutRef.current)
519
+ }, [active, at?.label, at?.value, beside])
520
+ // ...and on the box, which a container resize changes without a hover.
521
+ useEffect(() => {
522
+ const layer = readoutRef.current?.parentElement
523
+ if (!shown || !layer || typeof ResizeObserver === 'undefined') return
524
+ const observer = new ResizeObserver(() => {
525
+ if (readoutRef.current !== null) fitReadout(readoutRef.current)
526
+ })
527
+ observer.observe(layer)
528
+ return () => observer.disconnect()
529
+ }, [shown])
494
530
  const readoutStyle: CSSProperties | undefined =
495
531
  at === null
496
532
  ? undefined
497
- : {
498
- ...(beside === 'right'
499
- ? {
500
- left: `calc(${at.fx * 100}% + ${READOUT_GAP}px)`,
501
- maxWidth: `calc(${(1 - at.fx) * 100}% - ${READOUT_GAP}px)`,
502
- }
503
- : {
504
- right: `calc(${(1 - at.fx) * 100}% + ${READOUT_GAP}px)`,
505
- maxWidth: `calc(${at.fx * 100}% - ${READOUT_GAP}px)`,
506
- }),
507
- ...(at.fy > 0.5 ? { top: 0 } : { bottom: 0 }),
508
- }
533
+ : hosted
534
+ ? { left: `${at.fx * 100}%`, translate: `${-at.fx * 100}% 0`, maxWidth: '100%' }
535
+ : {
536
+ ...(beside === 'right'
537
+ ? {
538
+ left: `calc(${at.fx * 100}% + ${READOUT_GAP}px)`,
539
+ maxWidth: `calc(${(1 - at.fx) * 100}% - ${READOUT_GAP}px)`,
540
+ }
541
+ : {
542
+ right: `calc(${(1 - at.fx) * 100}% + ${READOUT_GAP}px)`,
543
+ maxWidth: `calc(${at.fx * 100}% - ${READOUT_GAP}px)`,
544
+ }),
545
+ ...(at.fy > 0.5 ? { top: 0 } : { bottom: 0 }),
546
+ }
509
547
  return (
510
548
  <div
511
549
  data-basalt-sparkline=""
550
+ {...(hosted && { 'data-basalt-hosted': '' })}
512
551
  role="presentation"
513
552
  className={cx(classes.root, className)}
514
553
  style={{ width: width ?? '100%', height, minWidth: 0, ...style }}
@@ -544,13 +583,19 @@ export function Sparkline(props: SparklineProps): ReactElement {
544
583
  />
545
584
  )}
546
585
  <output
586
+ ref={readoutRef}
547
587
  data-basalt-sparkline-readout=""
548
588
  aria-live={hover === null ? 'polite' : 'off'}
549
589
  className={classes.readout}
550
590
  style={readoutStyle}
551
591
  >
552
592
  {format(at.value)}
553
- {at.label !== undefined && <span className={classes.label}> · {at.label}</span>}
593
+ {at.label !== undefined && (
594
+ <span className={classes.label}>
595
+ <span className={classes.sep}> · </span>
596
+ {at.label}
597
+ </span>
598
+ )}
554
599
  </output>
555
600
  </span>
556
601
  )}
@@ -4,6 +4,9 @@
4
4
  * set is the caller mapping its groups to entries. The y domain is the visible stack total, so a
5
5
  * legend toggle shrinks the axis; the tooltip lists the top band first, matching the plot.
6
6
  *
7
+ * A band whose every value is `0` is skipped (no band, no legend entry, no tooltip row); `null` is a
8
+ * gap, not a zero, and stays.
9
+ *
7
10
  * A stack is only as dense as its sparsest band: a row where ANY visible band is `null` has no
8
11
  * total, so every band gaps across it. Reading it as `0` would claim a measured zero.
9
12
  */
@@ -44,7 +47,15 @@ export type StackedAreaProps<T, X extends ChartX = ChartX> = Omit<
44
47
  export function StackedArea<T, X extends ChartX = ChartX>(
45
48
  props: StackedAreaProps<T, X>,
46
49
  ): ReactElement {
47
- const { series: bands, fillOpacity, ...rest } = props
50
+ const { series: given, fillOpacity, ...rest } = props
51
+ // A band whose every value is 0 draws nothing but a legend entry that names an empty layer: skip it.
52
+ const bands = useMemo(
53
+ () =>
54
+ rest.data.length === 0
55
+ ? given
56
+ : given.filter((b) => !rest.data.every((d) => b.getValue(d) === 0)),
57
+ [given, rest.data],
58
+ )
48
59
  // `mark: 'bar'` is what the rung sums for the auto domain, and the legend/tooltip swatch.
49
60
  const series = useMemo<ChartSeries<T>[]>(
50
61
  () =>
@@ -15,7 +15,10 @@
15
15
  }
16
16
 
17
17
  @container (min-width: 240px) {
18
+ /* One row: `foldLegend` (legend.tsx) folds what does not fit into `+N`; zones lead the series. */
18
19
  .auto {
20
+ flex-wrap: nowrap;
21
+ overflow: hidden;
19
22
  display: flex;
20
23
  column-gap: var(--bc-dots-gap);
21
24
  --vx-hit-gap: var(--bc-dots-gap);
@@ -24,6 +27,8 @@
24
27
 
25
28
  @container (min-width: 480px) {
26
29
  .auto {
30
+ flex-wrap: wrap;
31
+ overflow: visible;
27
32
  column-gap: var(--bc-legend-gap);
28
33
  --vx-hit-gap: var(--bc-legend-gap);
29
34
  }
@@ -43,3 +48,14 @@
43
48
  display: none;
44
49
  }
45
50
  }
51
+
52
+ /* The compact fold (`foldLegend`, which only folds while the row is `nowrap`); wide keeps every entry.
53
+ * `!important`: an entry's inline `all: unset` (legend.tsx) would otherwise reset `display`. */
54
+ .auto [data-legend-folded] {
55
+ display: none !important;
56
+ }
57
+
58
+ .auto [data-legend-more] {
59
+ order: 1;
60
+ flex: none;
61
+ }
@@ -211,6 +211,7 @@ export function seriesRow(
211
211
 
212
212
  /** Keys the compiler reserves for the legend entries it derives from `refLines`. */
213
213
  const REF_KEY_PREFIX = '__ref-'
214
+ const ZONE_KEY_PREFIX = '__zone-'
214
215
 
215
216
  /** The legend key of a reference line that names itself (`RefLine.legend`). */
216
217
  const refLegendKey = (index: number): string => `${REF_KEY_PREFIX}${index}`
@@ -251,6 +252,25 @@ export function refLegendSeries<T>(refLines: readonly RefLine[] | undefined): Ch
251
252
  )
252
253
  }
253
254
 
255
+ /** Legend-only entries for the zones that name themselves (`ZoneSpec.legend`), in zone order. */
256
+ export function zoneLegendSeries<T>(zones: readonly ZoneSpec[] | undefined): ChartSeries<T>[] {
257
+ return (zones ?? []).flatMap((z, i) =>
258
+ z.legend === undefined
259
+ ? []
260
+ : [
261
+ {
262
+ key: `${ZONE_KEY_PREFIX}${i}`,
263
+ label: z.legend.label,
264
+ color: z.legend.color ?? SWATCH_SOLID.get(z.fill) ?? z.fill,
265
+ mark: z.legend.mark ?? 'bar',
266
+ role: 'reference' as const,
267
+ tooltip: false,
268
+ getValue: () => null,
269
+ },
270
+ ],
271
+ )
272
+ }
273
+
254
274
  /** The visible series: not toggled off, and not a companion whose parent is. */
255
275
  export function visibleSeries<T>(
256
276
  series: readonly ChartSeries<T>[],
@@ -297,6 +317,29 @@ function wholeStepFormat<T>(
297
317
  return (v) => axis.format(v).replace(padded, '$1')
298
318
  }
299
319
 
320
+ /** A fixed domain's end this near the last round tick (as a share of the tick step) stays unlabelled. */
321
+ const END_TICK_MIN_GAP = 0.4
322
+
323
+ /**
324
+ * The compact ladder's three ticks can stop short of a fixed domain's end (`[0, 25]` ticks `0 10 20`),
325
+ * and a unit the formatter states on the top tick (`25 days`) goes with it. A fixed domain whose end
326
+ * leaves at least {@link END_TICK_MIN_GAP} of a step above the last tick gets the end as a tick too.
327
+ */
328
+ function withEndTick<T>(
329
+ cfg: AxisConfig<T> | undefined,
330
+ axis: YAxis,
331
+ count: number,
332
+ ): { values: readonly number[] } | null {
333
+ if (!Array.isArray(cfg?.domain) || cfg.scale === 'log' || cfg.nice === true) return null
334
+ const [lo, hi] = [Math.min(...axis.domain), Math.max(...axis.domain)]
335
+ const round = scaleLinear().domain([lo, hi]).ticks(count)
336
+ const last = round.at(-1)
337
+ const next = round.at(1)
338
+ const first = round.at(0)
339
+ if (last === undefined || next === undefined || first === undefined || last >= hi) return null
340
+ return hi - last >= (next - first) * END_TICK_MIN_GAP ? { values: [...round, hi] } : null
341
+ }
342
+
300
343
  export function yGuide<T>(opts: {
301
344
  cfg: AxisConfig<T> | undefined
302
345
  axis: YAxis
@@ -309,7 +352,9 @@ export function yGuide<T>(opts: {
309
352
  const ticks =
310
353
  typeof cfg?.ticks === 'object'
311
354
  ? { values: cfg.ticks }
312
- : { count: typeof cfg?.ticks === 'number' ? cfg.ticks : ladder.yTicks }
355
+ : ((cls === 'compact' && cfg?.ticks === undefined
356
+ ? withEndTick(cfg, axis, ladder.yTicks)
357
+ : null) ?? { count: typeof cfg?.ticks === 'number' ? cfg.ticks : ladder.yTicks })
313
358
  const gridLine = grid ? { grid: GRID_LINE } : {}
314
359
  if (cls === 'micro') return { ...gridLine, axis: false }
315
360
  const tickFormat = wholeStepFormat(axis, cfg, ticks)
@@ -960,6 +1005,39 @@ const stripAnchor = (
960
1005
  const STRIP_TOOLTIP_PLACEMENT = ['bottom', 'top'] as const
961
1006
  const STRIP_TOOLTIP_OFFSET = 8
962
1007
 
1008
+ /** A tooltip's chrome (title row, padding) and each series row, px: the guess the bar anchor reserves. */
1009
+ const TIP_CHROME = 30
1010
+ const TIP_ROW = 18
1011
+ /** Air between a clamped tooltip's top and the plot's top edge, px. */
1012
+ const TIP_TOP_AIR = 4
1013
+
1014
+ /** A tall bar's tooltip steps aside by this much (a tooltip's half width plus a bar's), px. */
1015
+ const TIP_SIDE_STEP = 96
1016
+
1017
+ /**
1018
+ * A bar's tooltip opens above the bar, and above a tall bar that is above the plot, over the card's
1019
+ * headline. For a bar too tall to fit it, the anchor drops to where the open-above tooltip's top meets
1020
+ * the plot's top edge (`rows` series rows tall) and steps to the side with more room, so the tooltip
1021
+ * sits beside the bar, in the plot, and not on the bar's top. A short bar is unaffected.
1022
+ */
1023
+ const barAnchor =
1024
+ (rows: number) =>
1025
+ (
1026
+ points: readonly ChartPoint[],
1027
+ { plot }: ChartTooltipAnchorContext,
1028
+ ): { x: number; y: number } => {
1029
+ const xs = points.map((p) => p.x)
1030
+ const ys = points.map((p) => p.y)
1031
+ const centre = (Math.min(...xs) + Math.max(...xs)) / 2
1032
+ const x = Math.min(Math.max(centre, plot.x), plot.x + plot.width)
1033
+ const y = (Math.min(...ys) + Math.max(...ys)) / 2
1034
+ const floor = plot.y + TIP_TOP_AIR + TIP_CHROME + rows * TIP_ROW
1035
+ if (y >= floor) return { x, y }
1036
+ const toRight = x - plot.x < plot.width / 2
1037
+ const stepped = x + (toRight ? TIP_SIDE_STEP : -TIP_SIDE_STEP)
1038
+ return { x: Math.min(Math.max(stepped, plot.x), plot.x + plot.width), y: floor }
1039
+ }
1040
+
963
1041
  function tooltipSpec<T, X extends ChartX>(opts: {
964
1042
  input: CartesianInput<T, X>
965
1043
  axes: Axes<T>
@@ -979,7 +1057,11 @@ function tooltipSpec<T, X extends ChartX>(opts: {
979
1057
  use: quietWhileFollowing,
980
1058
  ...followerOptions(input.tooltip, input.cursorGroup, input.chartId),
981
1059
  portal,
982
- anchor: input.tooltipBelow ? stripAnchor : 'group-center',
1060
+ anchor: input.tooltipBelow
1061
+ ? stripAnchor
1062
+ : visible.some((s) => s.mark === 'bar')
1063
+ ? barAnchor(rowSeries.length)
1064
+ : 'group-center',
983
1065
  ...(input.tooltipBelow && { placement: STRIP_TOOLTIP_PLACEMENT, offset: STRIP_TOOLTIP_OFFSET }),
984
1066
  content: (points: readonly ChartPoint[]) => {
985
1067
  const primary = points[0]
@@ -4,6 +4,7 @@
4
4
  * its parent's entry. Toggling an entry hides the series from the plot, the tooltip and the auto
5
5
  * domain together; hovering one emphasizes it (the definition is rebuilt with `highlighted`).
6
6
  */
7
+ import { useEffect, useLayoutEffect, useRef } from 'react'
7
8
  import type { CSSProperties, ReactElement } from 'react'
8
9
  import { VX } from '../tokens'
9
10
  import classes from './chart-legend.module.css'
@@ -28,13 +29,17 @@ const ROLE_ORDER = ['series', 'overlay', 'reference'] as const
28
29
  */
29
30
  const DOTS_GAP = 30
30
31
 
32
+ const byReferenceFirst = <T,>(a: ChartSeries<T>, b: ChartSeries<T>): number =>
33
+ Number(b.role === 'reference') - Number(a.role === 'reference')
34
+
31
35
  /** The entries a series list derives, in display order (by role when `groups`). */
32
36
  export function legendEntries<T>(
33
37
  series: readonly ChartSeries<T>[],
34
38
  groups: boolean,
35
39
  ): ChartSeries<T>[][] {
36
40
  const entries = series.filter((s) => s.legend !== false)
37
- if (!groups) return entries.length ? [entries] : []
41
+ // Zones and reference lines, which hue alone cannot name, lead: the compact row folds from its end.
42
+ if (!groups) return entries.length ? [entries.toSorted(byReferenceFirst)] : []
38
43
  return ROLE_ORDER.map((role) => entries.filter((s) => (s.role ?? 'series') === role)).filter(
39
44
  (g) => g.length > 0,
40
45
  )
@@ -57,8 +62,10 @@ const rowBaseStyle: CSSProperties = {
57
62
  const rowStyle: CSSProperties = { ...rowBaseStyle, display: 'flex' }
58
63
  /** The gaps `chart-legend.module.css` reads, as custom properties. */
59
64
  type LegendVars = CSSProperties & Record<'--bc-legend-gap' | '--bc-dots-gap', string>
65
+ // `flex-wrap` is the stylesheet's too: one folded row below 480px, wrapping rows from it.
66
+ const { flexWrap: _wrap, ...autoBaseStyle } = rowBaseStyle
60
67
  const autoRowStyle: LegendVars = {
61
- ...rowBaseStyle,
68
+ ...autoBaseStyle,
62
69
  '--bc-legend-gap': `${VX.legendGap}px`,
63
70
  '--bc-dots-gap': `${DOTS_GAP}px`,
64
71
  }
@@ -187,12 +194,69 @@ export type ChartLegendProps<T> = {
187
194
  hideAtWide?: boolean
188
195
  }
189
196
 
197
+ const VISUALLY_HIDDEN = {
198
+ position: 'absolute',
199
+ width: '1px',
200
+ height: '1px',
201
+ overflow: 'hidden',
202
+ clipPath: 'inset(50%)',
203
+ whiteSpace: 'nowrap',
204
+ } as const
205
+
206
+ /**
207
+ * The compact legend is ONE row (the stylesheet sets `nowrap` below 480px). Entries that do not fit
208
+ * fold into a `+N` chip (named for assistive tech by the folded labels), the last entry first. The
209
+ * entries are in display order: the reference/zone entries, which hue alone cannot name, lead the
210
+ * series (the title and tooltip name those).
211
+ * Measured on the node, never in React state, so a hover or a resize does not re-render.
212
+ */
213
+ function foldLegend(row: HTMLElement): void {
214
+ const items = [...row.querySelectorAll<HTMLElement>('[data-legend-key]')]
215
+ const more = row.querySelector<HTMLElement>('[data-legend-more]')
216
+ for (const it of items) it.removeAttribute('data-legend-folded')
217
+ more?.setAttribute('hidden', '')
218
+ if (more === null || getComputedStyle(row).flexWrap !== 'nowrap') return
219
+ const display = items
220
+ const folded: HTMLElement[] = []
221
+ while (row.scrollWidth > row.clientWidth + 0.5 && folded.length < display.length - 1) {
222
+ const last = display[display.length - 1 - folded.length]
223
+ if (last === undefined) break
224
+ last.setAttribute('data-legend-folded', '')
225
+ folded.push(last)
226
+ more.removeAttribute('hidden')
227
+ const names = folded.map((f) => f.textContent).join(', ')
228
+ more.textContent = `+${folded.length}`
229
+ more.title = names
230
+ // The folded labels, visually hidden: assistive tech reads `+2: Caution, Danger`.
231
+ const hiddenNames = document.createElement('span')
232
+ hiddenNames.textContent = `: ${names}`
233
+ Object.assign(hiddenNames.style, VISUALLY_HIDDEN)
234
+ more.append(hiddenNames)
235
+ }
236
+ }
237
+
190
238
  export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null {
239
+ const rowRef = useRef<HTMLFieldSetElement>(null)
240
+ const auto = props.mode === 'auto'
241
+ // Re-fold when the entries change; a resize re-folds through the observer.
242
+ const signature = props.series.map((s) => s.key).join('|')
243
+ // `signature` is intentionally an extra dep: the fold must re-run when the entries change.
244
+ useLayoutEffect(() => {
245
+ if (auto && rowRef.current !== null) foldLegend(rowRef.current)
246
+ }, [auto, signature])
247
+ // Same: `signature` re-subscribes the observer to the re-rendered row.
248
+ useEffect(() => {
249
+ const row = rowRef.current
250
+ if (!auto || row === null || typeof ResizeObserver === 'undefined') return
251
+ const observer = new ResizeObserver(() => foldLegend(row))
252
+ observer.observe(row)
253
+ return () => observer.disconnect()
254
+ }, [auto, signature])
191
255
  const groups = legendEntries(props.series, props.groups)
192
256
  if (groups.length === 0) return null
193
- const auto = props.mode === 'auto'
194
257
  return (
195
258
  <fieldset
259
+ ref={rowRef}
196
260
  aria-label="Legend"
197
261
  data-basalt-chart-legend={props.mode}
198
262
  // `visibility: hidden` is the real guard (nothing is announced, focused or clickable);
@@ -219,6 +283,7 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
219
283
  <span
220
284
  key={s.key}
221
285
  data-legend-key={s.key}
286
+ data-legend-role={s.role ?? 'series'}
222
287
  style={itemStyle}
223
288
  onMouseEnter={() => props.onHighlight(s.key)}
224
289
  onMouseLeave={() => props.onHighlight(null)}
@@ -231,6 +296,7 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
231
296
  key={s.key}
232
297
  type="button"
233
298
  data-legend-key={s.key}
299
+ data-legend-role={s.role ?? 'series'}
234
300
  data-basalt-hit=""
235
301
  aria-pressed={!off}
236
302
  style={itemStyle}
@@ -245,6 +311,7 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
245
311
  )
246
312
  }),
247
313
  ])}
314
+ {auto && <span data-legend-more="" hidden style={noteStyle} />}
248
315
  </fieldset>
249
316
  )
250
317
  }
@@ -1,10 +1,11 @@
1
1
  /*
2
- * The sparkline's hover / focus readout: one quiet chip, never a floating tooltip, so a narrow cell
3
- * cannot be escaped. It sits INSIDE the plot box, beside the hovered point (the roomier side, so it
4
- * flips at the edges) and on the half of the box away from the point, so it covers neither the dot
5
- * nor anything the host draws round the sparkline (a card's delta period, a strip's caption): a chip
6
- * above the box landed on that text, and a host slot that clips took it off the page. Where it
7
- * crosses the line it is opaque, so it reads over it. Placement is inline (`Sparkline.tsx`).
2
+ * The sparkline's hover / focus readout: one quiet chip, never a floating tooltip. Inside a host that
3
+ * reserves a line for it (`StatCard`'s sparkline slot, a strip cell's visual: `data-basalt-hosted`,
4
+ * `--basalt-spark-readout-h`) it sits ABOVE the plot, so it never covers the plotted line, the dashed
5
+ * reference or the dot. A bare `Sparkline` has no such line, so its chip stays inside its own box
6
+ * (placed inline in `Sparkline.tsx`, away from the point). `Sparkline.tsx` slides it with the point
7
+ * (`left` + `translate` by one fraction), which keeps it inside the box at either edge at any width.
8
+ * `--basalt-spark-readout-lift: 0` on a host puts the chip back in the box.
8
9
  */
9
10
 
10
11
  .root {
@@ -35,10 +36,62 @@
35
36
  border-radius: var(--vx-radius-ctrl);
36
37
  }
37
38
 
39
+ /* The host's reserved line: above the plot. The chip's bottom meets the sparkline's own top edge (the
40
+ * layer sits `--basalt-spark-inset` below it). */
41
+ [data-basalt-hosted] .readout {
42
+ top: calc(
43
+ var(--basalt-spark-readout-lift, 1) * -1 *
44
+ (var(--basalt-spark-readout-h, 1.125rem) + var(--basalt-spark-inset, 0px))
45
+ );
46
+ max-height: none;
47
+ }
48
+
38
49
  .label {
39
50
  opacity: 0.7;
40
51
  }
41
52
 
53
+ .sep {
54
+ white-space: pre;
55
+ }
56
+
57
+ /* A readout that overflows its box first drops the air round its separator and its padding. */
58
+ .readout[data-tight] {
59
+ padding-inline: 2px;
60
+ }
61
+
62
+ .readout[data-tight] .sep {
63
+ letter-spacing: -0.15em;
64
+ word-spacing: -0.25em;
65
+ }
66
+
67
+ /* A readout that still overflows stacks (set in `Sparkline.tsx`): the date on its own line, wrapped
68
+ * not clipped. It sits INSIDE the plot's top band (the lift-0 placement), hosted or bare: a hosted
69
+ * chip grown past the host's one reserved line would cover the figure's delta or qualifier above. */
70
+ .readout[data-stacked] {
71
+ block-size: auto;
72
+ max-height: none;
73
+ padding-block: 1px;
74
+ line-height: 1.25;
75
+ text-overflow: clip;
76
+ white-space: normal;
77
+ overflow-wrap: break-word;
78
+ /* Not the shrink-to-fit width an absolutely positioned box gets: at a point near the right edge
79
+ * that is the sliver right of `left`, and the date would wrap letter by letter. */
80
+ width: max-content;
81
+ }
82
+
83
+ [data-basalt-hosted] .readout[data-stacked] {
84
+ top: 0;
85
+ }
86
+
87
+ .readout[data-stacked] .label {
88
+ display: block;
89
+ }
90
+
91
+ .readout[data-stacked] .sep {
92
+ display: none;
93
+ }
94
+
42
95
  .layer {
43
96
  position: absolute;
44
97
  pointer-events: none;
@@ -6,6 +6,7 @@ declare const classes: {
6
6
  readonly root: string
7
7
  readonly readout: string
8
8
  readonly label: string
9
+ readonly sep: string
9
10
  readonly layer: string
10
11
  readonly dot: string
11
12
  }
@@ -106,7 +106,7 @@ export function ChartPlaceholder(props: {
106
106
  )
107
107
  const label =
108
108
  kind === 'error'
109
- ? toErrorMessage(props.state?.error, 'The chart failed to load.')
109
+ ? toErrorMessage(props.state?.error, 'The request failed.')
110
110
  : emptyLabel(props.state)
111
111
  const body = props.compact ? (
112
112
  <span aria-hidden="true">—</span>
@@ -132,6 +132,15 @@ export type ZoneSpec = {
132
132
  to: number
133
133
  fill: string
134
134
  axisSide?: 'left' | 'right' | undefined
135
+ /**
136
+ * Names the band in the legend (its fill as the swatch, a bar by default), so a zone chart keeps
137
+ * a key at 390 and needs no always-`null` series. `mark` is the swatch shape. `color` is the
138
+ * swatch when the fill is a whisper-alpha wash a 10px swatch would lose (default: the fill, a
139
+ * status tint mapped to its solid).
140
+ */
141
+ legend?:
142
+ | { label: string; mark?: 'line' | 'bar' | undefined; color?: string | undefined }
143
+ | undefined
135
144
  /** A rule on the band's visual `top` (the larger bound) and/or `bottom` (the smaller), whichever
136
145
  * of `from`/`to` that is. */
137
146
  edge?: ZoneEdge<'top' | 'bottom'> | undefined