@sybilion/uilib 1.8.2 → 1.8.4

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 (76) hide show
  1. package/dist/esm/src/components/ui/BarChart/BarChart.js +39 -7
  2. package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +71 -6
  3. package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.styl.js +2 -2
  4. package/dist/esm/src/components/ui/Chart/components/ChartAxes.js +11 -3
  5. package/dist/esm/src/components/ui/Chart/components/ChartTooltipContent.js +6 -3
  6. package/dist/esm/src/components/ui/Chart/components/QuantileBands.js +1 -1
  7. package/dist/esm/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.js +20 -0
  8. package/dist/esm/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.js +7 -0
  9. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.js +2 -2
  10. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.styl.js +2 -2
  11. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +49 -13
  12. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.js +45 -11
  13. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.js +15 -8
  14. package/dist/esm/src/components/ui/TimeRangeControls/TimeRangeControls.js +1 -1
  15. package/dist/esm/src/components/ui/Toggle/Toggle.styl.js +2 -2
  16. package/dist/esm/src/components/ui/ToggleGroup/ToggleGroup.js +1 -1
  17. package/dist/esm/src/components/ui/ToggleGroup/ToggleGroup.styl.js +1 -1
  18. package/dist/esm/types/src/components/ui/BarChart/BarChart.types.d.ts +22 -0
  19. package/dist/esm/types/src/components/ui/Chart/chartForecastVisualization.types.d.ts +5 -0
  20. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +22 -5
  21. package/dist/esm/types/src/components/ui/Chart/components/ChartAxes.d.ts +8 -1
  22. package/dist/esm/types/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.d.ts +22 -0
  23. package/dist/esm/types/src/components/ui/Chart/components/SeriesLegend/index.d.ts +1 -0
  24. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.d.ts +1 -1
  25. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.types.d.ts +7 -0
  26. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +10 -1
  27. package/dist/esm/types/src/components/ui/ChartAreaInteractive/chartHistories.d.ts +5 -0
  28. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.d.ts +10 -3
  29. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.d.ts +1 -1
  30. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.types.d.ts +9 -0
  31. package/dist/esm/types/src/components/ui/TimeRangeControls/TimeRangeControls.d.ts +7 -1
  32. package/dist/esm/types/src/components/ui/Toggle/Toggle.types.d.ts +1 -1
  33. package/dist/esm/types/src/components/ui/ToggleGroup/ToggleGroup.helpers.d.ts +2 -2
  34. package/dist/esm/types/src/components/ui/ToggleGroup/ToggleGroup.types.d.ts +3 -3
  35. package/dist/esm/types/tests/viewChartGaps.test.d.ts +1 -0
  36. package/package.json +1 -1
  37. package/src/components/ui/BarChart/AGENT.md +4 -0
  38. package/src/components/ui/BarChart/BarChart.styl.d.ts +1 -1
  39. package/src/components/ui/BarChart/BarChart.tsx +107 -21
  40. package/src/components/ui/BarChart/BarChart.types.ts +22 -0
  41. package/src/components/ui/Chart/AGENT.md +3 -0
  42. package/src/components/ui/Chart/chartForecastVisualization.types.ts +5 -0
  43. package/src/components/ui/Chart/components/BaseChartWrapper.styl +5 -0
  44. package/src/components/ui/Chart/components/BaseChartWrapper.styl.d.ts +1 -0
  45. package/src/components/ui/Chart/components/BaseChartWrapper.tsx +124 -5
  46. package/src/components/ui/Chart/components/ChartAxes.tsx +29 -5
  47. package/src/components/ui/Chart/components/ChartTooltipContent.tsx +6 -3
  48. package/src/components/ui/Chart/components/QuantileBands.tsx +1 -0
  49. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl +34 -0
  50. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.d.ts +12 -0
  51. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.tsx +70 -0
  52. package/src/components/ui/Chart/components/SeriesLegend/index.ts +1 -0
  53. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.styl +5 -0
  54. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.styl.d.ts +1 -0
  55. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.tsx +7 -1
  56. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.types.ts +7 -0
  57. package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +110 -40
  58. package/src/components/ui/ChartAreaInteractive/chartHistories.ts +5 -0
  59. package/src/components/ui/StackedAreaChart/AGENT.md +1 -0
  60. package/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.ts +54 -13
  61. package/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.tsx +1 -1
  62. package/src/components/ui/StackedAreaChart/StackedAreaChart.tsx +36 -12
  63. package/src/components/ui/StackedAreaChart/StackedAreaChart.types.ts +9 -0
  64. package/src/components/ui/TimeRangeControls/AGENT.md +1 -1
  65. package/src/components/ui/TimeRangeControls/TimeRangeControls.test.tsx +21 -0
  66. package/src/components/ui/TimeRangeControls/TimeRangeControls.tsx +13 -2
  67. package/src/components/ui/Toggle/Toggle.styl +24 -0
  68. package/src/components/ui/Toggle/Toggle.styl.d.ts +1 -0
  69. package/src/components/ui/Toggle/Toggle.types.ts +1 -1
  70. package/src/components/ui/ToggleGroup/AGENT.md +1 -0
  71. package/src/components/ui/ToggleGroup/ToggleGroup.helpers.ts +2 -2
  72. package/src/components/ui/ToggleGroup/ToggleGroup.styl +8 -0
  73. package/src/components/ui/ToggleGroup/ToggleGroup.tsx +1 -0
  74. package/src/components/ui/ToggleGroup/ToggleGroup.types.ts +3 -3
  75. package/src/docs/pages/ChartAreaInteractivePage.tsx +34 -0
  76. package/src/docs/pages/TimeRangeControlsPage.tsx +9 -0
@@ -0,0 +1,70 @@
1
+ import cn from 'classnames';
2
+ import type { ReactNode } from 'react';
3
+
4
+ import ChartS from '../../Chart.styl';
5
+ import S from './SeriesLegend.styl';
6
+
7
+ export type SeriesLegendItem = {
8
+ /** The series' data key; the legend hands it back on a click. */
9
+ dataKey: string;
10
+ label: ReactNode;
11
+ color: string;
12
+ /** Draw the swatch as a dashed line (a forecast line). */
13
+ dashed?: boolean;
14
+ /** Draw the swatch as a filled square (a bar or an area) instead of a line. */
15
+ square?: boolean;
16
+ };
17
+
18
+ /**
19
+ * A plain legend: one entry per series, in the order given, each a button
20
+ * that hides or shows its series. A hidden series' entry is dimmed.
21
+ */
22
+ export function SeriesLegend({
23
+ items,
24
+ hiddenSeries,
25
+ onToggle,
26
+ className,
27
+ }: {
28
+ items: SeriesLegendItem[];
29
+ hiddenSeries?: ReadonlySet<string>;
30
+ /** Without it the entries are text, not buttons. */
31
+ onToggle?: (dataKey: string) => void;
32
+ className?: string;
33
+ }) {
34
+ if (items.length === 0) return null;
35
+ return (
36
+ <div className={cn(ChartS.legendContainer, S.root, className)}>
37
+ {items.map(item => {
38
+ const dimmed = hiddenSeries?.has(item.dataKey) ?? false;
39
+ const content = (
40
+ <>
41
+ <span
42
+ className={cn(
43
+ S.swatch,
44
+ item.square ? S.square : item.dashed && S.dashed,
45
+ )}
46
+ style={{ color: item.color }}
47
+ aria-hidden
48
+ />
49
+ {item.label}
50
+ </>
51
+ );
52
+ return onToggle ? (
53
+ <button
54
+ key={item.dataKey}
55
+ type="button"
56
+ className={cn(ChartS.legendItem, S.button, dimmed && S.dimmed)}
57
+ aria-pressed={!dimmed}
58
+ onClick={() => onToggle(item.dataKey)}
59
+ >
60
+ {content}
61
+ </button>
62
+ ) : (
63
+ <span key={item.dataKey} className={ChartS.legendItem}>
64
+ {content}
65
+ </span>
66
+ );
67
+ })}
68
+ </div>
69
+ );
70
+ }
@@ -0,0 +1 @@
1
+ export { SeriesLegend, type SeriesLegendItem } from './SeriesLegend';
@@ -34,6 +34,11 @@
34
34
  gap var(--p-2)
35
35
  margin-bottom 1rem
36
36
 
37
+ // Takes the row's free space, so the controls after it sit at the end.
38
+ .chartHeaderTitle
39
+ flex 1 1 auto
40
+ min-width 0
41
+
37
42
  .chartContainerWrapper
38
43
  position relative
39
44
 
@@ -4,6 +4,7 @@ interface CssExports {
4
4
  'chartContainer': string;
5
5
  'chartContainerWrapper': string;
6
6
  'chartHeaderContainer': string;
7
+ 'chartHeaderTitle': string;
7
8
  'fadeIn': string;
8
9
  'loading': string;
9
10
  'loadingSpinner': string;
@@ -74,6 +74,8 @@ export function ChartAreaInteractive({
74
74
  onUpperThresholdChange,
75
75
  discreteThresholdValues,
76
76
  headerActions,
77
+ headerTitle,
78
+ timeRangeVariant,
77
79
  excludeLegendIds,
78
80
  loadingAnalyses,
79
81
  onLegendClick,
@@ -296,13 +298,17 @@ export function ChartAreaInteractive({
296
298
  className={cn(className, loading && S.loading)}
297
299
  disabled={loading}
298
300
  >
299
- {(!disableTimeRangeSelector || headerActions) && (
301
+ {(!disableTimeRangeSelector || headerActions || headerTitle) && (
300
302
  <div className={S.chartHeaderContainer}>
303
+ {headerTitle != null && (
304
+ <div className={S.chartHeaderTitle}>{headerTitle}</div>
305
+ )}
301
306
  {!disableTimeRangeSelector && (
302
307
  <TimeRangeControls
303
308
  timeRange={timeRange}
304
309
  onTimeRangeChange={onTimeRangeChange}
305
310
  loading={loading}
311
+ variant={timeRangeVariant}
306
312
  />
307
313
  )}
308
314
 
@@ -48,6 +48,13 @@ export interface ChartAreaInteractiveProps extends BaseChartWrapperProps {
48
48
  onUpperThresholdChange?: (value: number) => void;
49
49
  discreteThresholdValues?: { lower: number[]; upper: number[] };
50
50
  headerActions?: React.ReactNode;
51
+ /**
52
+ * Shown at the start of the header row, before the time range control,
53
+ * which then sits at the row's end (e.g. a one-line summary of the chart).
54
+ */
55
+ headerTitle?: React.ReactNode;
56
+ /** The time range control's look (`TimeRangeControls` `variant`). */
57
+ timeRangeVariant?: 'default' | 'segmented';
51
58
  loadingAnalyses?: Set<string>;
52
59
  onLegendClick?: (data: LegendPayload) => undefined | boolean;
53
60
  disableTimeRangeSelector?: boolean;
@@ -30,6 +30,11 @@ export type ForecastItemData = {
30
30
  * histories, a forecast joins one only when this names it.
31
31
  */
32
32
  continues?: string | number;
33
+ /**
34
+ * Draw this line across rows it has no value for. Without it the chart's
35
+ * `connectForecastNulls` decides.
36
+ */
37
+ connectNulls?: boolean;
33
38
  };
34
39
 
35
40
  export type Dot = {
@@ -63,7 +68,13 @@ export const getForecastQuantileBandColor = (index: number) =>
63
68
  ];
64
69
 
65
70
  /** A history line as drawn: data key, label and colour with defaults applied. */
66
- export type HistoryLine = { dataKey: string; name: string; color: string };
71
+ export type HistoryLine = {
72
+ dataKey: string;
73
+ name: string;
74
+ color: string;
75
+ /** The line's own `connectNulls`, when it sets one. */
76
+ connectNulls?: boolean;
77
+ };
67
78
 
68
79
  /** Default colour of the history at `index`: the forecast palette from its far end. */
69
80
  export function getHistoryColor(index: number): string {
@@ -79,6 +90,7 @@ export function resolveHistoryLines(
79
90
  dataKey: historySeriesKey(h.id),
80
91
  name: h.name || String(h.id),
81
92
  color: h.color ?? getHistoryColor(index),
93
+ connectNulls: h.connectNulls,
82
94
  }));
83
95
  }
84
96
 
@@ -110,6 +122,7 @@ export const ChartLines = memo(
110
122
  connectForecastNulls = false,
111
123
  historyOnTop = false,
112
124
  showEndDots = true,
125
+ dotLonePoints = false,
113
126
  }: {
114
127
  chartData: ChartDataPoint[];
115
128
  forecastData?: ForecastItemData[];
@@ -134,6 +147,8 @@ export const ChartLines = memo(
134
147
  historyOnTop?: boolean;
135
148
  /** Mark each line's last point with a dot (default: on). */
136
149
  showEndDots?: boolean;
150
+ /** Dot a point a gapped line leaves alone (default: off). */
151
+ dotLonePoints?: boolean;
137
152
  }) => {
138
153
  const dotStroke = isDarkTheme ? '#000000' : '#FFFFFF';
139
154
 
@@ -199,31 +214,61 @@ export const ChartLines = memo(
199
214
  return indices;
200
215
  }, [chartData, forecastData]);
201
216
 
202
- // Helper to render dot at last data point
217
+ // How many values each line has, for `dotLonePoints` on a line drawn
218
+ // across gaps: such a line leaves a point alone only when it is its only
219
+ // value.
220
+ const valueCounts = useMemo(() => {
221
+ if (!dotLonePoints) return undefined;
222
+ const counts: Record<string, number> = {};
223
+ for (const row of chartData) {
224
+ for (const [key, value] of Object.entries(row)) {
225
+ if (typeof value === 'number') counts[key] = (counts[key] ?? 0) + 1;
226
+ }
227
+ }
228
+ return counts;
229
+ }, [chartData, dotLonePoints]);
230
+
231
+ // A dot on the line's last point (with `showEndDots`), and (with
232
+ // `dotLonePoints`) on any point the line leaves alone, which would
233
+ // otherwise not show: no value in the rows on either side, or, for a line
234
+ // drawn across gaps, no other value at all.
203
235
  const renderDot = (
204
236
  props: any,
205
237
  lastIndex: number,
206
238
  dataKey: string,
207
239
  color: string,
240
+ connected: boolean,
208
241
  ) => {
242
+ const i = props.index;
209
243
  if (
210
- lastIndex >= 0 &&
211
- props.index === lastIndex &&
212
- chartData[props.index]?.[dataKey] != null &&
213
- props.cy != null &&
214
- props.cx != null
244
+ typeof i !== 'number' ||
245
+ chartData[i]?.[dataKey] == null ||
246
+ props.cy == null ||
247
+ props.cx == null
215
248
  ) {
216
- return <circle cx={props.cx} cy={props.cy} r={3} fill={color} />;
249
+ return null;
250
+ }
251
+ const isEnd = showEndDots && lastIndex >= 0 && i === lastIndex;
252
+ const isAlone =
253
+ dotLonePoints &&
254
+ (connected
255
+ ? valueCounts?.[dataKey] === 1
256
+ : chartData[i - 1]?.[dataKey] == null &&
257
+ chartData[i + 1]?.[dataKey] == null);
258
+ if (isEnd || isAlone) {
259
+ return (
260
+ <circle
261
+ key={`dot-${dataKey}-${i}`}
262
+ cx={props.cx}
263
+ cy={props.cy}
264
+ r={3}
265
+ fill={color}
266
+ />
267
+ );
217
268
  }
218
269
  return null;
219
270
  };
220
271
 
221
- const renderHistoryDot = (props: any, dataKey: string, color: string) =>
222
- renderDot(props, lastHistoryIndices[dataKey] ?? -1, dataKey, color);
223
-
224
- const renderForecastDot = (props: any, id: number, color: string) =>
225
- renderDot(props, lastForecastIndices[id] ?? -1, `forecast_${id}`, color);
226
-
227
272
  const animationActive = Boolean(shouldAnimate) && !disableAnimation;
228
273
  const historicalAnimationActive =
229
274
  animationActive && !disableHistoricalAnimation;
@@ -236,30 +281,45 @@ export const ChartLines = memo(
236
281
  // hiding, showing and added forecasts, and leaves the tooltip's order.
237
282
  const historyZIndex = historyOnTop ? DefaultZIndexes.line + 1 : undefined;
238
283
 
239
- const historyElements = historyLines.map(({ dataKey, name, color }) => (
240
- <Line
241
- key={dataKey}
242
- zIndex={historyZIndex}
243
- type="monotone"
244
- dataKey={dataKey}
245
- stroke={color}
246
- strokeWidth={1}
247
- dot={
248
- showEndDots ? props => renderHistoryDot(props, dataKey, color) : false
249
- }
250
- activeDot={{ ...activeDotHistorical, fill: color }}
251
- name={name}
252
- legendType={showLegend === false ? 'none' : undefined}
253
- strokeDasharray="0"
254
- connectNulls={connectHistoryNulls}
255
- hide={hiddenSeries?.has(dataKey)}
256
- isAnimationActive={historicalAnimationActive}
257
- animationDuration={animationDuration}
258
- animateNewValues={valueAnimationEnabled}
259
- animationBegin={0}
260
- animationEasing="ease-out"
261
- />
262
- ));
284
+ const historyElements = historyLines.map(
285
+ ({ dataKey, name, color, connectNulls }) => {
286
+ const connected = connectNulls ?? connectHistoryNulls;
287
+ return (
288
+ <Line
289
+ key={dataKey}
290
+ zIndex={historyZIndex}
291
+ type="monotone"
292
+ dataKey={dataKey}
293
+ stroke={color}
294
+ strokeWidth={1}
295
+ // A line with no dot to draw skips the per-point call.
296
+ dot={
297
+ showEndDots || dotLonePoints
298
+ ? props =>
299
+ renderDot(
300
+ props,
301
+ lastHistoryIndices[dataKey] ?? -1,
302
+ dataKey,
303
+ color,
304
+ connected,
305
+ )
306
+ : false
307
+ }
308
+ activeDot={{ ...activeDotHistorical, fill: color }}
309
+ name={name}
310
+ legendType={showLegend === false ? 'none' : undefined}
311
+ strokeDasharray="0"
312
+ connectNulls={connected}
313
+ hide={hiddenSeries?.has(dataKey)}
314
+ isAnimationActive={historicalAnimationActive}
315
+ animationDuration={animationDuration}
316
+ animateNewValues={valueAnimationEnabled}
317
+ animationBegin={0}
318
+ animationEasing="ease-out"
319
+ />
320
+ );
321
+ },
322
+ );
263
323
 
264
324
  const forecastElements = forecastData?.map(
265
325
  (data: ForecastItemData, index: number) => {
@@ -269,6 +329,7 @@ export const ChartLines = memo(
269
329
  color = FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length],
270
330
  } = data;
271
331
  const dataKey = `forecast_${id}`;
332
+ const connected = data.connectNulls ?? connectForecastNulls;
272
333
 
273
334
  return (
274
335
  <Line
@@ -279,12 +340,21 @@ export const ChartLines = memo(
279
340
  strokeWidth={1}
280
341
  strokeDasharray={forecastLineStyle === 'dashed' ? '4 2' : '0'}
281
342
  dot={
282
- showEndDots ? props => renderForecastDot(props, id, color) : false
343
+ showEndDots || dotLonePoints
344
+ ? props =>
345
+ renderDot(
346
+ props,
347
+ lastForecastIndices[id] ?? -1,
348
+ dataKey,
349
+ color,
350
+ connected,
351
+ )
352
+ : false
283
353
  }
284
354
  activeDot={activeDotForecast(color)}
285
355
  name={`${name || `${id}`}`}
286
356
  legendType={showLegend === false ? 'none' : undefined}
287
- connectNulls={connectForecastNulls}
357
+ connectNulls={connected}
288
358
  hide={hiddenSeries?.has(dataKey)}
289
359
  isAnimationActive={forecastAnimationActive}
290
360
  animationDuration={animationDuration}
@@ -23,6 +23,11 @@ export type HistoryItemData = {
23
23
  * colour to both.
24
24
  */
25
25
  color?: string;
26
+ /**
27
+ * Draw this line across rows it has no value for. Without it the chart's
28
+ * `connectHistoryNulls` decides.
29
+ */
30
+ connectNulls?: boolean;
26
31
  };
27
32
 
28
33
  /** Data key of one history line in `chartData` rows. */
@@ -19,6 +19,7 @@ StackedAreaChart shows how a total is built from parts over time: cost layers st
19
19
  - Keep `margin.pct` in the host's state and pass it on every change; the margin layer stays mounted, so typing does not redraw the chart.
20
20
  - Set `yearTicks` for multi-year monthly data so the axis reads one label per year.
21
21
  - Pass `hiddenKeys` and `onToggleKey` when the host must remember which series are hidden.
22
+ - Name the axes with `xAxisLabel` and `yAxisLabel`; pass `tooltipValueFormatter` when the tooltip should read differently from the axis (for example with a unit).
22
23
 
23
24
  ## Don't
24
25
 
@@ -196,31 +196,75 @@ function compareSides(
196
196
  * A value axis from 0 for a top value: at most `maxIntervals` steps of
197
197
  * 1, 2, 2.5 or 5 × 10ⁿ, with a little headroom above the top. Small changes
198
198
  * in the top (a margin being typed) move the axis by one step at most,
199
- * instead of doubling it the way automatic rounding can.
199
+ * instead of doubling it the way automatic rounding can. A `bottom` below 0
200
+ * (a negative layer or line) starts the axis at a step below it, as `min`.
200
201
  */
201
202
  export function valueAxis(
202
203
  top: number,
203
204
  maxIntervals = 5,
204
205
  headroom = 0.05,
205
- ): { max: number; ticks: number[] } {
206
- const target = Number.isFinite(top) && top > 0 ? top * (1 + headroom) : 1;
207
- let exponent = Math.floor(Math.log10(target / maxIntervals));
206
+ bottom = 0,
207
+ ): { min?: number; max: number; ticks: number[] } {
208
+ const low = Number.isFinite(bottom) && bottom < 0 ? bottom * (1 + headroom) : 0;
209
+ const high =
210
+ Number.isFinite(top) && top > 0 ? top * (1 + headroom) : low < 0 ? 0 : 1;
211
+ let exponent = Math.floor(Math.log10((high - low) / maxIntervals));
208
212
  for (;;) {
209
213
  for (const mantissa of [1, 2, 2.5, 5]) {
210
214
  const step = mantissa * 10 ** exponent;
211
- const count = Math.ceil(target / step - 1e-9);
212
- if (count <= maxIntervals) {
215
+ const first = low < 0 ? Math.floor(low / step + 1e-9) * step : 0;
216
+ const count = Math.ceil((high - first) / step - 1e-9);
217
+ // Both ends round out to a step, so a range across 0 gets one more.
218
+ if (count <= maxIntervals + (low < 0 ? 1 : 0)) {
213
219
  const ticks = Array.from({ length: count + 1 }, (_, i) =>
214
- Number((i * step).toPrecision(12)),
220
+ Number((first + i * step).toPrecision(12)),
215
221
  );
216
- return { max: ticks[ticks.length - 1], ticks };
222
+ const max = ticks[ticks.length - 1];
223
+ return low < 0 ? { min: ticks[0], max, ticks } : { max, ticks };
217
224
  }
218
225
  }
219
226
  exponent += 1;
220
227
  }
221
228
  }
222
229
 
223
- /** The highest stacked total (layers plus margin) or line value on any row. */
230
+ /**
231
+ * The lowest point the stack (a negative layer or margin pulls it below 0)
232
+ * or a line reaches; 0 when nothing is negative.
233
+ */
234
+ export function chartBottom(
235
+ rows: readonly StackedAreaChartDatum[],
236
+ layerKeys: readonly string[],
237
+ lineKeys: readonly string[],
238
+ ): number {
239
+ let bottom = 0;
240
+ for (const row of rows) {
241
+ bottom = Math.min(bottom, stackExtent(row, layerKeys)[0]);
242
+ for (const key of lineKeys) bottom = Math.min(bottom, num(row[key]) ?? 0);
243
+ }
244
+ return bottom;
245
+ }
246
+
247
+ /**
248
+ * The lowest and highest running totals up a row's stack (layers, then the
249
+ * margin): recharts draws each layer from the total below it, so a negative
250
+ * layer above a positive one leaves the peak below the final total.
251
+ */
252
+ function stackExtent(
253
+ row: StackedAreaChartDatum,
254
+ layerKeys: readonly string[],
255
+ ): [number, number] {
256
+ let running = 0;
257
+ let low = 0;
258
+ let high = 0;
259
+ for (const key of [...layerKeys, MARGIN_KEY]) {
260
+ running += num(row[key]) ?? 0;
261
+ low = Math.min(low, running);
262
+ high = Math.max(high, running);
263
+ }
264
+ return [low, high];
265
+ }
266
+
267
+ /** The highest point the stack (layers plus margin) or a line reaches. */
224
268
  export function chartTop(
225
269
  rows: readonly StackedAreaChartDatum[],
226
270
  layerKeys: readonly string[],
@@ -228,10 +272,7 @@ export function chartTop(
228
272
  ): number {
229
273
  let top = 0;
230
274
  for (const row of rows) {
231
- top = Math.max(
232
- top,
233
- layersTotal(row, layerKeys) + (num(row[MARGIN_KEY]) ?? 0),
234
- );
275
+ top = Math.max(top, stackExtent(row, layerKeys)[1]);
235
276
  for (const key of lineKeys) top = Math.max(top, num(row[key]) ?? 0);
236
277
  }
237
278
  return top;
@@ -1,8 +1,8 @@
1
1
  import cn from 'classnames';
2
2
  import { CSSProperties } from 'react';
3
3
 
4
- import type { ChartConfig } from '#uilib/components/ui/Chart';
5
4
  import ChartS from '#uilib/components/ui/Chart/Chart.styl';
5
+ import type { ChartConfig } from '#uilib/components/ui/Chart/Chart.types';
6
6
 
7
7
  export type TooltipRow = {
8
8
  dataKey?: unknown;
@@ -1,16 +1,20 @@
1
1
  import cn from 'classnames';
2
2
  import { ReactNode, forwardRef, useMemo } from 'react';
3
3
 
4
- import type { ChartConfig } from '#uilib/components/ui/Chart';
5
- import { ChartContainer, ChartTooltip } from '#uilib/components/ui/Chart';
6
4
  import ChartS from '#uilib/components/ui/Chart/Chart.styl';
5
+ import type { ChartConfig } from '#uilib/components/ui/Chart/Chart.types';
7
6
  import { getChartSeriesColor } from '#uilib/components/ui/Chart/chartSeriesPalette';
7
+ // Straight from the components, not the Chart index, which also loads the
8
+ // canvas chart (lightweight-charts) and its styles.
9
+ import { ChartContainer } from '#uilib/components/ui/Chart/components/ChartContainer';
10
+ import { ChartPlacedTooltip as ChartTooltip } from '#uilib/components/ui/Chart/components/ChartPlacedTooltip';
8
11
  import { useLegendState } from '#uilib/components/ui/Chart/hooks/useLegendState';
9
12
  import {
10
13
  Area,
11
14
  Bar,
12
15
  CartesianGrid,
13
16
  ComposedChart,
17
+ Label,
14
18
  Line,
15
19
  ReferenceArea,
16
20
  XAxis,
@@ -19,6 +23,7 @@ import {
19
23
 
20
24
  import {
21
25
  MARGIN_KEY,
26
+ chartBottom,
22
27
  chartTop,
23
28
  compareRowZones,
24
29
  compareZones,
@@ -59,6 +64,8 @@ const splitKeys = (joined: string) => joined.split(KEY_SEP).slice(1);
59
64
  const ZONE_Z_INDEX = 50;
60
65
 
61
66
  const AXIS_LINE = { stroke: 'var(--border)', strokeWidth: 1 };
67
+ /** Room for an x-axis title under the ticks (recharts' default is 30). */
68
+ const X_AXIS_HEIGHT_WITH_LABEL = 44;
62
69
 
63
70
  const layerColor = (layer: StackedAreaChartLayer, index: number) =>
64
71
  layer.color ?? getChartSeriesColor(index);
@@ -118,8 +125,11 @@ const StackedAreaChart = forwardRef<HTMLDivElement, StackedAreaChartProps>(
118
125
  showTooltip = true,
119
126
  showGrid = true,
120
127
  valueFormatter,
128
+ tooltipValueFormatter = valueFormatter,
121
129
  xTickFormatter,
122
130
  tooltipLabelFormatter,
131
+ xAxisLabel,
132
+ yAxisLabel,
123
133
  height,
124
134
  ...props
125
135
  },
@@ -181,11 +191,15 @@ const StackedAreaChart = forwardRef<HTMLDivElement, StackedAreaChartProps>(
181
191
  const visibleLinesJoined = joinKeys(
182
192
  overlays.filter(o => !hidden.has(o.key)).map(o => o.key),
183
193
  );
184
- const yAxis = useMemo(
185
- () =>
186
- valueAxis(chartTop(rows, visibleKeys, splitKeys(visibleLinesJoined))),
187
- [rows, visibleKeys, visibleLinesJoined],
188
- );
194
+ const yAxis = useMemo(() => {
195
+ const lines = splitKeys(visibleLinesJoined);
196
+ return valueAxis(
197
+ chartTop(rows, visibleKeys, lines),
198
+ undefined,
199
+ undefined,
200
+ chartBottom(rows, visibleKeys, lines),
201
+ );
202
+ }, [rows, visibleKeys, visibleLinesJoined]);
189
203
  const ticks = useMemo(
190
204
  () => (yearTicks ? findYearTicks(data, xKey) : undefined),
191
205
  [yearTicks, data, xKey],
@@ -240,18 +254,28 @@ const StackedAreaChart = forwardRef<HTMLDivElement, StackedAreaChartProps>(
240
254
  minTickGap={ticks ? 8 : 24}
241
255
  tickLine={false}
242
256
  axisLine={AXIS_LINE}
243
- />
257
+ height={xAxisLabel ? X_AXIS_HEIGHT_WITH_LABEL : undefined}
258
+ >
259
+ {xAxisLabel && (
260
+ <Label value={xAxisLabel} position="insideBottom" offset={0} />
261
+ )}
262
+ </XAxis>
244
263
  <YAxis
245
264
  // Our own steps: automatic rounding can double the axis when the
246
265
  // margin nudges the top past a round number.
247
- domain={[0, yAxis.max]}
266
+ domain={[yAxis.min ?? 0, yAxis.max]}
248
267
  ticks={yAxis.ticks}
249
268
  allowDataOverflow
250
269
  tickFormatter={valueFormatter}
251
- width={56}
270
+ // Room for the rotated title beside the ticks.
271
+ width={yAxisLabel ? 72 : 56}
252
272
  tickLine={false}
253
273
  axisLine={AXIS_LINE}
254
- />
274
+ >
275
+ {yAxisLabel && (
276
+ <Label value={yAxisLabel} angle={-90} position="insideLeft" />
277
+ )}
278
+ </YAxis>
255
279
  {showTooltip && (
256
280
  <ChartTooltip
257
281
  content={tooltip => (
@@ -260,7 +284,7 @@ const StackedAreaChart = forwardRef<HTMLDivElement, StackedAreaChartProps>(
260
284
  payload={tooltip.payload as ReadonlyArray<TooltipRow>}
261
285
  label={tooltip.label}
262
286
  config={config}
263
- valueFormatter={valueFormatter}
287
+ valueFormatter={tooltipValueFormatter}
264
288
  labelFormatter={tooltipLabelFormatter}
265
289
  />
266
290
  )}
@@ -88,6 +88,15 @@ export interface StackedAreaChartProps extends Omit<
88
88
  showGrid?: boolean;
89
89
  /** Formats numeric y-axis ticks and tooltip values. */
90
90
  valueFormatter?: (value: number) => string;
91
+ /**
92
+ * Formats the tooltip's values (for example with a unit), when they should
93
+ * read differently from the axis. Defaults to `valueFormatter`.
94
+ */
95
+ tooltipValueFormatter?: (value: number) => string;
96
+ /** Title under the x axis. */
97
+ xAxisLabel?: string;
98
+ /** Title along the y axis. */
99
+ yAxisLabel?: string;
91
100
  /** Formats x-axis ticks (ignored for year ticks, which show the year). */
92
101
  xTickFormatter?: (value: string | number) => string;
93
102
  /** Formats the tooltip's x label. */
@@ -1,4 +1,4 @@
1
- TimeRangeControls renders a row of preset time range toggles, such as one month or one year, for switching the window of a chart. Control it with timeRange and onTimeRangeChange, and pass loading to disable the controls while data refreshes. Below 768px the same presets show as a select instead of the toggle row, so the control stays on a phone; a range that is not a preset (one dragged on the chart) selects no toggle and shows "Custom" in the select.
1
+ TimeRangeControls renders a row of preset time range toggles, such as one month or one year, for switching the window of a chart. Control it with timeRange and onTimeRangeChange, and pass loading to disable the controls while data refreshes. Below 768px the same presets show as a select instead of the toggle row, so the control stays on a phone; a range that is not a preset (one dragged on the chart) selects no toggle and shows "Custom" in the select. Pass variant="segmented" for the compact look (small buttons on a grey track, the picked one raised); ChartAreaInteractive passes it through as timeRangeVariant, and its headerTitle puts a one-line summary at the start of the same row, with the control at the end.
2
2
 
3
3
  ## When to use
4
4
 
@@ -37,4 +37,25 @@ describe('TimeRangeControls', () => {
37
37
  ),
38
38
  ).toBe(true);
39
39
  });
40
+
41
+ it('draws the segmented look on the toggle row when asked', () => {
42
+ const { rerender } = render(
43
+ <TimeRangeControls timeRange="1y" onTimeRangeChange={noop} />,
44
+ );
45
+ expect(screen.getByRole('group').getAttribute('data-variant')).toBe(
46
+ 'outline',
47
+ );
48
+ rerender(
49
+ <TimeRangeControls
50
+ timeRange="1y"
51
+ onTimeRangeChange={noop}
52
+ variant="segmented"
53
+ />,
54
+ );
55
+ const group = screen.getByRole('group');
56
+ expect(group.getAttribute('data-variant')).toBe('segmented');
57
+ for (const item of group.querySelectorAll('[data-slot="toggle-group-item"]')) {
58
+ expect(item.getAttribute('data-variant')).toBe('segmented');
59
+ }
60
+ });
40
61
  });