@sybilion/uilib 1.8.3 → 1.8.5

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 (51) 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/ChartLines.js +49 -13
  10. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.js +45 -11
  11. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.js +39 -9
  12. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.styl.js +2 -2
  13. package/dist/esm/types/src/components/ui/BarChart/BarChart.types.d.ts +22 -0
  14. package/dist/esm/types/src/components/ui/Chart/chartForecastVisualization.types.d.ts +5 -0
  15. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +22 -5
  16. package/dist/esm/types/src/components/ui/Chart/components/ChartAxes.d.ts +8 -1
  17. package/dist/esm/types/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.d.ts +22 -0
  18. package/dist/esm/types/src/components/ui/Chart/components/SeriesLegend/index.d.ts +1 -0
  19. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +10 -1
  20. package/dist/esm/types/src/components/ui/ChartAreaInteractive/chartHistories.d.ts +5 -0
  21. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.d.ts +10 -3
  22. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.d.ts +1 -1
  23. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.types.d.ts +14 -0
  24. package/dist/esm/types/tests/viewChartGaps.test.d.ts +1 -0
  25. package/package.json +1 -1
  26. package/src/components/ui/BarChart/AGENT.md +4 -0
  27. package/src/components/ui/BarChart/BarChart.styl.d.ts +1 -1
  28. package/src/components/ui/BarChart/BarChart.tsx +107 -21
  29. package/src/components/ui/BarChart/BarChart.types.ts +22 -0
  30. package/src/components/ui/Chart/AGENT.md +3 -0
  31. package/src/components/ui/Chart/chartForecastVisualization.types.ts +5 -0
  32. package/src/components/ui/Chart/components/BaseChartWrapper.styl +5 -0
  33. package/src/components/ui/Chart/components/BaseChartWrapper.styl.d.ts +1 -0
  34. package/src/components/ui/Chart/components/BaseChartWrapper.tsx +124 -5
  35. package/src/components/ui/Chart/components/ChartAxes.tsx +29 -5
  36. package/src/components/ui/Chart/components/ChartTooltipContent.tsx +6 -3
  37. package/src/components/ui/Chart/components/QuantileBands.tsx +1 -0
  38. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl +34 -0
  39. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.d.ts +12 -0
  40. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.tsx +70 -0
  41. package/src/components/ui/Chart/components/SeriesLegend/index.ts +1 -0
  42. package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +110 -40
  43. package/src/components/ui/ChartAreaInteractive/chartHistories.ts +5 -0
  44. package/src/components/ui/StackedAreaChart/AGENT.md +2 -0
  45. package/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.ts +54 -13
  46. package/src/components/ui/StackedAreaChart/StackedAreaChart.styl +3 -0
  47. package/src/components/ui/StackedAreaChart/StackedAreaChart.styl.d.ts +1 -0
  48. package/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.tsx +1 -1
  49. package/src/components/ui/StackedAreaChart/StackedAreaChart.tsx +80 -13
  50. package/src/components/ui/StackedAreaChart/StackedAreaChart.types.ts +14 -0
  51. package/src/docs/pages/StackedAreaChartPage.tsx +30 -0
@@ -1,31 +1,63 @@
1
1
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
2
  import cn from 'classnames';
3
3
  import { forwardRef, useMemo } from 'react';
4
- import { ChartTooltip, ChartLegend } from '../Chart/Chart.js';
5
4
  import { getChartSeriesColor } from '../Chart/chartSeriesPalette.js';
6
- import { BarChart as BarChart$1, CartesianGrid, XAxis, YAxis, Bar } from 'recharts';
7
- import S from './BarChart.styl.js';
8
5
  import { ChartContainer } from '../Chart/components/ChartContainer.js';
6
+ import { ChartPlacedTooltip } from '../Chart/components/ChartPlacedTooltip.js';
9
7
  import { ChartTooltipContent } from '../Chart/components/ChartTooltipContent.js';
10
- import { ChartLegendContent } from '../Chart/components/ChartLegendContent.js';
8
+ import { SeriesLegend } from '../Chart/components/SeriesLegend/SeriesLegend.js';
9
+ import { useLegendState } from '../Chart/hooks/useLegendState.js';
10
+ import { Label, BarChart as BarChart$1, CartesianGrid, XAxis, YAxis, Bar } from 'recharts';
11
+ import S from './BarChart.styl.js';
11
12
 
12
13
  const STACK_ID = 'stack';
14
+ /** Room for an axis title beside the ticks (recharts' default is 30). */
15
+ const CATEGORY_AXIS_HEIGHT_WITH_LABEL = 44;
16
+ const seriesColor = (item, index) => item.color ?? getChartSeriesColor(index);
13
17
  function buildChartConfig(series) {
14
18
  const config = {};
15
19
  series.forEach((item, index) => {
16
20
  config[item.key] = {
17
21
  label: item.label ?? item.key,
18
- color: item.color ?? getChartSeriesColor(index),
22
+ color: seriesColor(item, index),
19
23
  };
20
24
  });
21
25
  return config;
22
26
  }
23
- const BarChart = forwardRef(({ className, data, categoryKey, series, orientation = 'vertical', mode = 'grouped', showLegend = true, showTooltip = true, showGrid = true, valueFormatter, height, ...props }, ref) => {
27
+ const BarChart = forwardRef(({ className, data, categoryKey, series, orientation = 'vertical', mode = 'grouped', showLegend = true, showTooltip = true, showGrid = true, valueFormatter, tooltipValueFormatter, categoryTickFormatter, tooltipLabelFormatter, categoryAxisLabel, valueAxisLabel, hiddenKeys, onToggleKey, height, disableAnimation, ...props }, ref) => {
24
28
  const config = useMemo(() => buildChartConfig(series), [series]);
29
+ const legend = useLegendState();
30
+ const hidden = hiddenKeys ?? legend.hiddenSeries;
31
+ // The legend entries are buttons only for a host that asked for toggling
32
+ // (onToggleKey); without hiddenKeys the chart keeps the hidden set itself.
33
+ const toggle = onToggleKey
34
+ ? (key) => {
35
+ onToggleKey(key);
36
+ if (!hiddenKeys)
37
+ legend.toggleSeries(key);
38
+ }
39
+ : undefined;
25
40
  const isHorizontal = orientation === 'horizontal';
26
41
  const stackId = mode === 'stacked' ? STACK_ID : undefined;
27
42
  const barRadius = mode === 'stacked' ? 0 : isHorizontal ? [0, 3, 3, 0] : [3, 3, 0, 0];
28
- return (jsx("div", { ref: ref, className: cn(S.root, className), ...props, children: jsx(ChartContainer, { config: config, style: height ? { height: `${height}px` } : undefined, children: jsxs(BarChart$1, { data: data, layout: isHorizontal ? 'vertical' : 'horizontal', accessibilityLayer: true, children: [showGrid && (jsx(CartesianGrid, { stroke: "var(--border)", strokeWidth: 0.6, vertical: isHorizontal, horizontal: !isHorizontal })), isHorizontal ? (jsxs(Fragment, { children: [jsx(XAxis, { type: "number", tickLine: false, axisLine: { stroke: 'var(--border)', strokeWidth: 1 }, tickFormatter: valueFormatter }), jsx(YAxis, { type: "category", dataKey: categoryKey, tickLine: false, axisLine: { stroke: 'var(--border)', strokeWidth: 1 }, width: 80 })] })) : (jsxs(Fragment, { children: [jsx(XAxis, { type: "category", dataKey: categoryKey, tickLine: false, axisLine: { stroke: 'var(--border)', strokeWidth: 1 } }), jsx(YAxis, { type: "number", tickLine: false, axisLine: { stroke: 'var(--border)', strokeWidth: 1 }, width: 48, tickFormatter: valueFormatter })] })), showTooltip && (jsx(ChartTooltip, { cursor: { fill: 'var(--muted)' }, content: jsx(ChartTooltipContent, { indicator: "dot" }) })), series.map(item => (jsx(Bar, { dataKey: item.key, fill: `var(--color-${item.key})`, stackId: stackId, radius: barRadius, maxBarSize: 48 }, item.key))), showLegend && jsx(ChartLegend, { content: jsx(ChartLegendContent, {}) })] }) }) }));
43
+ const axisLine = { stroke: 'var(--border)', strokeWidth: 1 };
44
+ const categoryLabel = categoryAxisLabel ? (isHorizontal ? (jsx(Label, { value: categoryAxisLabel, angle: -90, position: "insideLeft" })) : (jsx(Label, { value: categoryAxisLabel, position: "insideBottom", offset: 0 }))) : null;
45
+ const valueLabel = valueAxisLabel ? (isHorizontal ? (jsx(Label, { value: valueAxisLabel, position: "insideBottom", offset: 0 })) : (jsx(Label, { value: valueAxisLabel, angle: -90, position: "insideLeft" }))) : null;
46
+ const labelFormatter = tooltipLabelFormatter
47
+ ? (label) => tooltipLabelFormatter(typeof label === 'number' ? label : String(label ?? ''))
48
+ : undefined;
49
+ return (jsxs("div", { ref: ref, className: cn(S.root, className), ...props, children: [jsx(ChartContainer, { config: config, style: height ? { height: `${height}px` } : undefined, children: jsxs(BarChart$1, { data: data, layout: isHorizontal ? 'vertical' : 'horizontal', accessibilityLayer: true, children: [showGrid && (jsx(CartesianGrid, { stroke: "var(--border)", strokeWidth: 0.6, vertical: isHorizontal, horizontal: !isHorizontal })), isHorizontal ? (jsxs(Fragment, { children: [jsx(XAxis, { type: "number", tickLine: false, axisLine: axisLine, tickFormatter: valueFormatter, height: valueAxisLabel ? CATEGORY_AXIS_HEIGHT_WITH_LABEL : undefined, children: valueLabel }), jsx(YAxis, { type: "category", dataKey: categoryKey, tickLine: false, axisLine: axisLine, tickFormatter: categoryTickFormatter,
50
+ // Room for the rotated title beside the category names.
51
+ width: categoryAxisLabel ? 96 : 80, children: categoryLabel })] })) : (jsxs(Fragment, { children: [jsx(XAxis, { type: "category", dataKey: categoryKey, tickLine: false, axisLine: axisLine, tickFormatter: categoryTickFormatter, height: categoryAxisLabel
52
+ ? CATEGORY_AXIS_HEIGHT_WITH_LABEL
53
+ : undefined, children: categoryLabel }), jsx(YAxis, { type: "number", tickLine: false, axisLine: axisLine,
54
+ // Room for the title beside the tick labels.
55
+ width: valueAxisLabel ? 64 : 48, tickFormatter: valueFormatter, children: valueLabel })] })), showTooltip && (jsx(ChartPlacedTooltip, { cursor: { fill: 'var(--muted)' }, content: jsx(ChartTooltipContent, { indicator: "dot", valueFormatter: tooltipValueFormatter, labelFormatter: labelFormatter }) })), series.map(item => (jsx(Bar, { dataKey: item.key, fill: `var(--color-${item.key})`, stackId: stackId, radius: barRadius, maxBarSize: 48, hide: hidden.has(item.key), isAnimationActive: !disableAnimation }, item.key)))] }) }), showLegend && (jsx(SeriesLegend, { items: series.map((item, index) => ({
56
+ dataKey: item.key,
57
+ label: item.label ?? item.key,
58
+ color: seriesColor(item, index),
59
+ square: true,
60
+ })), hiddenSeries: hidden, onToggle: toggle }))] }));
29
61
  });
30
62
  BarChart.displayName = 'BarChart';
31
63
 
@@ -2,7 +2,7 @@ import { jsx, jsxs } from 'react/jsx-runtime';
2
2
  import cn from 'classnames';
3
3
  import { forwardRef, useState, useRef, useMemo, useEffect } from 'react';
4
4
  import { resolveHistoryLines, getForecastColor, ChartLines } from '../../ChartAreaInteractive/ChartLines.js';
5
- import { isHistorySeriesKey, historySeriesKeys } from '../../ChartAreaInteractive/chartHistories.js';
5
+ import { isHistorySeriesKey, HISTORY_SERIES_KEY, historySeriesKeys } from '../../ChartAreaInteractive/chartHistories.js';
6
6
  import { Skeleton } from '../../Skeleton/Skeleton.js';
7
7
  import { chartRenderQueue } from '../../../../utils/chartRenderQueue.js';
8
8
  import { LineChart, ComposedChart } from 'recharts';
@@ -19,6 +19,7 @@ import { ChartTooltipContent } from './ChartTooltipContent.js';
19
19
  import { CustomChartLegend } from './CustomChartLegend/CustomChartLegend.js';
20
20
  import { LegendSvg } from './LegendSvg/LegendSvg.js';
21
21
  import { QuantileBands } from './QuantileBands.js';
22
+ import { SeriesLegend } from './SeriesLegend/SeriesLegend.js';
22
23
 
23
24
  function clampTooltipTranslate(args) {
24
25
  const { coordinate, viewBox, tooltipWidth: tw, tooltipHeight: th, offset, edgeMargin, } = args;
@@ -64,7 +65,9 @@ BaseChartWrapperLoading.displayName = 'BaseChartWrapperLoading';
64
65
  * Separated to maintain hook order consistency
65
66
  */
66
67
  const BaseChartWrapperContent = forwardRef((props, ref) => {
67
- const { chartConfig = {}, chartData, historicalLineColor, forecastData = [], historyData, loading, hasCombinedData, renderId, isDarkTheme, height, className, loadingComponentClassName, footerClassName, chartClassName, xAxisClassName, yAxisClassName, legendClassName, footerActions, quantileBands, quantileBandKey, xMin, xMax, yMin, yMax, autoScaleYAxis = true, formatNumber, formatTooltipValue, connectHistoryNulls, connectForecastNulls, historyOnTop, showEndDots, formatDate: formatDateFn = formatDate, labelFormatter, onLegendClick, margin, chartType = 'composed', disableAnimation = false, disableLineDrawAnimation = false, showGrid = true, showAxes = true, showTooltip = true, showLegend = true, showChartAxesLegend = true, xAxisLabel, yAxisLabel, showActiveDots = true, overlayElements, hiddenSeries, includeHiddenInYScale = false, excludeLegendIds, onAnalysisSelect, onFailedAnalysisClick, containerProps, error, loadingMessage, noDataHint, noDataMessage = 'No data available', noDataStatusTone = 'muted', suppressNoDataState = false, onGridHeightChange, forecastLineStyle = 'dashed', disableHistoricalAnimation = false, onShowAll: _onShowAll, onShowOnly: _onShowOnly, maxVisibleItems, preventDeselection, legendVariant = 'default', legendWidth = 1000, legendMarginLeft = 0, } = props;
68
+ const { chartConfig = {}, chartData, historicalLineColor, forecastData = [], historyData, loading, hasCombinedData, renderId, isDarkTheme, height, className, loadingComponentClassName, footerClassName, chartClassName, xAxisClassName, yAxisClassName, legendClassName, footerActions, quantileBands, quantileBandKey, xMin, xMax, yMin, yMax, autoScaleYAxis = true, formatNumber, formatTooltipValue, connectHistoryNulls, connectForecastNulls, historyOnTop, showEndDots, dotLonePoints, formatDate: formatDateProp, labelFormatter, onLegendClick, margin, chartType = 'composed', disableAnimation = false, disableLineDrawAnimation = false, showGrid = true, showAxes = true, showTooltip = true, showLegend = true, showChartAxesLegend = true, xAxisLabel, yAxisLabel, xAxisType, xTicks, showActiveDots = true, overlayElements, hiddenSeries, includeHiddenInYScale = false, excludeLegendIds, onAnalysisSelect, onFailedAnalysisClick, containerProps, error, loadingMessage, noDataHint, noDataMessage = 'No data available', noDataStatusTone = 'muted', suppressNoDataState = false, onGridHeightChange, forecastLineStyle = 'dashed', disableHistoricalAnimation = false, onShowAll: _onShowAll, onShowOnly: _onShowOnly, maxVisibleItems, preventDeselection, legendVariant = 'default', legendOrder, legendWidth = 1000, legendMarginLeft = 0, } = props;
69
+ // A number axis has no dates to format: its default prints the number.
70
+ const formatDateFn = formatDateProp ?? (xAxisType === 'number' ? String : formatDate);
68
71
  const [shouldAnimate, setShouldAnimate] = useState(false);
69
72
  const lineDataInitializedRef = useRef(false);
70
73
  const rootRef = useRef(null);
@@ -186,7 +189,13 @@ const BaseChartWrapperContent = forwardRef((props, ref) => {
186
189
  const renderTooltipContent = (props) => {
187
190
  // Filter payload to exclude items with null/undefined values
188
191
  // This prevents showing stale data when hovering on dates without data points
189
- const filteredPayload = normalizeTooltipPayload(props.payload);
192
+ const normalized = normalizeTooltipPayload(props.payload);
193
+ // With `legendOrder`, the rows read in the legend's order (recharts lists
194
+ // every history line before the forecasts).
195
+ const filteredPayload = legendOrder && normalized
196
+ ? [...normalized].sort((a, b) => orderRank(legendOrder, a.dataKey) -
197
+ orderRank(legendOrder, b.dataKey))
198
+ : normalized;
190
199
  // If no valid payload items, render ChartTooltipContent with active=false and empty payload
191
200
  // This allows ChartTooltipContent to clear its lastTooltipData state
192
201
  if (!filteredPayload || filteredPayload.length === 0) {
@@ -245,6 +254,52 @@ const BaseChartWrapperContent = forwardRef((props, ref) => {
245
254
  updated_at: item.updated_at,
246
255
  }));
247
256
  }, [forecastData, excludeLegendIds, showLegend]);
257
+ // The plain legend: every line in `legendOrder` (else histories, then
258
+ // forecasts), forecasts drawn dashed when their lines are.
259
+ const plainLegend = useMemo(() => {
260
+ if (!showLegend || legendVariant !== 'plain')
261
+ return [];
262
+ // Without historyData the chart draws the single `historical` line;
263
+ // it is listed when it has a value to draw.
264
+ const singleHistory = !historyData?.length &&
265
+ chartData.some(row => row[HISTORY_SERIES_KEY] != null)
266
+ ? [
267
+ {
268
+ dataKey: HISTORY_SERIES_KEY,
269
+ label: 'Historical Data',
270
+ color: historicalLineColor ?? (isDarkTheme ? '#ffffff' : '#000000'),
271
+ },
272
+ ]
273
+ : [];
274
+ const all = [
275
+ ...singleHistory,
276
+ ...(historyLegend ?? []).map(h => ({
277
+ dataKey: h.dataKey,
278
+ label: h.value,
279
+ color: h.color,
280
+ })),
281
+ ...legendPayload.map(p => ({
282
+ dataKey: p.dataKey,
283
+ label: p.value,
284
+ color: p.color,
285
+ dashed: forecastLineStyle === 'dashed',
286
+ })),
287
+ ];
288
+ if (!legendOrder)
289
+ return all;
290
+ return [...all].sort((a, b) => orderRank(legendOrder, a.dataKey) - orderRank(legendOrder, b.dataKey));
291
+ }, [
292
+ showLegend,
293
+ legendVariant,
294
+ historyData,
295
+ chartData,
296
+ historicalLineColor,
297
+ isDarkTheme,
298
+ historyLegend,
299
+ legendPayload,
300
+ forecastLineStyle,
301
+ legendOrder,
302
+ ]);
248
303
  useEffect(() => {
249
304
  if (disableAnimation) {
250
305
  setShouldAnimate(false);
@@ -336,9 +391,14 @@ const BaseChartWrapperContent = forwardRef((props, ref) => {
336
391
  // The same axes in the grid layer and the chart layer, so both share one
337
392
  // scale. Hidden when showAxes is off: the hidden x-axis still places the
338
393
  // rows by date, so the tooltip names it.
339
- const axes = (jsx(ChartAxes, { hide: !showAxes, formatDate: formatDateFn, formatNumber: formatNumber, xAxisClassName: xAxisClassName, yAxisClassName: yAxisClassName, xAxisLabel: xAxisLabel, yAxisLabel: yAxisLabel, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax, autoScaleYAxis: effectiveAutoScale }));
340
- return (jsxs("div", { className: cn(S.root, !showLegend && S.noLegend, !showChartAxesLegend && S.hideChartAxesLegend, disableLineDrawAnimation && S.noLineDrawAnimation, isLoaded && S.loaded, className), ref: setRefs, children: [loading && (jsx("div", { className: S.loadingOverlay, children: jsx(Skeleton, {}) })), showGrid && (jsx(ChartContainer, { config: chartConfig, className: cn(S.gridLayer, chartClassName), style: height ? { height: `${height}px` } : undefined, children: jsxs(ChartComponent, { data: chartData, margin: margin, children: [jsx(ChartGrid, {}), axes] }) })), jsx(ChartContainer, { config: chartConfig, className: cn(S.chartLayer, chartClassName), style: height ? { height: `${height}px` } : undefined, ...containerProps, children: jsxs(ChartComponent, { data: chartData, margin: margin, children: [axes, quantileBands?.[0] && (jsx(QuantileBands, { hiddenBands: hiddenSeries, quantileBandKey: quantileBandKey, animate: true, animationDuration: 150, animationBegin: 0, customBands: quantileBands, showLegend: showLegend })), jsx(ChartLines, { historicalLineColor: historicalLineColor, chartData: chartData, forecastData: forecastData, historyData: historyData, hiddenSeries: hiddenSeries, isDarkTheme: isDarkTheme, shouldAnimate: shouldAnimate, disableAnimation: disableAnimation, disableHistoricalAnimation: disableHistoricalAnimation, showLegend: showLegend, forecastLineStyle: forecastLineStyle, connectHistoryNulls: connectHistoryNulls, connectForecastNulls: connectForecastNulls, historyOnTop: historyOnTop, showEndDots: showEndDots }), showTooltip && (jsx("div", { children: jsx(ChartPlacedTooltip, { cursor: false, offset: TOOLTIP_OFFSET, allowEscapeViewBox: { x: false, y: false }, wrapperStyle: tooltipWrapperStyle(), content: renderTooltipContent }) }))] }) }), overlayElements, jsxs("div", { className: cn(S.footer, footerClassName), children: [showLegend &&
341
- (legendVariant === 'svg' ? (jsx(LegendSvg, { payload: [
394
+ const axes = (jsx(ChartAxes, { hide: !showAxes, formatDate: formatDateFn, formatNumber: formatNumber, xAxisClassName: xAxisClassName, yAxisClassName: yAxisClassName, xAxisLabel: xAxisLabel, yAxisLabel: yAxisLabel, xAxisType: xAxisType, xTicks: xTicks, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax, autoScaleYAxis: effectiveAutoScale }));
395
+ return (jsxs("div", { className: cn(S.root, !showLegend && S.noLegend, !showChartAxesLegend && S.hideChartAxesLegend, disableLineDrawAnimation && S.noLineDrawAnimation, isLoaded && S.loaded, className), ref: setRefs, children: [loading && (jsx("div", { className: S.loadingOverlay, children: jsx(Skeleton, {}) })), showGrid && (jsx(ChartContainer, { config: chartConfig, className: cn(S.gridLayer, chartClassName), style: height ? { height: `${height}px` } : undefined, children: jsxs(ChartComponent, { data: chartData, margin: margin, children: [jsx(ChartGrid, {}), axes] }) })), jsx(ChartContainer, { config: chartConfig, className: cn(S.chartLayer, chartClassName), style: height ? { height: `${height}px` } : undefined, ...containerProps, children: jsxs(ChartComponent, { data: chartData, margin: margin, children: [axes, quantileBands?.[0] && (jsx(QuantileBands, { hiddenBands: hiddenSeries, quantileBandKey: quantileBandKey, animate: !disableAnimation, animationDuration: 150, animationBegin: 0, customBands: quantileBands, showLegend: showLegend })), jsx(ChartLines, { historicalLineColor: historicalLineColor, chartData: chartData, forecastData: forecastData, historyData: historyData, hiddenSeries: hiddenSeries, isDarkTheme: isDarkTheme, shouldAnimate: shouldAnimate, disableAnimation: disableAnimation, disableHistoricalAnimation: disableHistoricalAnimation, showLegend: showLegend, forecastLineStyle: forecastLineStyle, connectHistoryNulls: connectHistoryNulls, connectForecastNulls: connectForecastNulls, historyOnTop: historyOnTop, showEndDots: showEndDots, dotLonePoints: dotLonePoints }), showTooltip && (jsx("div", { children: jsx(ChartPlacedTooltip, { cursor: false, offset: TOOLTIP_OFFSET, allowEscapeViewBox: { x: false, y: false }, wrapperStyle: tooltipWrapperStyle(), content: renderTooltipContent }) }))] }) }), overlayElements, jsxs("div", { className: cn(S.footer, footerClassName), children: [showLegend &&
396
+ (legendVariant === 'plain' ? (jsx(SeriesLegend, { className: cn(S.plainLegend, legendClassName), items: plainLegend, hiddenSeries: hiddenSeries, onToggle: onLegendClick
397
+ ? dataKey => {
398
+ const index = plainLegend.findIndex(item => item.dataKey === dataKey);
399
+ onLegendClick({ dataKey, value: plainLegend[index]?.label }, index, {});
400
+ }
401
+ : undefined })) : legendVariant === 'svg' ? (jsx(LegendSvg, { payload: [
342
402
  ...(historyLegend ?? []).map(p => ({ ...p, solid: true })),
343
403
  ...legendPayload.map(p => ({
344
404
  value: p.value,
@@ -352,6 +412,11 @@ BaseChartWrapperContent.displayName = 'BaseChartWrapperContent';
352
412
  * Base chart wrapper component with common structure
353
413
  * Handles container, grid, axes, tooltip, and legend
354
414
  */
415
+ /** A key's place in `order`; keys not in it go last, in their own order. */
416
+ function orderRank(order, key) {
417
+ const i = typeof key === 'string' ? order.indexOf(key) : -1;
418
+ return i === -1 ? order.length : i;
419
+ }
355
420
  function BaseChartWrapper(props) {
356
421
  const { renderId, chartData, loading, hasCombinedData, legendVariant } = props;
357
422
  const [isReadyToRender, setIsReadyToRender] = useState(false);
@@ -1,7 +1,7 @@
1
1
  import styleInject from 'style-inject';
2
2
 
3
- var css_248z = ".BaseChartWrapper_chartContainer__J6CIc,.BaseChartWrapper_root__hhfho{min-height:100%}.BaseChartWrapper_root__hhfho{position:relative;width:100%}.BaseChartWrapper_gridLayer__cwJXA{pointer-events:none;position:absolute;z-index:1}.BaseChartWrapper_gridLayer__cwJXA .recharts-cartesian-axis{pointer-events:auto;z-index:1}.BaseChartWrapper_chartLayer__HmBaJ{inset:0;pointer-events:auto;position:relative;z-index:3}.BaseChartWrapper_chartLayer__HmBaJ .recharts-surface{background:transparent}.BaseChartWrapper_chartLayer__HmBaJ .recharts-layer{pointer-events:none}.BaseChartWrapper_chartLayer__HmBaJ .recharts-tooltip-wrapper{visibility:visible!important}.BaseChartWrapper_invisibleAxis__TQ-Zk .recharts-cartesian-axis-tick{visibility:hidden}.BaseChartWrapper_legend__gkSy1{position:absolute;top:100%;width:100%}.BaseChartWrapper_noLegend__jqaPa{display:block}.BaseChartWrapper_hideChartAxesLegend__dgVx- .recharts-cartesian-axis-tick-label{display:none!important}.BaseChartWrapper_chartLoadingContainer__AJP-0{align-items:center;display:flex;height:var(--chart-height);justify-content:center;width:100%}.BaseChartWrapper_loadingChartSlot__eG2BL{height:100%;position:relative;width:100%}.BaseChartWrapper_loadingOverlay__GcOkA{height:100%;inset:0;opacity:.5;pointer-events:none;position:absolute;transition:opacity .1s ease-out;width:100%;z-index:10}.BaseChartWrapper_loadingOverlay__GcOkA [data-slot=skeleton]{border-radius:var(--p-4)!important}.BaseChartWrapper_loaded__Gj15C .BaseChartWrapper_loadingOverlay__GcOkA{opacity:0}.BaseChartWrapper_errorContainer__1bXy1{align-items:center;color:var(--destructive);display:flex;justify-content:center;min-height:250px}.BaseChartWrapper_emptyChartSizer__Wg--C{min-height:var(--chart-height);width:100%}.BaseChartWrapper_errorMessage__veSmB{color:var(--destructive)}.BaseChartWrapper_noLineDrawAnimation__cyrzV .recharts-line-curve{stroke-dasharray:inherit!important}.BaseChartWrapper_footer__nP5u6{align-items:center;display:flex;gap:var(--p-2);justify-content:space-between}";
4
- var S = {"root":"BaseChartWrapper_root__hhfho","chartContainer":"BaseChartWrapper_chartContainer__J6CIc","gridLayer":"BaseChartWrapper_gridLayer__cwJXA","chartLayer":"BaseChartWrapper_chartLayer__HmBaJ","invisibleAxis":"BaseChartWrapper_invisibleAxis__TQ-Zk","legend":"BaseChartWrapper_legend__gkSy1","noLegend":"BaseChartWrapper_noLegend__jqaPa","hideChartAxesLegend":"BaseChartWrapper_hideChartAxesLegend__dgVx-","chartLoadingContainer":"BaseChartWrapper_chartLoadingContainer__AJP-0","loadingChartSlot":"BaseChartWrapper_loadingChartSlot__eG2BL","loadingOverlay":"BaseChartWrapper_loadingOverlay__GcOkA","loaded":"BaseChartWrapper_loaded__Gj15C","errorContainer":"BaseChartWrapper_errorContainer__1bXy1","emptyChartSizer":"BaseChartWrapper_emptyChartSizer__Wg--C","errorMessage":"BaseChartWrapper_errorMessage__veSmB","noLineDrawAnimation":"BaseChartWrapper_noLineDrawAnimation__cyrzV","footer":"BaseChartWrapper_footer__nP5u6"};
3
+ var css_248z = ".BaseChartWrapper_chartContainer__J6CIc,.BaseChartWrapper_root__hhfho{min-height:100%}.BaseChartWrapper_root__hhfho{position:relative;width:100%}.BaseChartWrapper_gridLayer__cwJXA{pointer-events:none;position:absolute;z-index:1}.BaseChartWrapper_gridLayer__cwJXA .recharts-cartesian-axis{pointer-events:auto;z-index:1}.BaseChartWrapper_chartLayer__HmBaJ{inset:0;pointer-events:auto;position:relative;z-index:3}.BaseChartWrapper_chartLayer__HmBaJ .recharts-surface{background:transparent}.BaseChartWrapper_chartLayer__HmBaJ .recharts-layer{pointer-events:none}.BaseChartWrapper_chartLayer__HmBaJ .recharts-tooltip-wrapper{visibility:visible!important}.BaseChartWrapper_invisibleAxis__TQ-Zk .recharts-cartesian-axis-tick{visibility:hidden}.BaseChartWrapper_legend__gkSy1{position:absolute;top:100%;width:100%}.BaseChartWrapper_noLegend__jqaPa{display:block}.BaseChartWrapper_hideChartAxesLegend__dgVx- .recharts-cartesian-axis-tick-label{display:none!important}.BaseChartWrapper_chartLoadingContainer__AJP-0{align-items:center;display:flex;height:var(--chart-height);justify-content:center;width:100%}.BaseChartWrapper_loadingChartSlot__eG2BL{height:100%;position:relative;width:100%}.BaseChartWrapper_loadingOverlay__GcOkA{height:100%;inset:0;opacity:.5;pointer-events:none;position:absolute;transition:opacity .1s ease-out;width:100%;z-index:10}.BaseChartWrapper_loadingOverlay__GcOkA [data-slot=skeleton]{border-radius:var(--p-4)!important}.BaseChartWrapper_loaded__Gj15C .BaseChartWrapper_loadingOverlay__GcOkA{opacity:0}.BaseChartWrapper_errorContainer__1bXy1{align-items:center;color:var(--destructive);display:flex;justify-content:center;min-height:250px}.BaseChartWrapper_emptyChartSizer__Wg--C{min-height:var(--chart-height);width:100%}.BaseChartWrapper_errorMessage__veSmB{color:var(--destructive)}.BaseChartWrapper_noLineDrawAnimation__cyrzV .recharts-line-curve{stroke-dasharray:inherit!important}.BaseChartWrapper_footer__nP5u6{align-items:center;display:flex;gap:var(--p-2);justify-content:space-between}.BaseChartWrapper_plainLegend__tVct-{flex:1}";
4
+ var S = {"root":"BaseChartWrapper_root__hhfho","chartContainer":"BaseChartWrapper_chartContainer__J6CIc","gridLayer":"BaseChartWrapper_gridLayer__cwJXA","chartLayer":"BaseChartWrapper_chartLayer__HmBaJ","invisibleAxis":"BaseChartWrapper_invisibleAxis__TQ-Zk","legend":"BaseChartWrapper_legend__gkSy1","noLegend":"BaseChartWrapper_noLegend__jqaPa","hideChartAxesLegend":"BaseChartWrapper_hideChartAxesLegend__dgVx-","chartLoadingContainer":"BaseChartWrapper_chartLoadingContainer__AJP-0","loadingChartSlot":"BaseChartWrapper_loadingChartSlot__eG2BL","loadingOverlay":"BaseChartWrapper_loadingOverlay__GcOkA","loaded":"BaseChartWrapper_loaded__Gj15C","errorContainer":"BaseChartWrapper_errorContainer__1bXy1","emptyChartSizer":"BaseChartWrapper_emptyChartSizer__Wg--C","errorMessage":"BaseChartWrapper_errorMessage__veSmB","noLineDrawAnimation":"BaseChartWrapper_noLineDrawAnimation__cyrzV","footer":"BaseChartWrapper_footer__nP5u6","plainLegend":"BaseChartWrapper_plainLegend__tVct-"};
5
5
  styleInject(css_248z);
6
6
 
7
7
  export { S as default };
@@ -3,10 +3,14 @@ import { useMemo } from 'react';
3
3
  import { XAxis, Label, YAxis } from 'recharts';
4
4
  import { generateRoundedYTicks, formatNumber, formatYAxisNumber } from '../tools/formatters.js';
5
5
 
6
+ /** Axis room for a title beside the ticks. */
7
+ const X_AXIS_HEIGHT_WITH_LABEL = 44;
8
+ const Y_AXIS_WIDTH_WITH_LABEL = 72;
9
+ const numericDate = (row) => Number(row.date);
6
10
  function ChartAxes({ xAxisClassName, yAxisClassName, xAxisLabel, yAxisLabel, formatDate,
7
11
  // The host's number format for the y-axis ticks; uilib's compact one
8
12
  // (K/M/B, whole numbers below 1000) without it.
9
- formatNumber: formatNumber$1 = formatNumber, xMin, xMax, yMin, yMax, autoScaleYAxis = false, hide = false, }) {
13
+ formatNumber: formatNumber$1 = formatNumber, xMin, xMax, yMin, yMax, autoScaleYAxis = false, xAxisType = 'category', xTicks, hide = false, }) {
10
14
  const tickColor = 'var(--muted-foreground)';
11
15
  // Generate rounded ticks to avoid duplicates when we have explicit domain
12
16
  const yTicks = useMemo(() => {
@@ -46,8 +50,12 @@ formatNumber: formatNumber$1 = formatNumber, xMin, xMax, yMin, yMax, autoScaleYA
46
50
  else if (yMin !== undefined && yMax !== undefined) {
47
51
  yDomain = [yMin, yMax];
48
52
  }
49
- return (jsxs(Fragment, { children: [jsx(XAxis, { className: xAxisClassName, dataKey: "date", hide: hide, tickLine: false, axisLine: false, tickMargin: 8, minTickGap: 32, tick: { fill: tickColor }, tickFormatter: value => formatDate(value), ...(xMin !== undefined &&
50
- xMax !== undefined && { domain: [xMin, xMax] }), children: xAxisLabel && (jsx(Label, { value: xAxisLabel, position: "insideBottom", offset: -5 })) }), hide && !autoScaleYAxis && yMin !== undefined && yMax !== undefined && (jsx(YAxis, { hide: true, domain: [yMin, yMax] })), !hide && (jsx(YAxis, { className: yAxisClassName, tickLine: false, axisLine: false, tickMargin: 8, minTickGap: 32, tick: { fill: tickColor }, tickFormatter: formatNumber$1, ...(yDomain && { domain: yDomain }), ...(yTicks && { ticks: yTicks }), allowDataOverflow: !autoScaleYAxis, children: yAxisLabel && (jsx(Label, { value: yAxisLabel, angle: -90, position: "insideLeft" })) }))] }));
53
+ return (jsxs(Fragment, { children: [jsx(XAxis, { className: xAxisClassName,
54
+ // A number axis reads the row's `date` as a number (rows keep it as
55
+ // text, like every other chart's).
56
+ dataKey: xAxisType === 'number' ? numericDate : 'date', type: xAxisType, hide: hide, tickLine: false, axisLine: false, tickMargin: 8, minTickGap: xTicks ? 8 : 32, tick: { fill: tickColor }, tickFormatter: value => formatDate(value), ...(xAxisLabel && { height: X_AXIS_HEIGHT_WITH_LABEL }), ...(xTicks && { ticks: [...xTicks] }), ...(xMin !== undefined && xMax !== undefined
57
+ ? { domain: [xMin, xMax] }
58
+ : xAxisType === 'number' && { domain: ['dataMin', 'dataMax'] }), children: xAxisLabel && (jsx(Label, { value: xAxisLabel, position: "insideBottom", offset: 0 })) }), hide && !autoScaleYAxis && yMin !== undefined && yMax !== undefined && (jsx(YAxis, { hide: true, domain: [yMin, yMax] })), !hide && (jsx(YAxis, { className: yAxisClassName, tickLine: false, axisLine: false, tickMargin: 8, minTickGap: 32, tick: { fill: tickColor }, tickFormatter: formatNumber$1, ...(yAxisLabel && { width: Y_AXIS_WIDTH_WITH_LABEL }), ...(yDomain && { domain: yDomain }), ...(yTicks && { ticks: yTicks }), allowDataOverflow: !autoScaleYAxis, children: yAxisLabel && (jsx(Label, { value: yAxisLabel, angle: -90, position: "insideLeft" })) }))] }));
51
59
  }
52
60
 
53
61
  export { ChartAxes };
@@ -45,13 +45,16 @@ function ChartTooltipContent({ active, className, indicator = 'dot', hideLabel =
45
45
  const [item] = payloadArray;
46
46
  const key = `${labelKey || item.dataKey || item.name || 'value'}`;
47
47
  const itemConfig = getPayloadConfigFromPayload(config, item, key);
48
- const value = !labelKey && typeof displayLabel === 'string'
49
- ? config[displayLabel]?.label || displayLabel
48
+ // A number x (a number axis) is the label as much as a text one is.
49
+ const value = !labelKey &&
50
+ (typeof displayLabel === 'string' || typeof displayLabel === 'number')
51
+ ? config[String(displayLabel)]?.label ||
52
+ displayLabel
50
53
  : itemConfig?.label;
51
54
  if (labelFormatter) {
52
55
  return (jsx("div", { className: cn('font-medium', labelClassName), children: labelFormatter(value, displayPayload) }));
53
56
  }
54
- if (!value) {
57
+ if (value == null || value === '') {
55
58
  return null;
56
59
  }
57
60
  return jsx("div", { className: cn('font-medium', labelClassName), children: value });
@@ -14,7 +14,7 @@ function QuantileBands({ color, hiddenBands = new Set(), quantileBandKey, animat
14
14
  const fillColor = color || band.color || getForecastQuantileBandColor(index);
15
15
  return (jsx(Area, { type: band.type || 'monotone', dataKey: band.key, name: band.name, stroke: band.strokeWidth ? fillColor : 'none', strokeWidth: band.strokeWidth || 0, strokeDasharray: band.strokeDasharray, strokeOpacity: band.strokeOpacity, fill: fillColor,
16
16
  // fillOpacity={band.opacity}
17
- legendType: showLegend === false ? 'none' : undefined, connectNulls: band.connectNulls ?? true, dot: false, activeDot: false, isAnimationActive: animate, animationDuration: animationDuration, animationBegin: animationBegin, animationEasing: "ease-out" }, quantileBandKey
17
+ legendType: showLegend === false ? 'none' : undefined, tooltipType: band.showInTooltip === false ? 'none' : undefined, connectNulls: band.connectNulls ?? true, dot: false, activeDot: false, isAnimationActive: animate, animationDuration: animationDuration, animationBegin: animationBegin, animationEasing: "ease-out" }, quantileBandKey
18
18
  ? `${quantileBandKey}-${index}`
19
19
  : `quantile-band-${index}`));
20
20
  }) }));
@@ -0,0 +1,20 @@
1
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
+ import cn from 'classnames';
3
+ import ChartS from '../../Chart.styl.js';
4
+ import S from './SeriesLegend.styl.js';
5
+
6
+ /**
7
+ * A plain legend: one entry per series, in the order given, each a button
8
+ * that hides or shows its series. A hidden series' entry is dimmed.
9
+ */
10
+ function SeriesLegend({ items, hiddenSeries, onToggle, className, }) {
11
+ if (items.length === 0)
12
+ return null;
13
+ return (jsx("div", { className: cn(ChartS.legendContainer, S.root, className), children: items.map(item => {
14
+ const dimmed = hiddenSeries?.has(item.dataKey) ?? false;
15
+ const content = (jsxs(Fragment, { children: [jsx("span", { className: cn(S.swatch, item.square ? S.square : item.dashed && S.dashed), style: { color: item.color }, "aria-hidden": true }), item.label] }));
16
+ return onToggle ? (jsx("button", { type: "button", className: cn(ChartS.legendItem, S.button, dimmed && S.dimmed), "aria-pressed": !dimmed, onClick: () => onToggle(item.dataKey), children: content }, item.dataKey)) : (jsx("span", { className: ChartS.legendItem, children: content }, item.dataKey));
17
+ }) }));
18
+ }
19
+
20
+ export { SeriesLegend };
@@ -0,0 +1,7 @@
1
+ import styleInject from 'style-inject';
2
+
3
+ var css_248z = ".SeriesLegend_root__5W8Ao{flex-wrap:wrap;margin-top:.75rem;row-gap:.5rem}.SeriesLegend_button__F5-RK{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;border:0;color:inherit;cursor:pointer;font:inherit;padding:0}.SeriesLegend_dimmed__I8twS{opacity:.4}.SeriesLegend_swatch__kZTb2{border-top:2px solid;flex-shrink:0;height:0;width:14px}.SeriesLegend_dashed__tqWnl{border-top-style:dashed}.SeriesLegend_square__4EzP7{background:currentColor;border-radius:2px;border-top:0;height:.5rem;width:.5rem}";
4
+ var S = {"root":"SeriesLegend_root__5W8Ao","button":"SeriesLegend_button__F5-RK","dimmed":"SeriesLegend_dimmed__I8twS","swatch":"SeriesLegend_swatch__kZTb2","dashed":"SeriesLegend_dashed__tqWnl","square":"SeriesLegend_square__4EzP7"};
5
+ styleInject(css_248z);
6
+
7
+ export { S as default };
@@ -29,6 +29,7 @@ function resolveHistoryLines(histories) {
29
29
  dataKey: historySeriesKey(h.id),
30
30
  name: h.name || String(h.id),
31
31
  color: h.color ?? getHistoryColor(index),
32
+ connectNulls: h.connectNulls,
32
33
  }));
33
34
  }
34
35
  /** Same tint logic as intervals/threshold overlays: band fill follows forecast line hex when known. */
@@ -37,7 +38,7 @@ function resolveQuantileBandFillForForecastLine(lineColor, forecastIndex) {
37
38
  return mapped ?? getForecastQuantileBandColor(forecastIndex);
38
39
  }
39
40
  // Memoized component for chart lines - only re-renders when data/analyses/hiddenSeries change
40
- const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, isDarkTheme, shouldAnimate, historicalLineColor = isDarkTheme ? '#ffffff' : '#000000', showLegend = true, forecastLineStyle = 'dashed', disableAnimation = false, disableHistoricalAnimation = false, connectHistoryNulls = false, connectForecastNulls = false, historyOnTop = false, showEndDots = true, }) => {
41
+ const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, isDarkTheme, shouldAnimate, historicalLineColor = isDarkTheme ? '#ffffff' : '#000000', showLegend = true, forecastLineStyle = 'dashed', disableAnimation = false, disableHistoricalAnimation = false, connectHistoryNulls = false, connectForecastNulls = false, historyOnTop = false, showEndDots = true, dotLonePoints = false, }) => {
41
42
  const dotStroke = isDarkTheme ? '#000000' : '#FFFFFF';
42
43
  const activeDotHistorical = {
43
44
  r: 6,
@@ -92,19 +93,44 @@ const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, i
92
93
  });
93
94
  return indices;
94
95
  }, [chartData, forecastData]);
95
- // Helper to render dot at last data point
96
- const renderDot = (props, lastIndex, dataKey, color) => {
97
- if (lastIndex >= 0 &&
98
- props.index === lastIndex &&
99
- chartData[props.index]?.[dataKey] != null &&
100
- props.cy != null &&
101
- props.cx != null) {
102
- return jsx("circle", { cx: props.cx, cy: props.cy, r: 3, fill: color });
96
+ // How many values each line has, for `dotLonePoints` on a line drawn
97
+ // across gaps: such a line leaves a point alone only when it is its only
98
+ // value.
99
+ const valueCounts = useMemo(() => {
100
+ if (!dotLonePoints)
101
+ return undefined;
102
+ const counts = {};
103
+ for (const row of chartData) {
104
+ for (const [key, value] of Object.entries(row)) {
105
+ if (typeof value === 'number')
106
+ counts[key] = (counts[key] ?? 0) + 1;
107
+ }
108
+ }
109
+ return counts;
110
+ }, [chartData, dotLonePoints]);
111
+ // A dot on the line's last point (with `showEndDots`), and (with
112
+ // `dotLonePoints`) on any point the line leaves alone, which would
113
+ // otherwise not show: no value in the rows on either side, or, for a line
114
+ // drawn across gaps, no other value at all.
115
+ const renderDot = (props, lastIndex, dataKey, color, connected) => {
116
+ const i = props.index;
117
+ if (typeof i !== 'number' ||
118
+ chartData[i]?.[dataKey] == null ||
119
+ props.cy == null ||
120
+ props.cx == null) {
121
+ return null;
122
+ }
123
+ const isEnd = showEndDots && lastIndex >= 0 && i === lastIndex;
124
+ const isAlone = dotLonePoints &&
125
+ (connected
126
+ ? valueCounts?.[dataKey] === 1
127
+ : chartData[i - 1]?.[dataKey] == null &&
128
+ chartData[i + 1]?.[dataKey] == null);
129
+ if (isEnd || isAlone) {
130
+ return (jsx("circle", { cx: props.cx, cy: props.cy, r: 3, fill: color }, `dot-${dataKey}-${i}`));
103
131
  }
104
132
  return null;
105
133
  };
106
- const renderHistoryDot = (props, dataKey, color) => renderDot(props, lastHistoryIndices[dataKey] ?? -1, dataKey, color);
107
- const renderForecastDot = (props, id, color) => renderDot(props, lastForecastIndices[id] ?? -1, `forecast_${id}`, color);
108
134
  const animationActive = Boolean(shouldAnimate) && !disableAnimation;
109
135
  const historicalAnimationActive = animationActive && !disableHistoricalAnimation;
110
136
  const forecastAnimationActive = animationActive;
@@ -114,11 +140,21 @@ const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, i
114
140
  // JSX order: a layer above the forecasts keeps history on top through
115
141
  // hiding, showing and added forecasts, and leaves the tooltip's order.
116
142
  const historyZIndex = historyOnTop ? DefaultZIndexes.line + 1 : undefined;
117
- const historyElements = historyLines.map(({ dataKey, name, color }) => (jsx(Line, { zIndex: historyZIndex, type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1, dot: showEndDots ? props => renderHistoryDot(props, dataKey, color) : false, activeDot: { ...activeDotHistorical, fill: color }, name: name, legendType: showLegend === false ? 'none' : undefined, strokeDasharray: "0", connectNulls: connectHistoryNulls, hide: hiddenSeries?.has(dataKey), isAnimationActive: historicalAnimationActive, animationDuration: animationDuration, animateNewValues: valueAnimationEnabled, animationBegin: 0, animationEasing: "ease-out" }, dataKey)));
143
+ const historyElements = historyLines.map(({ dataKey, name, color, connectNulls }) => {
144
+ const connected = connectNulls ?? connectHistoryNulls;
145
+ return (jsx(Line, { zIndex: historyZIndex, type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1,
146
+ // A line with no dot to draw skips the per-point call.
147
+ dot: showEndDots || dotLonePoints
148
+ ? props => renderDot(props, lastHistoryIndices[dataKey] ?? -1, dataKey, color, connected)
149
+ : false, activeDot: { ...activeDotHistorical, fill: color }, name: name, legendType: showLegend === false ? 'none' : undefined, strokeDasharray: "0", connectNulls: connected, hide: hiddenSeries?.has(dataKey), isAnimationActive: historicalAnimationActive, animationDuration: animationDuration, animateNewValues: valueAnimationEnabled, animationBegin: 0, animationEasing: "ease-out" }, dataKey));
150
+ });
118
151
  const forecastElements = forecastData?.map((data, index) => {
119
152
  const { id, name, color = FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length], } = data;
120
153
  const dataKey = `forecast_${id}`;
121
- return (jsx(Line, { type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1, strokeDasharray: forecastLineStyle === 'dashed' ? '4 2' : '0', dot: showEndDots ? props => renderForecastDot(props, id, color) : false, activeDot: activeDotForecast(color), name: `${name || `${id}`}`, legendType: showLegend === false ? 'none' : undefined, connectNulls: connectForecastNulls, hide: hiddenSeries?.has(dataKey), isAnimationActive: forecastAnimationActive, animationDuration: animationDuration, animateNewValues: valueAnimationEnabled, animationBegin: 0, animationEasing: "ease-out", className: data.status === 'pending' ? 'chart-line-blinking' : undefined }, `forecast-${id}`));
154
+ const connected = data.connectNulls ?? connectForecastNulls;
155
+ return (jsx(Line, { type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1, strokeDasharray: forecastLineStyle === 'dashed' ? '4 2' : '0', dot: showEndDots || dotLonePoints
156
+ ? props => renderDot(props, lastForecastIndices[id] ?? -1, dataKey, color, connected)
157
+ : false, activeDot: activeDotForecast(color), name: `${name || `${id}`}`, legendType: showLegend === false ? 'none' : undefined, connectNulls: connected, hide: hiddenSeries?.has(dataKey), isAnimationActive: forecastAnimationActive, animationDuration: animationDuration, animateNewValues: valueAnimationEnabled, animationBegin: 0, animationEasing: "ease-out", className: data.status === 'pending' ? 'chart-line-blinking' : undefined }, `forecast-${id}`));
122
158
  });
123
159
  return (jsxs(Fragment, { children: [historyElements, forecastElements] }));
124
160
  });
@@ -156,28 +156,62 @@ function compareSides(rows, layerKeys, compareKey) {
156
156
  * A value axis from 0 for a top value: at most `maxIntervals` steps of
157
157
  * 1, 2, 2.5 or 5 × 10ⁿ, with a little headroom above the top. Small changes
158
158
  * in the top (a margin being typed) move the axis by one step at most,
159
- * instead of doubling it the way automatic rounding can.
159
+ * instead of doubling it the way automatic rounding can. A `bottom` below 0
160
+ * (a negative layer or line) starts the axis at a step below it, as `min`.
160
161
  */
161
- function valueAxis(top, maxIntervals = 5, headroom = 0.05) {
162
- const target = Number.isFinite(top) && top > 0 ? top * (1 + headroom) : 1;
163
- let exponent = Math.floor(Math.log10(target / maxIntervals));
162
+ function valueAxis(top, maxIntervals = 5, headroom = 0.05, bottom = 0) {
163
+ const low = Number.isFinite(bottom) && bottom < 0 ? bottom * (1 + headroom) : 0;
164
+ const high = Number.isFinite(top) && top > 0 ? top * (1 + headroom) : low < 0 ? 0 : 1;
165
+ let exponent = Math.floor(Math.log10((high - low) / maxIntervals));
164
166
  for (;;) {
165
167
  for (const mantissa of [1, 2, 2.5, 5]) {
166
168
  const step = mantissa * 10 ** exponent;
167
- const count = Math.ceil(target / step - 1e-9);
168
- if (count <= maxIntervals) {
169
- const ticks = Array.from({ length: count + 1 }, (_, i) => Number((i * step).toPrecision(12)));
170
- return { max: ticks[ticks.length - 1], ticks };
169
+ const first = low < 0 ? Math.floor(low / step + 1e-9) * step : 0;
170
+ const count = Math.ceil((high - first) / step - 1e-9);
171
+ // Both ends round out to a step, so a range across 0 gets one more.
172
+ if (count <= maxIntervals + (low < 0 ? 1 : 0)) {
173
+ const ticks = Array.from({ length: count + 1 }, (_, i) => Number((first + i * step).toPrecision(12)));
174
+ const max = ticks[ticks.length - 1];
175
+ return low < 0 ? { min: ticks[0], max, ticks } : { max, ticks };
171
176
  }
172
177
  }
173
178
  exponent += 1;
174
179
  }
175
180
  }
176
- /** The highest stacked total (layers plus margin) or line value on any row. */
181
+ /**
182
+ * The lowest point the stack (a negative layer or margin pulls it below 0)
183
+ * or a line reaches; 0 when nothing is negative.
184
+ */
185
+ function chartBottom(rows, layerKeys, lineKeys) {
186
+ let bottom = 0;
187
+ for (const row of rows) {
188
+ bottom = Math.min(bottom, stackExtent(row, layerKeys)[0]);
189
+ for (const key of lineKeys)
190
+ bottom = Math.min(bottom, num(row[key]) ?? 0);
191
+ }
192
+ return bottom;
193
+ }
194
+ /**
195
+ * The lowest and highest running totals up a row's stack (layers, then the
196
+ * margin): recharts draws each layer from the total below it, so a negative
197
+ * layer above a positive one leaves the peak below the final total.
198
+ */
199
+ function stackExtent(row, layerKeys) {
200
+ let running = 0;
201
+ let low = 0;
202
+ let high = 0;
203
+ for (const key of [...layerKeys, MARGIN_KEY]) {
204
+ running += num(row[key]) ?? 0;
205
+ low = Math.min(low, running);
206
+ high = Math.max(high, running);
207
+ }
208
+ return [low, high];
209
+ }
210
+ /** The highest point the stack (layers plus margin) or a line reaches. */
177
211
  function chartTop(rows, layerKeys, lineKeys) {
178
212
  let top = 0;
179
213
  for (const row of rows) {
180
- top = Math.max(top, layersTotal(row, layerKeys) + (num(row[MARGIN_KEY]) ?? 0));
214
+ top = Math.max(top, stackExtent(row, layerKeys)[1]);
181
215
  for (const key of lineKeys)
182
216
  top = Math.max(top, num(row[key]) ?? 0);
183
217
  }
@@ -209,4 +243,4 @@ function yearLabel(x) {
209
243
  return YEAR_RE.exec(String(x))?.[1] ?? String(x);
210
244
  }
211
245
 
212
- export { COST_KNOWN_KEY, MARGIN_KEY, chartTop, compareRowZones, compareZones, layersTotal, stackRows, stackWeights, valueAxis, yearLabel, yearTicks };
246
+ export { COST_KNOWN_KEY, MARGIN_KEY, chartBottom, chartTop, compareRowZones, compareZones, layersTotal, stackRows, stackWeights, valueAxis, yearLabel, yearTicks };