@sybilion/uilib 1.8.0 → 1.8.2

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 (50) hide show
  1. package/dist/esm/src/components/ui/Chart/Chart.js +4 -1
  2. package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +30 -8
  3. package/dist/esm/src/components/ui/Chart/components/ChartAxes.js +12 -11
  4. package/dist/esm/src/components/ui/Chart/components/ChartPlacedTooltip.js +65 -0
  5. package/dist/esm/src/components/ui/Chart/components/ChartTooltipContent.js +2 -2
  6. package/dist/esm/src/components/ui/Chart/components/ChartTooltipItem.js +22 -6
  7. package/dist/esm/src/components/ui/Chart/components/QuantileBands.js +1 -1
  8. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +14 -8
  9. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.js +2 -3
  10. package/dist/esm/src/components/ui/TimeRangeControls/TimeRangeControls.js +18 -4
  11. package/dist/esm/src/components/widgets/DriverCard/DriverPerformanceChart.js +5 -25
  12. package/dist/esm/src/index.js +1 -0
  13. package/dist/esm/types/src/components/ui/Chart/Chart.d.ts +4 -2
  14. package/dist/esm/types/src/components/ui/Chart/Chart.types.d.ts +5 -0
  15. package/dist/esm/types/src/components/ui/Chart/chartForecastVisualization.types.d.ts +7 -0
  16. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +17 -0
  17. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.test.d.ts +1 -0
  18. package/dist/esm/types/src/components/ui/Chart/components/ChartAxes.d.ts +8 -1
  19. package/dist/esm/types/src/components/ui/Chart/components/ChartAxes.test.d.ts +1 -0
  20. package/dist/esm/types/src/components/ui/Chart/components/ChartPlacedTooltip.d.ts +31 -0
  21. package/dist/esm/types/src/components/ui/Chart/components/ChartPlacedTooltip.test.d.ts +1 -0
  22. package/dist/esm/types/src/components/ui/Chart/components/ChartTooltipContent.d.ts +1 -1
  23. package/dist/esm/types/src/components/ui/Chart/components/ChartTooltipContent.test.d.ts +1 -0
  24. package/dist/esm/types/src/components/ui/Chart/components/ChartTooltipItem.d.ts +2 -1
  25. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +12 -1
  26. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.d.ts +2 -3
  27. package/dist/esm/types/src/components/ui/TimeRangeControls/TimeRangeControls.d.ts +9 -3
  28. package/dist/esm/types/src/components/ui/TimeRangeControls/TimeRangeControls.test.d.ts +1 -0
  29. package/package.json +2 -2
  30. package/src/components/ui/Chart/AGENT.md +5 -0
  31. package/src/components/ui/Chart/Chart.tsx +7 -1
  32. package/src/components/ui/Chart/Chart.types.ts +5 -0
  33. package/src/components/ui/Chart/chartForecastVisualization.types.ts +7 -0
  34. package/src/components/ui/Chart/components/BaseChartWrapper.test.tsx +344 -0
  35. package/src/components/ui/Chart/components/BaseChartWrapper.tsx +78 -36
  36. package/src/components/ui/Chart/components/ChartAxes.test.tsx +60 -0
  37. package/src/components/ui/Chart/components/ChartAxes.tsx +42 -45
  38. package/src/components/ui/Chart/components/ChartPlacedTooltip.test.tsx +160 -0
  39. package/src/components/ui/Chart/components/ChartPlacedTooltip.tsx +93 -0
  40. package/src/components/ui/Chart/components/ChartTooltipContent.test.tsx +85 -0
  41. package/src/components/ui/Chart/components/ChartTooltipContent.tsx +2 -0
  42. package/src/components/ui/Chart/components/ChartTooltipItem.tsx +41 -10
  43. package/src/components/ui/Chart/components/QuantileBands.tsx +1 -1
  44. package/src/components/ui/ChartAreaInteractive/AGENT.md +2 -0
  45. package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +75 -45
  46. package/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.tsx +2 -3
  47. package/src/components/ui/TimeRangeControls/AGENT.md +1 -1
  48. package/src/components/ui/TimeRangeControls/TimeRangeControls.test.tsx +40 -0
  49. package/src/components/ui/TimeRangeControls/TimeRangeControls.tsx +46 -35
  50. package/src/components/widgets/DriverCard/DriverPerformanceChart.tsx +2 -2
@@ -24,7 +24,7 @@ import {
24
24
  } from '#uilib/components/ui/ChartAreaInteractive/chartHistories';
25
25
  import { Skeleton } from '#uilib/components/ui/Skeleton';
26
26
  import { chartRenderQueue } from '#uilib/utils/chartRenderQueue';
27
- import { Tooltip as ChartTooltip, ComposedChart, LineChart } from 'recharts';
27
+ import { ComposedChart, LineChart } from 'recharts';
28
28
  import { LegendPayload } from 'recharts/types/component/DefaultLegendContent';
29
29
 
30
30
  import { normalizeTooltipPayload } from '../Chart.helpers';
@@ -39,6 +39,7 @@ import {
39
39
  type ChartEmptyStatusTone,
40
40
  } from './ChartEmptyState/ChartEmptyState';
41
41
  import { ChartGrid } from './ChartGrid';
42
+ import { ChartPlacedTooltip, isTooltipUnder } from './ChartPlacedTooltip';
42
43
  import { ChartTooltipContent } from './ChartTooltipContent';
43
44
  import { CustomChartLegend } from './CustomChartLegend/CustomChartLegend';
44
45
  import { LegendSvg } from './LegendSvg/LegendSvg';
@@ -84,6 +85,21 @@ function clampTooltipTranslate(args: {
84
85
  return { x: tx, y: ty };
85
86
  }
86
87
 
88
+ /**
89
+ * The tooltip slides after the cursor, unless the user asked for less motion.
90
+ * ChartPlacedTooltip turns this off under a narrow chart.
91
+ */
92
+ const TOOLTIP_WRAPPER_STYLE = {
93
+ transition: 'transform 0.2s ease-out, opacity 0.2s ease-out',
94
+ };
95
+
96
+ function tooltipWrapperStyle() {
97
+ const reduceMotion =
98
+ typeof window !== 'undefined' &&
99
+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
100
+ return reduceMotion ? undefined : TOOLTIP_WRAPPER_STYLE;
101
+ }
102
+
87
103
  export interface BaseChartWrapperProps {
88
104
  renderId?: string; // unique id for the render, used to identify the render in the render queue
89
105
  chartConfig?: ChartConfig;
@@ -117,6 +133,19 @@ export interface BaseChartWrapperProps {
117
133
  yMax?: number;
118
134
  autoScaleYAxis?: boolean;
119
135
  formatNumber?: (value: number) => string;
136
+ /**
137
+ * Formats the numbers in the tooltip. Without it they print as is. Not
138
+ * `formatNumber`, which is the axis's and often compact ("1.2k").
139
+ */
140
+ formatTooltipValue?: (value: number) => string;
141
+ /** Draw history lines across months with no value (default: a gap). */
142
+ connectHistoryNulls?: boolean;
143
+ /** Draw forecast lines across months with no value (default: a gap). */
144
+ connectForecastNulls?: boolean;
145
+ /** Draw history lines over the forecast lines (default: under them). */
146
+ historyOnTop?: boolean;
147
+ /** Mark each line's last point with a dot (default: on). */
148
+ showEndDots?: boolean;
120
149
  formatDate?: (value: string, detailed?: boolean) => string;
121
150
  labelFormatter?: (value: unknown) => string;
122
151
  onLegendClick?: (data: LegendPayload, index: number, event: any) => void;
@@ -130,6 +159,10 @@ export interface BaseChartWrapperProps {
130
159
  */
131
160
  disableLineDrawAnimation?: boolean;
132
161
  showGrid?: boolean;
162
+ /**
163
+ * Draw the axes. Off, a hidden x-axis is kept so the tooltip still names
164
+ * the row's date.
165
+ */
133
166
  showAxes?: boolean;
134
167
  showTooltip?: boolean;
135
168
  showLegend?: boolean;
@@ -237,6 +270,11 @@ const BaseChartWrapperContent = forwardRef<
237
270
  yMax,
238
271
  autoScaleYAxis = true,
239
272
  formatNumber,
273
+ formatTooltipValue,
274
+ connectHistoryNulls,
275
+ connectForecastNulls,
276
+ historyOnTop,
277
+ showEndDots,
240
278
  formatDate: formatDateFn = formatDate,
241
279
  labelFormatter,
242
280
  onLegendClick,
@@ -311,10 +349,18 @@ const BaseChartWrapperContent = forwardRef<
311
349
  const applyTooltipPosition = () => {
312
350
  const wrapper = tooltipWrapperRef.current;
313
351
  const coord = rawTooltipCoordinateRef.current;
314
- const chartWrapper = rootRef.current?.querySelector('.recharts-wrapper');
352
+ // The chart the tooltip belongs to (with the grid on, the first chart in
353
+ // the root is the grid layer's).
354
+ const chartWrapper =
355
+ wrapper?.closest('.recharts-wrapper') ??
356
+ rootRef.current?.querySelector('.recharts-wrapper');
315
357
 
316
358
  if (!wrapper || !coord || !(chartWrapper instanceof HTMLElement)) return;
317
359
 
360
+ // A narrow chart's tooltip sits under it, where ChartPlacedTooltip has
361
+ // recharts put it. Leave it there: one writer, so it does not jump.
362
+ if (isTooltipUnder(wrapper)) return;
363
+
318
364
  const measured = wrapper.getBoundingClientRect();
319
365
  const width = tooltipSizeRef.current.width || measured.width;
320
366
  const height = tooltipSizeRef.current.height || measured.height;
@@ -364,8 +410,6 @@ const BaseChartWrapperContent = forwardRef<
364
410
 
365
411
  if (wrapperEl instanceof HTMLElement) {
366
412
  tooltipWrapperRef.current = wrapperEl;
367
- wrapperEl.style.transition =
368
- 'transform 0.2s ease-out, opacity 0.2s ease-out';
369
413
  requestAnimationFrame(() => applyTooltipPositionRef.current());
370
414
  }
371
415
  };
@@ -432,6 +476,7 @@ const BaseChartWrapperContent = forwardRef<
432
476
  label={props.label}
433
477
  labelFormatter={labelFormatter || defaultLabelFormatter}
434
478
  indicator="dot"
479
+ valueFormatter={formatTooltipValue}
435
480
  />
436
481
  );
437
482
  }
@@ -455,6 +500,7 @@ const BaseChartWrapperContent = forwardRef<
455
500
  label={props.label}
456
501
  labelFormatter={labelFormatter || defaultLabelFormatter}
457
502
  indicator="dot"
503
+ valueFormatter={formatTooltipValue}
458
504
  />
459
505
  );
460
506
  };
@@ -663,6 +709,26 @@ const BaseChartWrapperContent = forwardRef<
663
709
  const ChartComponent = chartType === 'line' ? LineChart : ComposedChart;
664
710
  const defaultLabelFormatter = (v: unknown) => formatDateFn(v as string, true);
665
711
 
712
+ // The same axes in the grid layer and the chart layer, so both share one
713
+ // scale. Hidden when showAxes is off: the hidden x-axis still places the
714
+ // rows by date, so the tooltip names it.
715
+ const axes = (
716
+ <ChartAxes
717
+ hide={!showAxes}
718
+ formatDate={formatDateFn}
719
+ formatNumber={formatNumber}
720
+ xAxisClassName={xAxisClassName}
721
+ yAxisClassName={yAxisClassName}
722
+ xAxisLabel={xAxisLabel}
723
+ yAxisLabel={yAxisLabel}
724
+ xMin={xMin}
725
+ xMax={xMax}
726
+ yMin={yMin}
727
+ yMax={yMax}
728
+ autoScaleYAxis={effectiveAutoScale}
729
+ />
730
+ );
731
+
666
732
  return (
667
733
  <div
668
734
  className={cn(
@@ -690,21 +756,7 @@ const BaseChartWrapperContent = forwardRef<
690
756
  >
691
757
  <ChartComponent data={chartData} margin={margin}>
692
758
  <ChartGrid />
693
- {showAxes && (
694
- <ChartAxes
695
- formatDate={formatDateFn}
696
- formatNumber={formatNumber}
697
- xAxisClassName={xAxisClassName}
698
- yAxisClassName={yAxisClassName}
699
- xAxisLabel={xAxisLabel}
700
- yAxisLabel={yAxisLabel}
701
- xMin={xMin}
702
- xMax={xMax}
703
- yMin={yMin}
704
- yMax={yMax}
705
- autoScaleYAxis={effectiveAutoScale}
706
- />
707
- )}
759
+ {axes}
708
760
  </ChartComponent>
709
761
  </ChartContainer>
710
762
  )}
@@ -717,22 +769,7 @@ const BaseChartWrapperContent = forwardRef<
717
769
  {...containerProps}
718
770
  >
719
771
  <ChartComponent data={chartData} margin={margin}>
720
- {/* Render invisible axes for coordinate system, but hide labels */}
721
- {showAxes && (
722
- <ChartAxes
723
- formatDate={formatDateFn}
724
- formatNumber={formatNumber}
725
- xAxisClassName={cn(xAxisClassName)}
726
- yAxisClassName={cn(yAxisClassName)}
727
- xAxisLabel={xAxisLabel}
728
- yAxisLabel={yAxisLabel}
729
- xMin={xMin}
730
- xMax={xMax}
731
- yMin={yMin}
732
- yMax={yMax}
733
- autoScaleYAxis={effectiveAutoScale}
734
- />
735
- )}
772
+ {axes}
736
773
 
737
774
  {/* Quantile Bands (widest to narrowest) */}
738
775
  {quantileBands?.[0] && (
@@ -759,14 +796,19 @@ const BaseChartWrapperContent = forwardRef<
759
796
  disableHistoricalAnimation={disableHistoricalAnimation}
760
797
  showLegend={showLegend}
761
798
  forecastLineStyle={forecastLineStyle}
799
+ connectHistoryNulls={connectHistoryNulls}
800
+ connectForecastNulls={connectForecastNulls}
801
+ historyOnTop={historyOnTop}
802
+ showEndDots={showEndDots}
762
803
  />
763
804
 
764
805
  {showTooltip && (
765
806
  <div>
766
- <ChartTooltip
807
+ <ChartPlacedTooltip
767
808
  cursor={false}
768
809
  offset={TOOLTIP_OFFSET}
769
810
  allowEscapeViewBox={{ x: false, y: false }}
811
+ wrapperStyle={tooltipWrapperStyle()}
770
812
  content={renderTooltipContent}
771
813
  />
772
814
  </div>
@@ -0,0 +1,60 @@
1
+ import { render } from '@testing-library/react';
2
+
3
+ import { formatNumber as compact } from '../tools/formatters';
4
+ import { ChartAxes } from './ChartAxes';
5
+
6
+ // Recharts' axes draw no tick text in jsdom, so this reads the formatter
7
+ // ChartAxes hands its YAxis.
8
+ const yAxisProps: Array<{ tickFormatter?: (v: number) => string }> = [];
9
+ jest.mock('recharts', () => ({
10
+ ...jest.requireActual('recharts'),
11
+ XAxis: () => null,
12
+ YAxis: (props: { tickFormatter?: (v: number) => string }) => {
13
+ yAxisProps.push(props);
14
+ return null;
15
+ },
16
+ }));
17
+
18
+ const formatDate = (v: string) => v;
19
+
20
+ describe('ChartAxes y-axis numbers', () => {
21
+ beforeEach(() => {
22
+ yAxisProps.length = 0;
23
+ });
24
+
25
+ it("uses the host's formatNumber", () => {
26
+ const own = (v: number) => `${v.toFixed(2)} u`;
27
+ render(<ChartAxes formatDate={formatDate} formatNumber={own} />);
28
+ expect(yAxisProps.at(-1)?.tickFormatter).toBe(own);
29
+ });
30
+
31
+ it('is compact without one', () => {
32
+ render(<ChartAxes formatDate={formatDate} />);
33
+ expect(yAxisProps.at(-1)?.tickFormatter).toBe(compact);
34
+ });
35
+
36
+ it('formats fixed-range ticks with it too', () => {
37
+ const own = jest.fn((v: number) => `${v} u`);
38
+ render(
39
+ <ChartAxes
40
+ formatDate={formatDate}
41
+ formatNumber={own}
42
+ yMin={0}
43
+ yMax={1}
44
+ autoScaleYAxis={false}
45
+ />,
46
+ );
47
+ expect(own).toHaveBeenCalled();
48
+ });
49
+ });
50
+
51
+ describe('ChartAxes auto-scaled y range', () => {
52
+ it("uses recharts' own fit around the data, not the values scaled", () => {
53
+ yAxisProps.length = 0;
54
+ render(<ChartAxes formatDate={formatDate} autoScaleYAxis />);
55
+ expect((yAxisProps.at(-1) as { domain?: unknown })?.domain).toEqual([
56
+ 'auto',
57
+ 'auto',
58
+ ]);
59
+ });
60
+ });
@@ -1,9 +1,9 @@
1
- import { useMemo, useRef } from 'react';
1
+ import { type ComponentProps, useMemo, useRef } from 'react';
2
2
 
3
3
  import { Label, XAxis, YAxis } from 'recharts';
4
4
 
5
5
  import {
6
- formatNumber,
6
+ formatNumber as defaultFormatNumber,
7
7
  formatYAxisNumber,
8
8
  generateRoundedYTicks,
9
9
  } from '../tools/formatters';
@@ -20,6 +20,13 @@ interface ChartAxesProps {
20
20
  yMin?: number;
21
21
  yMax?: number;
22
22
  autoScaleYAxis?: boolean;
23
+ /**
24
+ * Draw no axes. A hidden x-axis is kept, so the tooltip still names the
25
+ * row's date. The y-axis keeps fixed `yMin`/`yMax` (with `autoScaleYAxis`
26
+ * off) as its range, widened if the data goes past it; otherwise it is
27
+ * recharts' default, as without axes.
28
+ */
29
+ hide?: boolean;
23
30
  }
24
31
 
25
32
  export function ChartAxes({
@@ -28,18 +35,21 @@ export function ChartAxes({
28
35
  xAxisLabel,
29
36
  yAxisLabel,
30
37
  formatDate,
31
- // formatNumber = formatYAxisNumber,
38
+ // The host's number format for the y-axis ticks; uilib's compact one
39
+ // (K/M/B, whole numbers below 1000) without it.
40
+ formatNumber = defaultFormatNumber,
32
41
  xMin,
33
42
  xMax,
34
43
  yMin,
35
44
  yMax,
36
45
  autoScaleYAxis = false,
46
+ hide = false,
37
47
  }: ChartAxesProps) {
38
48
  const tickColor = 'var(--muted-foreground)';
39
49
 
40
50
  // Generate rounded ticks to avoid duplicates when we have explicit domain
41
51
  const yTicks = useMemo(() => {
42
- if (yMin !== undefined && yMax !== undefined && !autoScaleYAxis) {
52
+ if (!hide && yMin !== undefined && yMax !== undefined && !autoScaleYAxis) {
43
53
  const ticks = generateRoundedYTicks(yMin, yMax);
44
54
  const formatter = formatNumber || formatYAxisNumber;
45
55
 
@@ -68,35 +78,16 @@ export function ChartAxes({
68
78
  return Array.from(ticksByFormatted.values()).sort((a, b) => a - b);
69
79
  }
70
80
  return undefined;
71
- }, [yMin, yMax, autoScaleYAxis, formatNumber]);
81
+ }, [hide, yMin, yMax, autoScaleYAxis, formatNumber]);
72
82
 
73
83
  // Determine Y-axis domain
74
- let yDomain:
75
- | [
76
- (
77
- | number
78
- | string
79
- | 'auto'
80
- | 'dataMin'
81
- | 'dataMax'
82
- | ((dataMin: number) => number)
83
- ),
84
- (
85
- | number
86
- | string
87
- | 'auto'
88
- | 'dataMin'
89
- | 'dataMax'
90
- | ((dataMax: number) => number)
91
- ),
92
- ]
93
- | undefined;
84
+ let yDomain: ComponentProps<typeof YAxis>['domain'];
94
85
 
95
86
  if (autoScaleYAxis) {
96
- yDomain = [
97
- (dataMin: number) => dataMin * 0.95,
98
- (dataMax: number) => dataMax * 1.05,
99
- ];
87
+ // recharts' own fit: nice round ticks just around the data, so a series
88
+ // moving 1000–1010 fills the chart (scaling the values by 0.95/1.05 left
89
+ // it flat) and a negative one is padded too.
90
+ yDomain = ['auto', 'auto'];
100
91
  } else if (yMin !== undefined && yMax !== undefined) {
101
92
  yDomain = [yMin, yMax];
102
93
  }
@@ -106,6 +97,7 @@ export function ChartAxes({
106
97
  <XAxis
107
98
  className={xAxisClassName}
108
99
  dataKey="date"
100
+ hide={hide}
109
101
  tickLine={false}
110
102
  axisLine={false}
111
103
  tickMargin={8}
@@ -119,22 +111,27 @@ export function ChartAxes({
119
111
  <Label value={xAxisLabel} position="insideBottom" offset={-5} />
120
112
  )}
121
113
  </XAxis>
122
- <YAxis
123
- className={yAxisClassName}
124
- tickLine={false}
125
- axisLine={false}
126
- tickMargin={8}
127
- minTickGap={32}
128
- tick={{ fill: tickColor }}
129
- tickFormatter={formatNumber}
130
- {...(yDomain && { domain: yDomain })}
131
- {...(yTicks && { ticks: yTicks })}
132
- allowDataOverflow={!autoScaleYAxis}
133
- >
134
- {yAxisLabel && (
135
- <Label value={yAxisLabel} angle={-90} position="insideLeft" />
136
- )}
137
- </YAxis>
114
+ {hide && !autoScaleYAxis && yMin !== undefined && yMax !== undefined && (
115
+ <YAxis hide domain={[yMin, yMax]} />
116
+ )}
117
+ {!hide && (
118
+ <YAxis
119
+ className={yAxisClassName}
120
+ tickLine={false}
121
+ axisLine={false}
122
+ tickMargin={8}
123
+ minTickGap={32}
124
+ tick={{ fill: tickColor }}
125
+ tickFormatter={formatNumber}
126
+ {...(yDomain && { domain: yDomain })}
127
+ {...(yTicks && { ticks: yTicks })}
128
+ allowDataOverflow={!autoScaleYAxis}
129
+ >
130
+ {yAxisLabel && (
131
+ <Label value={yAxisLabel} angle={-90} position="insideLeft" />
132
+ )}
133
+ </YAxis>
134
+ )}
138
135
  </>
139
136
  );
140
137
  }
@@ -0,0 +1,160 @@
1
+ import { act, fireEvent, render, waitFor } from '@testing-library/react';
2
+ import { Line, LineChart } from 'recharts';
3
+
4
+ import {
5
+ ChartPlacedTooltip,
6
+ NARROW_CHART_PX,
7
+ NARROW_TOOLTIP_GAP_PX,
8
+ isTooltipUnder,
9
+ opensTooltipUnder,
10
+ } from './ChartPlacedTooltip';
11
+
12
+ // jsdom lays nothing out; recharts reads the wrapper's box to place the
13
+ // pointer, so give every element the chart's size.
14
+ const H = 100;
15
+ let width = 300;
16
+ const box = () =>
17
+ ({
18
+ x: 0,
19
+ y: 0,
20
+ top: 0,
21
+ left: 0,
22
+ right: width,
23
+ bottom: H,
24
+ width,
25
+ height: H,
26
+ toJSON() {},
27
+ }) as DOMRect;
28
+
29
+ beforeAll(() => {
30
+ for (const [prop, get] of [
31
+ ['clientWidth', () => width],
32
+ ['offsetWidth', () => width],
33
+ ['clientHeight', () => H],
34
+ ['offsetHeight', () => H],
35
+ ] as const) {
36
+ Object.defineProperty(HTMLElement.prototype, prop, {
37
+ configurable: true,
38
+ get,
39
+ });
40
+ }
41
+ HTMLElement.prototype.getBoundingClientRect = box;
42
+ });
43
+
44
+ const data = [
45
+ { date: '2026-01', v: 1 },
46
+ { date: '2026-02', v: 2 },
47
+ { date: '2026-03', v: 3 },
48
+ ];
49
+
50
+ // recharts' default margin is 5 on every side; the tooltip starts under the
51
+ // x-axis, so it leaves the bottom one out.
52
+ const MARGIN = 5;
53
+
54
+ function renderChart(
55
+ w: number,
56
+ tooltip: Partial<Parameters<typeof ChartPlacedTooltip>[0]> = {},
57
+ margin?: { top: number; right: number; bottom: number; left: number },
58
+ ) {
59
+ width = w;
60
+ return render(
61
+ <LineChart width={w} height={H} data={data} margin={margin}>
62
+ <Line dataKey="v" isAnimationActive={false} />
63
+ <ChartPlacedTooltip
64
+ content={() => <div className="tip">tip</div>}
65
+ {...tooltip}
66
+ />
67
+ </LineChart>,
68
+ );
69
+ }
70
+
71
+ // The tooltip's vertical translate, once the hover has placed it.
72
+ async function hoverAndReadY(container: HTMLElement, w: number) {
73
+ const chart = container.querySelector('.recharts-wrapper');
74
+ expect(chart).toBeTruthy();
75
+ await act(async () => {
76
+ fireEvent.mouseMove(chart!, { clientX: w - 20, clientY: H / 2 });
77
+ });
78
+ const wrapper = () =>
79
+ container.querySelector<HTMLElement>('.recharts-tooltip-wrapper');
80
+ await waitFor(() => expect(wrapper()?.style.visibility).toBe('visible'));
81
+ const m = /translate\(([-\d.]+)px,\s*([-\d.]+)px\)/.exec(
82
+ wrapper()!.style.transform,
83
+ );
84
+ expect(m).toBeTruthy();
85
+ return { y: Number(m![2]), transition: wrapper()!.style.transition };
86
+ }
87
+
88
+ describe('ChartPlacedTooltip', () => {
89
+ it('knows which widths are narrow', () => {
90
+ expect(opensTooltipUnder(undefined)).toBe(false);
91
+ expect(opensTooltipUnder(0)).toBe(false);
92
+ expect(opensTooltipUnder(NARROW_CHART_PX - 1)).toBe(true);
93
+ expect(opensTooltipUnder(NARROW_CHART_PX)).toBe(false);
94
+ });
95
+
96
+ it('opens under a narrow chart, without sliding there', async () => {
97
+ const { container } = renderChart(300);
98
+ const { y, transition } = await hoverAndReadY(container, 300);
99
+ expect(y).toBe(H - MARGIN + NARROW_TOOLTIP_GAP_PX);
100
+ expect(transition).toBe('none');
101
+ const wrapper = container.querySelector<HTMLElement>(
102
+ '.recharts-tooltip-wrapper',
103
+ )!;
104
+ expect(isTooltipUnder(wrapper)).toBe(true);
105
+ expect(wrapper.style.display).toBe('');
106
+ });
107
+
108
+ it('starts right under the x-axis labels, not under the bottom margin', async () => {
109
+ const { container } = renderChart(
110
+ 300,
111
+ {},
112
+ {
113
+ top: 20,
114
+ right: 5,
115
+ bottom: 20,
116
+ left: 5,
117
+ },
118
+ );
119
+ const { y } = await hoverAndReadY(container, 300);
120
+ expect(y).toBe(H - 20 + NARROW_TOOLTIP_GAP_PX);
121
+ });
122
+
123
+ it('takes no room under a narrow chart while nothing is hovered', async () => {
124
+ const { container } = renderChart(300);
125
+ await hoverAndReadY(container, 300);
126
+ const chart = container.querySelector('.recharts-wrapper')!;
127
+ await act(async () => {
128
+ fireEvent.mouseLeave(chart);
129
+ });
130
+ await waitFor(() =>
131
+ expect(
132
+ container.querySelector<HTMLElement>('.recharts-tooltip-wrapper')?.style
133
+ .display,
134
+ ).toBe('none'),
135
+ );
136
+ });
137
+
138
+ it('stays over a wide chart', async () => {
139
+ const { container } = renderChart(640);
140
+ const { y } = await hoverAndReadY(container, 640);
141
+ expect(y).toBeLessThan(H);
142
+ expect(
143
+ isTooltipUnder(
144
+ container.querySelector<HTMLElement>('.recharts-tooltip-wrapper')!,
145
+ ),
146
+ ).toBe(false);
147
+ });
148
+
149
+ it("lets the caller's position win", async () => {
150
+ const { container } = renderChart(300, { position: { y: 7 } });
151
+ const { y } = await hoverAndReadY(container, 300);
152
+ expect(y).toBe(7);
153
+ });
154
+
155
+ it('keeps the under-chart y when the caller sets only x', async () => {
156
+ const { container } = renderChart(300, { position: { x: 0 } });
157
+ const { y } = await hoverAndReadY(container, 300);
158
+ expect(y).toBe(H - MARGIN + NARROW_TOOLTIP_GAP_PX);
159
+ });
160
+ });
@@ -0,0 +1,93 @@
1
+ import { type CSSProperties, type ComponentProps, useMemo } from 'react';
2
+
3
+ import {
4
+ Tooltip,
5
+ useChartHeight,
6
+ useChartWidth,
7
+ useIsTooltipActive,
8
+ useMargin,
9
+ } from 'recharts';
10
+
11
+ /** Charts narrower than this open their tooltip under the chart, not over it. */
12
+ export const NARROW_CHART_PX = 500;
13
+
14
+ /** Gap between a narrow chart's x-axis labels and its tooltip. */
15
+ export const NARROW_TOOLTIP_GAP_PX = 4;
16
+
17
+ /**
18
+ * Set to 1 on the tooltip wrapper's style while it sits under the chart, so
19
+ * code that moves the wrapper itself (BaseChartWrapper) leaves it alone
20
+ * instead of deciding again.
21
+ */
22
+ export const TOOLTIP_UNDER_VAR = '--chart-tooltip-under';
23
+
24
+ /** Whether a chart this wide opens its tooltip under itself. */
25
+ export function opensTooltipUnder(chartWidth: number | undefined): boolean {
26
+ return chartWidth != null && chartWidth > 0 && chartWidth < NARROW_CHART_PX;
27
+ }
28
+
29
+ /** Whether ChartPlacedTooltip put this tooltip wrapper under its chart. */
30
+ export function isTooltipUnder(wrapper: HTMLElement): boolean {
31
+ return wrapper.style.getPropertyValue(TOOLTIP_UNDER_VAR).trim() === '1';
32
+ }
33
+
34
+ type ChartPlacedTooltipProps = ComponentProps<typeof Tooltip>;
35
+
36
+ /**
37
+ * A recharts Tooltip that, on a chart narrower than {@link NARROW_CHART_PX},
38
+ * sits under the chart instead of over the lines, starting right under the
39
+ * x-axis labels (the chart's bottom margin is left out), so a small chart stays
40
+ * readable while it is hovered. It may then cover what follows the chart, be
41
+ * clipped by a parent that hides overflow, or run past the page edge; that is
42
+ * accepted. Under a chart it does not slide (no transition, whatever
43
+ * `wrapperStyle` says), and while no point is hovered it takes no room
44
+ * (`display: none`), so it never grows a scrolling parent. A caller's
45
+ * `position.x` and `position.y` each win, as does `isAnimationActive`. With
46
+ * `portal`, recharts places nothing, so neither does this.
47
+ */
48
+ export function ChartPlacedTooltip(props: ChartPlacedTooltipProps) {
49
+ const width = useChartWidth();
50
+ const height = useChartHeight();
51
+ const hovered = useIsTooltipActive();
52
+ const bottomMargin = useMargin()?.bottom ?? 0;
53
+ const open = props.active ?? hovered;
54
+
55
+ const under =
56
+ props.portal == null &&
57
+ opensTooltipUnder(width) &&
58
+ height != null &&
59
+ height > 0;
60
+ const callerPosition = props.position;
61
+ const y = under
62
+ ? (callerPosition?.y ??
63
+ height - Math.max(0, bottomMargin) + NARROW_TOOLTIP_GAP_PX)
64
+ : undefined;
65
+ const position = useMemo(
66
+ () => (y == null ? undefined : { ...callerPosition, y }),
67
+ [callerPosition, y],
68
+ );
69
+ const callerWrapperStyle = props.wrapperStyle;
70
+ const wrapperStyle = useMemo(
71
+ () =>
72
+ under
73
+ ? ({
74
+ ...callerWrapperStyle,
75
+ [TOOLTIP_UNDER_VAR]: '1',
76
+ transition: 'none',
77
+ ...(open ? {} : { display: 'none' }),
78
+ } as CSSProperties)
79
+ : undefined,
80
+ [under, open, callerWrapperStyle],
81
+ );
82
+
83
+ if (!under) return <Tooltip {...props} />;
84
+
85
+ return (
86
+ <Tooltip
87
+ {...props}
88
+ position={position}
89
+ isAnimationActive={props.isAnimationActive ?? false}
90
+ wrapperStyle={wrapperStyle}
91
+ />
92
+ );
93
+ }