basalt-ui 2.25.0 → 2.26.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 (72) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/MIGRATING.md +152 -19
  3. package/configs/oxlint-basalt.json +1 -1
  4. package/configs/oxlint-plugin.js +3 -9
  5. package/configs/oxlint-plugin.test.ts +6 -0
  6. package/dist/charts/ChartCard.d.ts +5 -3
  7. package/dist/charts/ChartCard.d.ts.map +1 -1
  8. package/dist/charts/ChartCard.js +10 -2
  9. package/dist/charts/Sparkline.d.ts.map +1 -1
  10. package/dist/charts/Sparkline.js +65 -7
  11. package/dist/charts/chart-box.module.css +50 -7
  12. package/dist/charts/chart-box.module.css.d.ts +2 -0
  13. package/dist/charts/chart-card.module.css +34 -0
  14. package/dist/charts/chart-card.module.css.d.ts +2 -0
  15. package/dist/charts/chart-legend.module.css +5 -6
  16. package/dist/charts/compile.d.ts.map +1 -1
  17. package/dist/charts/compile.js +27 -1
  18. package/dist/charts/legend.d.ts.map +1 -1
  19. package/dist/charts/legend.js +42 -9
  20. package/dist/charts/sparkline.module.css +13 -9
  21. package/dist/charts/state.d.ts.map +1 -1
  22. package/dist/charts/state.js +6 -1
  23. package/dist/dashboard/meter-model.d.ts +2 -0
  24. package/dist/dashboard/meter-model.d.ts.map +1 -1
  25. package/dist/dashboard/meter-model.js +99 -7
  26. package/dist/dashboard/meter-parts.d.ts +4 -7
  27. package/dist/dashboard/meter-parts.d.ts.map +1 -1
  28. package/dist/dashboard/meter-parts.js +102 -78
  29. package/dist/dashboard/meter.d.ts +1 -1
  30. package/dist/dashboard/meter.d.ts.map +1 -1
  31. package/dist/dashboard/meter.js +10 -7
  32. package/dist/dashboard/meter.module.css +43 -12
  33. package/dist/dashboard/meter.module.css.d.ts +1 -2
  34. package/dist/dashboard/section.d.ts +1 -2
  35. package/dist/dashboard/section.d.ts.map +1 -1
  36. package/dist/dashboard/section.module.css +8 -7
  37. package/dist/dashboard/stat-card.module.css +17 -0
  38. package/dist/dashboard/stat-strip.d.ts +9 -1
  39. package/dist/dashboard/stat-strip.d.ts.map +1 -1
  40. package/dist/dashboard/stat-strip.js +32 -6
  41. package/dist/dashboard/stat-strip.module.css +38 -0
  42. package/dist/dashboard/stat-strip.module.css.d.ts +3 -0
  43. package/dist/dashboard/visual-slot.d.ts +4 -0
  44. package/dist/dashboard/visual-slot.d.ts.map +1 -1
  45. package/dist/dashboard/visual-slot.js +2 -0
  46. package/dist/dashboard/widget-header.module.css +9 -0
  47. package/llms.txt +2 -2
  48. package/package.json +1 -1
  49. package/src/charts/ChartCard.tsx +23 -4
  50. package/src/charts/Sparkline.tsx +105 -10
  51. package/src/charts/chart-box.module.css +50 -7
  52. package/src/charts/chart-box.module.css.d.ts +2 -0
  53. package/src/charts/chart-card.module.css +34 -0
  54. package/src/charts/chart-card.module.css.d.ts +2 -0
  55. package/src/charts/chart-legend.module.css +5 -6
  56. package/src/charts/compile.ts +40 -1
  57. package/src/charts/legend.tsx +64 -16
  58. package/src/charts/sparkline.module.css +13 -9
  59. package/src/charts/state.tsx +18 -1
  60. package/src/dashboard/meter-model.ts +147 -12
  61. package/src/dashboard/meter-parts.tsx +71 -50
  62. package/src/dashboard/meter.module.css +43 -12
  63. package/src/dashboard/meter.module.css.d.ts +1 -2
  64. package/src/dashboard/meter.tsx +22 -9
  65. package/src/dashboard/section.module.css +8 -7
  66. package/src/dashboard/section.tsx +1 -2
  67. package/src/dashboard/stat-card.module.css +17 -0
  68. package/src/dashboard/stat-strip.module.css +38 -0
  69. package/src/dashboard/stat-strip.module.css.d.ts +3 -0
  70. package/src/dashboard/stat-strip.tsx +49 -8
  71. package/src/dashboard/visual-slot.ts +5 -0
  72. package/src/dashboard/widget-header.module.css +9 -0
@@ -1,7 +1,9 @@
1
1
  import { createContext } from "react";
2
2
  const HOSTED = {};
3
+ const HOSTED_LOADING = { loading: true };
3
4
  const VisualSlotContext = createContext(null);
4
5
  export {
5
6
  HOSTED,
7
+ HOSTED_LOADING,
6
8
  VisualSlotContext
7
9
  };
@@ -221,6 +221,15 @@
221
221
  min-width: 0;
222
222
  }
223
223
 
224
+ /* A `widget` tier (ChartCard) caption in `actions` — `<Text size="xs">`, 12 — joins the chart text
225
+ * step beside the plot's ticks and legend (argo's strength cards: title 13 + caption 12 + ticks 11
226
+ * + section title 15 was four sizes). The cap is the `--text-fz` variable `Text` reads, pinned
227
+ * `!important` over the inline value its `size` prop writes; other sizes (`md` figures, `sm`) are
228
+ * not touched, and a `Text` sized by a consumer class never reads the variable. */
229
+ .root[data-tier='widget'] .actions :global(.mantine-Text-root[style*='--mantine-font-size-xs']) {
230
+ --text-fz: var(--vx-text-micro) !important;
231
+ }
232
+
224
233
  /* Directly under the title row, 4px off it — 1px put it inside the title's own line box, so a
225
234
  * section with both read as a two-line heading rather than a heading plus a note. */
226
235
  .subtitle {
package/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # basalt-ui v2.25.0
1
+ # basalt-ui v2.26.0
2
2
  # Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets
3
3
  #
4
4
  # Entry points: use the exact import specifier below; do not guess.
@@ -13,7 +13,7 @@
13
13
  # A subpath's `Install:` line is its required peers; `OptionalPeers:` are import()-only, install on use.
14
14
 
15
15
  Package: basalt-ui
16
- Version: 2.25.0
16
+ Version: 2.26.0
17
17
 
18
18
  ## basalt-ui
19
19
  Import: import { ... } from 'basalt-ui'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "2.25.0",
3
+ "version": "2.26.0",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
@@ -136,7 +136,8 @@ type ChartCardBaseProps = BasaltProps &
136
136
  deltaPolarity?: DeltaPolarity | undefined
137
137
  /** A mono count tag after the title. */
138
138
  count?: number | undefined
139
- /** Right-aligned controls. */
139
+ /** Right-aligned controls. A `<Text size="xs">` caption here renders at 11 (the chart-text step,
140
+ * beside the plot's ticks); wrap it in a `span` or give it your own class to opt out. */
140
141
  actions?: ReactNode
141
142
  /** A resolved state replaces `children` with its placeholder; the header stays. */
142
143
  state?: ChartState | undefined
@@ -163,8 +164,9 @@ type ChartCardBaseProps = BasaltProps &
163
164
 
164
165
  /**
165
166
  * `facts` replaces the legacy `value`/`delta` hero: the two are mutually exclusive in the type. The
166
- * facts show only at rest: while `state` is pending, errored or empty the figure would sit above a
167
- * skeleton or a placeholder that contradicts it, so the header keeps its title row alone.
167
+ * figures show only at rest: while `state` is errored or empty one would sit above a placeholder that
168
+ * contradicts it, so the header keeps its title row alone. While pending the row keeps its footprint
169
+ * as a skeleton (a figure bar and, with a `subtitle`, a basis line), never the stale figure.
168
170
  */
169
171
  export type ChartCardProps = ChartCardBaseProps &
170
172
  (
@@ -232,6 +234,18 @@ function Facts({
232
234
  )
233
235
  }
234
236
 
237
+ /** The facts row of a pending card: bars at the loaded row's height, no figure. */
238
+ function FactsSkeleton({ basis }: { basis: boolean }): ReactElement {
239
+ return (
240
+ <div data-basalt-facts-skeleton="" aria-hidden="true" className={classes.facts}>
241
+ <div className={classes.factsRow}>
242
+ <span className={classes.skeletonFigure} />
243
+ </div>
244
+ {basis && <p className={cx(classes.factsBasis, classes.skeletonBasis)} />}
245
+ </div>
246
+ )
247
+ }
248
+
235
249
  export function ChartCard({
236
250
  actions,
237
251
  state,
@@ -251,8 +265,12 @@ export function ChartCard({
251
265
  const { ref, short } = useShortCard()
252
266
  const resolved = resolveChartState(state)
253
267
  const showFacts = facts !== undefined && resolved === null
268
+ const skeletonFacts = facts !== undefined && resolved === 'pending'
254
269
  const hasHeader =
255
- actions !== undefined || showFacts || HEADER_TRIGGERS.some((k) => header[k] !== undefined)
270
+ actions !== undefined ||
271
+ showFacts ||
272
+ skeletonFacts ||
273
+ HEADER_TRIGGERS.some((k) => header[k] !== undefined)
256
274
  // With facts the subtitle is the basis line after them, not WidgetHeader's foldable row.
257
275
  const { subtitle, ...rest } = header
258
276
  const headerProps = facts === undefined ? header : rest
@@ -278,6 +296,7 @@ export function ChartCard({
278
296
  })}
279
297
  />
280
298
  {showFacts && <Facts facts={facts} basis={subtitle} stale={stale} />}
299
+ {skeletonFacts && <FactsSkeleton basis={subtitle !== undefined} />}
281
300
  </div>
282
301
  )}
283
302
  <div
@@ -389,18 +389,90 @@ function meanOf(rows: readonly Point[]): number {
389
389
  return sum / n
390
390
  }
391
391
 
392
+ /** A plotted point as fractions of the plot rect: `[fx, fy]`, fy down. */
393
+ type LinePoint = readonly [number, number]
394
+
395
+ /** Air between a stacked chip and the plotted line (stroke and dot radius included), px. */
396
+ const CLEAR = 4
397
+
398
+ /** Whether the polyline passes through the box `[left, left + w] x [top, top + h]`, grown by CLEAR. */
399
+ function lineHits(
400
+ pts: readonly (readonly [number, number])[],
401
+ box: { left: number; top: number; w: number; h: number },
402
+ ): boolean {
403
+ const x0 = box.left - CLEAR
404
+ const x1 = box.left + box.w + CLEAR
405
+ const y0 = box.top - CLEAR
406
+ const y1 = box.top + box.h + CLEAR
407
+ for (let i = 0; i < pts.length; i += 1) {
408
+ const [ax, ay] = pts[i] as readonly [number, number]
409
+ const next = pts[i + 1]
410
+ if (next === undefined) return ax >= x0 && ax <= x1 && ay >= y0 && ay <= y1
411
+ const [bx, by] = next
412
+ if (Math.max(ax, bx) < x0 || Math.min(ax, bx) > x1) continue
413
+ // y at the segment's ends clipped to the box's x-range: y is linear, so its range is the ends'.
414
+ const yAt = (x: number): number => (bx === ax ? ay : ay + ((by - ay) * (x - ax)) / (bx - ax))
415
+ const ya = yAt(Math.max(Math.min(ax, bx), x0))
416
+ const yb = yAt(Math.min(Math.max(ax, bx), x1))
417
+ if (Math.max(ya, yb) >= y0 && Math.min(ya, yb) <= y1) return true
418
+ }
419
+ return false
420
+ }
421
+
392
422
  /**
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.
423
+ * A hosted line's stacked chip is two lines tall, more than the host's one reserved line, so it sits
424
+ * in the plot, and never on the plotted line: first at the cursor (slid with it) at the plot's top,
425
+ * then its bottom, then to the right and to the left of the cursor at either edge, the first of
426
+ * those the line misses. A plot too short for the chip (a 22px strip cell) has no such spot: the
427
+ * chip then hangs from the plot's bottom edge, over the host's footer or card padding: a hover
428
+ * covers the figure's secondary text before it covers the data or the figure's delta above.
429
+ * Offsets go on `margin-left` and `top`, which React's `left` / `translate` do not own.
396
430
  */
397
- function fitReadout(node: HTMLElement): void {
431
+ function placeStacked(node: HTMLElement, line: () => readonly LinePoint[], fx: number): void {
432
+ const layer = node.parentElement
433
+ if (!layer) return
434
+ const [W, H, w, h] = [layer.clientWidth, layer.clientHeight, node.offsetWidth, node.offsetHeight]
435
+ if (W <= 0 || H <= 0) return
436
+ const pts = line().map(([x, y]): [number, number] => [x * W, y * H])
437
+ const slid = fx * (W - w)
438
+ const room = (left: number): number => Math.min(Math.max(left, 0), Math.max(W - w, 0))
439
+ const lefts = [slid, room(fx * W + CLEAR * 2), room(fx * W - CLEAR * 2 - w)]
440
+ const tops = [0, Math.max(H - h, 0)]
441
+ const fit = lefts
442
+ .flatMap((left) => tops.map((top) => ({ left, top, w, h })))
443
+ .find((box) => !lineHits(pts, box))
444
+ if (!fit) {
445
+ node.style.top = `${H + CLEAR}px`
446
+ return
447
+ }
448
+ node.style.top = `${fit.top}px`
449
+ node.style.marginLeft = `${fit.left - slid}px`
450
+ }
451
+
452
+ /**
453
+ * A readout never loses its separator or its date to an ellipsis: when the one-line chip overflows
454
+ * its box it first tightens (`data-tight`: less padding, the separator's air stays), then stacks
455
+ * (`data-stacked`: the date on its own line, placed off the plotted line when `line` is given). Set
456
+ * on the node, so a measure never re-renders.
457
+ */
458
+ function fitReadout(
459
+ node: HTMLElement,
460
+ line: (() => readonly LinePoint[]) | null,
461
+ fx: number,
462
+ ): void {
398
463
  const overflows = (): boolean => node.scrollWidth > node.clientWidth
399
464
  node.removeAttribute('data-tight')
400
465
  node.removeAttribute('data-stacked')
466
+ // `top` is React's on a bare chip; a hosted line's chip is the only one `placeStacked` writes to.
467
+ if (line !== null) {
468
+ node.style.removeProperty('top')
469
+ node.style.removeProperty('margin-left')
470
+ }
401
471
  if (!overflows()) return
402
472
  node.setAttribute('data-tight', '')
403
- if (overflows()) node.setAttribute('data-stacked', '')
473
+ if (!overflows()) return
474
+ node.setAttribute('data-stacked', '')
475
+ if (line !== null) placeStacked(node, line, fx)
404
476
  }
405
477
 
406
478
  export function Sparkline(props: SparklineProps): ReactElement {
@@ -514,16 +586,39 @@ export function Sparkline(props: SparklineProps): ReactElement {
514
586
  const beside = at === null ? null : at.fx > 0.5 ? 'left' : 'right'
515
587
  // The chip's fit depends on its text and (bare) its side, not on the pointer's every tick.
516
588
  const shown = at !== null
589
+ // The cursor's fraction is read at fit time: it moves with `active`, which already refits.
590
+ const fxRef = useRef(0)
517
591
  useLayoutEffect(() => {
518
- if (readoutRef.current !== null) fitReadout(readoutRef.current)
519
- }, [active, at?.label, at?.value, beside])
592
+ fxRef.current = at?.fx ?? 0
593
+ })
594
+ const fitRef = useRef<() => void>(() => {})
595
+ useLayoutEffect(() => {
596
+ // A hosted line's stacked chip clears the plotted line, built only when the chip stacks; a bar
597
+ // or a bare chip keeps its place.
598
+ const line =
599
+ hosted && mark === 'line' && model !== null
600
+ ? (): LinePoint[] =>
601
+ model.rows.flatMap((r, i): LinePoint[] =>
602
+ r.v === null
603
+ ? []
604
+ : [
605
+ [
606
+ (i - model.frame.x[0]) / (model.frame.x[1] - model.frame.x[0]),
607
+ (model.frame.y[1] - r.v) / (model.frame.y[1] - model.frame.y[0]),
608
+ ],
609
+ ],
610
+ )
611
+ : null
612
+ fitRef.current = () => {
613
+ if (readoutRef.current !== null) fitReadout(readoutRef.current, line, fxRef.current)
614
+ }
615
+ fitRef.current()
616
+ }, [active, at?.label, at?.value, beside, hosted, mark, model])
520
617
  // ...and on the box, which a container resize changes without a hover.
521
618
  useEffect(() => {
522
619
  const layer = readoutRef.current?.parentElement
523
620
  if (!shown || !layer || typeof ResizeObserver === 'undefined') return
524
- const observer = new ResizeObserver(() => {
525
- if (readoutRef.current !== null) fitReadout(readoutRef.current)
526
- })
621
+ const observer = new ResizeObserver(() => fitRef.current())
527
622
  observer.observe(layer)
528
623
  return () => observer.disconnect()
529
624
  }, [shown])
@@ -93,21 +93,64 @@
93
93
  min-height: inherit;
94
94
  }
95
95
 
96
+ /*
97
+ * A pending plot in the loaded shape (`state.tsx`): an axis baseline and a few bar ghosts in a
98
+ * neutral tone, so a loading card reads as the chart it will be rather than a blank plate. Heights
99
+ * are constants, so the server HTML is the client's. 18% ink over the panel is the tone of the
100
+ * facts skeleton (`chart-card.module.css`).
101
+ */
102
+ .ghost {
103
+ box-sizing: border-box;
104
+ display: flex;
105
+ align-items: flex-end;
106
+ gap: 5%;
107
+ width: 100%;
108
+ height: 100%;
109
+ padding: 12px 4px 0;
110
+ /* The axis baseline: a 1px line painted under the ghosts, not a border (the divider law inventories those). */
111
+ background: linear-gradient(
112
+ color-mix(in srgb, var(--vx-ink) 24%, var(--vx-surface-panel)),
113
+ color-mix(in srgb, var(--vx-ink) 24%, var(--vx-surface-panel))
114
+ )
115
+ bottom / 100% 1px no-repeat;
116
+ }
117
+
118
+ .ghostBar {
119
+ flex: 1 1 0;
120
+ min-width: 0;
121
+ border-radius: 3px 3px 0 0;
122
+ background: color-mix(in srgb, var(--vx-ink) 18%, var(--vx-surface-panel));
123
+ }
124
+
96
125
  /*
97
126
  * The engine paints its tooltip rows as a grid of `.55rem | minmax(0, 1fr) | auto` with inline
98
127
  * styles and `overflow-wrap: anywhere` on the card, so a narrow tooltip (a 390 viewport, a pointer
99
128
  * near an edge) squeezes the name column to one character per line. The name keeps a floor and
100
- * never wraps; a long name ends in an ellipsis, the value stays right-aligned. The tooltip is
101
- * portalled out of the chart's tree, hence the global class names. `!important` because the
102
- * engine's own values are inline.
129
+ * wraps at word breaks when it must; the figure never wraps and never ends in an ellipsis, it stays
130
+ * right-aligned. The tooltip is portalled out of the chart's tree, hence the global class names.
131
+ * `!important` because the engine's own values are inline.
103
132
  */
104
133
  :global(.ts-chart-tooltip__row) {
105
- grid-template-columns: 0.55rem minmax(6rem, max-content) auto !important;
134
+ grid-template-columns: 0.55rem minmax(6rem, 1fr) auto !important;
106
135
  }
107
136
 
108
137
  :global(.ts-chart-tooltip__row > span:nth-child(2)) {
109
- max-width: 14rem;
110
- overflow: hidden;
111
- text-overflow: ellipsis;
138
+ overflow-wrap: break-word;
139
+ white-space: normal;
140
+ }
141
+
142
+ :global(.ts-chart-tooltip__row > span:nth-child(3)) {
112
143
  white-space: nowrap;
113
144
  }
145
+
146
+ /* Opaque in both schemes: `--vx-tooltip-bg` is translucent in dark and the card's footer ghosts
147
+ * through a tooltip that opens over it (a slotted `Bars`). The tint is layered over the elevated
148
+ * surface, so a consumer's `tooltipBg` and `--basalt-tooltip-surface` still colour it. The engine's
149
+ * own value is inline. */
150
+ :global(.ts-chart-tooltip) {
151
+ background: linear-gradient(
152
+ var(--basalt-tooltip-surface, var(--vx-tooltip-bg)),
153
+ var(--basalt-tooltip-surface, var(--vx-tooltip-bg))
154
+ )
155
+ var(--vx-surface-elevated) !important;
156
+ }
@@ -9,5 +9,7 @@ declare const classes: {
9
9
  readonly fill: string
10
10
  readonly state: string
11
11
  readonly grow: string
12
+ readonly ghost: string
13
+ readonly ghostBar: string
12
14
  }
13
15
  export default classes
@@ -95,3 +95,37 @@
95
95
  .factsRow[data-stale] {
96
96
  opacity: 0.55;
97
97
  }
98
+
99
+ /*
100
+ * A pending card keeps its facts footprint: bars as tall as the loaded figure and basis lines (`1lh`
101
+ * at the same font size), painted a little inside the line box so they read as text, not slabs. The
102
+ * tone is the chart ghost's (`chart-box.module.css` `.ghost`).
103
+ */
104
+ .skeletonFigure,
105
+ .skeletonBasis {
106
+ position: relative;
107
+ display: block;
108
+ }
109
+
110
+ .skeletonFigure {
111
+ font-size: var(--vx-text-kpi);
112
+ height: 1lh;
113
+ width: 4.5rem;
114
+ }
115
+
116
+ .skeletonBasis {
117
+ font-size: var(--vx-text-sm);
118
+ height: 1lh;
119
+ width: 9rem;
120
+ max-width: 100%;
121
+ }
122
+
123
+ .skeletonFigure::before,
124
+ .skeletonBasis::before {
125
+ content: '';
126
+ position: absolute;
127
+ inset-inline: 0;
128
+ inset-block: 0.2lh;
129
+ border-radius: 3px;
130
+ background: color-mix(in srgb, var(--vx-ink) 18%, var(--vx-surface-panel));
131
+ }
@@ -11,5 +11,7 @@ declare const classes: {
11
11
  readonly factValue: string
12
12
  readonly factUnit: string
13
13
  readonly factPeriod: string
14
+ readonly skeletonFigure: string
15
+ readonly skeletonBasis: string
14
16
  }
15
17
  export default classes
@@ -15,10 +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
+ /* `foldLegend` (legend.tsx) folds the zones / references that wrap the row into `+N`; series never fold. */
19
19
  .auto {
20
- flex-wrap: nowrap;
21
- overflow: hidden;
20
+ --bc-fold: 1;
21
+ flex-wrap: wrap;
22
22
  display: flex;
23
23
  column-gap: var(--bc-dots-gap);
24
24
  --vx-hit-gap: var(--bc-dots-gap);
@@ -27,8 +27,7 @@
27
27
 
28
28
  @container (min-width: 480px) {
29
29
  .auto {
30
- flex-wrap: wrap;
31
- overflow: visible;
30
+ --bc-fold: 0;
32
31
  column-gap: var(--bc-legend-gap);
33
32
  --vx-hit-gap: var(--bc-legend-gap);
34
33
  }
@@ -49,7 +48,7 @@
49
48
  }
50
49
  }
51
50
 
52
- /* The compact fold (`foldLegend`, which only folds while the row is `nowrap`); wide keeps every entry.
51
+ /* The compact fold (`foldLegend`, which only folds while `--bc-fold` is 1); wide keeps every entry.
53
52
  * `!important`: an entry's inline `all: unset` (legend.tsx) would otherwise reset `display`. */
54
53
  .auto [data-legend-folded] {
55
54
  display: none !important;
@@ -15,6 +15,7 @@ import { ruleX, ruleY } from '@tanstack/charts/rule'
15
15
  import { scaleLinear } from '@tanstack/charts/scales/linear'
16
16
  import { scaleUtc } from 'd3-scale'
17
17
  import { portal } from '@tanstack/charts/tooltip/portal'
18
+ import type { ChartTooltipPortalExtension } from '@tanstack/charts/tooltip/portal'
18
19
  import type {
19
20
  ChartBuildContext,
20
21
  ChartTooltipAnchorContext,
@@ -1057,6 +1058,44 @@ const barAnchor =
1057
1058
  return { x: Math.min(Math.max(stepped, plot.x), plot.x + plot.width), y: floor }
1058
1059
  }
1059
1060
 
1061
+ /** The card a tooltip stays inside: a `ChartCard`, a strip cell, a `StatCard` (a Mantine Card). Never a Paper: the nearest small inner one would clamp. */
1062
+ const TIP_CARD = '[data-basalt-chart-card], [data-strip-cell], .mantine-Card-root'
1063
+ /** Air between a card-clamped tooltip and the card's edge, px. */
1064
+ const TIP_CARD_AIR = 4
1065
+
1066
+ /**
1067
+ * The engine places a portalled tooltip against the viewport, so at the first or last point of a
1068
+ * chart it opens past the card's edge, over the neighbouring card. Its placements (a hover, and its
1069
+ * own resize / scroll repositions, which never pass through `position`) all write the element's
1070
+ * inline `left`, so each write is followed by a slide back inside the card (the viewport placement
1071
+ * stands when the card is narrower than the tooltip).
1072
+ */
1073
+ const cardPortal: ChartTooltipPortalExtension = {
1074
+ id: portal.id,
1075
+ create(context, options) {
1076
+ const inner = portal.create(context, options)
1077
+ const { element, container } = context
1078
+ const watch = new MutationObserver(() => clampToCard(element, container))
1079
+ watch.observe(element, { attributes: true, attributeFilter: ['style'] })
1080
+ return {
1081
+ ...inner,
1082
+ destroy() {
1083
+ watch.disconnect()
1084
+ inner.destroy()
1085
+ },
1086
+ }
1087
+ },
1088
+ }
1089
+
1090
+ function clampToCard(tip: HTMLElement, within: Element): void {
1091
+ const card = within.closest(TIP_CARD)?.getBoundingClientRect()
1092
+ const left = Number.parseFloat(tip.style.left)
1093
+ const width = tip.offsetWidth
1094
+ if (!card || Number.isNaN(left) || width + 2 * TIP_CARD_AIR > card.width) return
1095
+ const next = Math.min(Math.max(left, card.left + TIP_CARD_AIR), card.right - width - TIP_CARD_AIR)
1096
+ if (Math.abs(next - left) > 0.5) tip.style.left = `${next}px`
1097
+ }
1098
+
1060
1099
  function tooltipSpec<T, X extends ChartX>(opts: {
1061
1100
  input: CartesianInput<T, X>
1062
1101
  axes: Axes<T>
@@ -1075,7 +1114,7 @@ function tooltipSpec<T, X extends ChartX>(opts: {
1075
1114
  return {
1076
1115
  use: quietWhileFollowing,
1077
1116
  ...followerOptions(input.tooltip, input.cursorGroup, input.chartId),
1078
- portal,
1117
+ portal: cardPortal,
1079
1118
  anchor: input.tooltipBelow
1080
1119
  ? stripAnchor
1081
1120
  : visible.some((s) => s.mark === 'bar')
@@ -29,8 +29,8 @@ const ROLE_ORDER = ['series', 'overlay', 'reference'] as const
29
29
  */
30
30
  const DOTS_GAP = 30
31
31
 
32
- const byReferenceFirst = <T,>(a: ChartSeries<T>, b: ChartSeries<T>): number =>
33
- Number(b.role === 'reference') - Number(a.role === 'reference')
32
+ const byReferenceLast = <T,>(a: ChartSeries<T>, b: ChartSeries<T>): number =>
33
+ Number(a.role === 'reference') - Number(b.role === 'reference')
34
34
 
35
35
  /** The entries a series list derives, in display order (by role when `groups`). */
36
36
  export function legendEntries<T>(
@@ -38,8 +38,8 @@ export function legendEntries<T>(
38
38
  groups: boolean,
39
39
  ): ChartSeries<T>[][] {
40
40
  const entries = series.filter((s) => s.legend !== false)
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)] : []
41
+ // Series lead, zones and reference lines follow: the compact fold takes the references from the end.
42
+ if (!groups) return entries.length ? [entries.toSorted(byReferenceLast)] : []
43
43
  return ROLE_ORDER.map((role) => entries.filter((s) => (s.role ?? 'series') === role)).filter(
44
44
  (g) => g.length > 0,
45
45
  )
@@ -62,7 +62,7 @@ const rowBaseStyle: CSSProperties = {
62
62
  const rowStyle: CSSProperties = { ...rowBaseStyle, display: 'flex' }
63
63
  /** The gaps `chart-legend.module.css` reads, as custom properties. */
64
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.
65
+ // `flex-wrap` is the stylesheet's too, so the same rule wraps at every width.
66
66
  const { flexWrap: _wrap, ...autoBaseStyle } = rowBaseStyle
67
67
  const autoRowStyle: LegendVars = {
68
68
  ...autoBaseStyle,
@@ -94,11 +94,17 @@ const buttonStyle: CSSProperties = {
94
94
  border: '1px solid transparent',
95
95
  display: 'inline-flex',
96
96
  alignItems: 'center',
97
+ // An entry never wraps inside itself (a threshold stays with its name) and never outgrows the row:
98
+ // the label ellipsizes at the row's width (`labelStyle`), its full name in `title`.
99
+ whiteSpace: 'nowrap',
100
+ maxWidth: '100%',
101
+ minWidth: 0,
97
102
  gap: 6,
98
103
  cursor: 'pointer',
99
104
  borderRadius: VX.radiusCtrl,
100
105
  }
101
- const noteStyle: CSSProperties = { color: VX.axis }
106
+ const noteStyle: CSSProperties = { color: VX.axis, flex: 'none' }
107
+ const labelStyle: CSSProperties = { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }
102
108
 
103
109
  /**
104
110
  * A legend entry that may be a sign-coloured bar: `colorNegative` is the below-zero colour and the
@@ -204,10 +210,29 @@ const VISUALLY_HIDDEN = {
204
210
  } as const
205
211
 
206
212
  /**
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).
213
+ * The number of lines the visible entries (and the chip) sit on. Bucketed by vertical centre, so the
214
+ * chip's own height (shorter than an entry's) does not read as another line.
215
+ */
216
+ function lineCount(row: HTMLElement, more: HTMLElement): number {
217
+ const shown = [...row.querySelectorAll<HTMLElement>('[data-legend-key]')].filter(
218
+ (it) => !it.hasAttribute('data-legend-folded'),
219
+ )
220
+ if (!more.hidden) shown.push(more)
221
+ const centres = shown
222
+ .map((it) => {
223
+ const r = it.getBoundingClientRect()
224
+ return r.top + r.height / 2
225
+ })
226
+ .toSorted((x, y) => x - y)
227
+ // A new line starts where the centre jumps by more than half an entry's height.
228
+ return centres.filter((c, i) => i === 0 || c - (centres[i - 1] ?? c) > 6).length
229
+ }
230
+
231
+ /**
232
+ * The compact legend names every series at every width. When the row wraps below 480px, the
233
+ * zone / reference entries fold into a `+N` chip (named for assistive tech by the folded labels), the
234
+ * last first, only while the row has more lines than the series alone would; a series never folds.
235
+ * The entries are in display order: series, then zones / references.
211
236
  * Measured on the node, never in React state, so a hover or a resize does not re-render.
212
237
  */
213
238
  function foldLegend(row: HTMLElement): void {
@@ -215,11 +240,21 @@ function foldLegend(row: HTMLElement): void {
215
240
  const more = row.querySelector<HTMLElement>('[data-legend-more]')
216
241
  for (const it of items) it.removeAttribute('data-legend-folded')
217
242
  more?.setAttribute('hidden', '')
218
- if (more === null || getComputedStyle(row).flexWrap !== 'nowrap') return
219
- const display = items
243
+ // A label that ellipsizes carries its full name in `title`; one that fits carries none.
244
+ for (const label of row.querySelectorAll<HTMLElement>('[data-legend-label]')) {
245
+ if (label.scrollWidth > label.clientWidth + 0.5) label.title = label.textContent ?? ''
246
+ else label.removeAttribute('title')
247
+ }
248
+ // `--bc-fold` is the stylesheet's compact flag (chart-legend.module.css); wide keeps every entry.
249
+ if (more === null || getComputedStyle(row).getPropertyValue('--bc-fold').trim() !== '1') return
250
+ const references = items.filter((it) => it.dataset['legendRole'] === 'reference')
251
+ // The series-only line count is the floor: folding a reference that frees no line only hides a name.
252
+ for (const r of references) r.setAttribute('data-legend-folded', '')
253
+ const floor = lineCount(row, more)
254
+ for (const r of references) r.removeAttribute('data-legend-folded')
220
255
  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]
256
+ while (folded.length < references.length && lineCount(row, more) > floor) {
257
+ const last = references[references.length - 1 - folded.length]
223
258
  if (last === undefined) break
224
259
  last.setAttribute('data-legend-folded', '')
225
260
  folded.push(last)
@@ -233,6 +268,11 @@ function foldLegend(row: HTMLElement): void {
233
268
  Object.assign(hiddenNames.style, VISUALLY_HIDDEN)
234
269
  more.append(hiddenNames)
235
270
  }
271
+ // Folding freed no line (the chip's own width cost it): show every name instead.
272
+ if (folded.length > 0 && lineCount(row, more) > floor) {
273
+ for (const f of folded) f.removeAttribute('data-legend-folded')
274
+ more.setAttribute('hidden', '')
275
+ }
236
276
  }
237
277
 
238
278
  export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null {
@@ -250,7 +290,13 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
250
290
  if (!auto || row === null || typeof ResizeObserver === 'undefined') return
251
291
  const observer = new ResizeObserver(() => foldLegend(row))
252
292
  observer.observe(row)
253
- return () => observer.disconnect()
293
+ // A web font landing changes the entry widths without resizing the row.
294
+ let live = true
295
+ void document.fonts?.ready?.then(() => live && foldLegend(row))
296
+ return () => {
297
+ live = false
298
+ observer.disconnect()
299
+ }
254
300
  }, [auto, signature])
255
301
  const groups = legendEntries(props.series, props.groups)
256
302
  if (groups.length === 0) return null
@@ -273,7 +319,9 @@ export function ChartLegend<T>(props: ChartLegendProps<T>): ReactElement | null
273
319
  const content = (
274
320
  <>
275
321
  <Swatch s={s} mode={props.mode} />
276
- <span>{s.label}</span>
322
+ <span style={labelStyle} data-legend-label="">
323
+ {s.label}
324
+ </span>
277
325
  {s.note !== undefined && <span style={noteStyle}>{s.note}</span>}
278
326
  </>
279
327
  )