@sybilion/uilib 1.7.1 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-glossary/content-prompt.generated.ts +2 -0
- package/dist/agent-glossary/content.generated.ts +2 -0
- package/dist/agent-glossary/content.md +2 -0
- package/dist/agent-glossary/content.prompt.md +2 -0
- package/dist/agent-glossary/workspace.generated.ts +1 -0
- package/dist/agent-glossary/workspace.index.md +1 -0
- package/dist/agent-glossary/workspace.md +1 -0
- package/dist/esm/src/components/ui/AnalysesSelector/AnalysesSelector.js +37 -20
- package/dist/esm/src/components/ui/Chart/Chart.styl.js +2 -2
- package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +46 -51
- package/dist/esm/src/components/ui/Chart/components/ChartContainer.js +2 -2
- package/dist/esm/src/components/ui/Chart/components/ChartGrid.js +2 -2
- package/dist/esm/src/components/ui/Chart/components/ChartLegendContent.js +2 -2
- package/dist/esm/src/components/ui/Chart/components/ChartLegendItem.js +2 -2
- package/dist/esm/src/components/ui/Chart/components/ChartTooltipContent.js +2 -2
- package/dist/esm/src/components/ui/Chart/components/ChartTooltipItem.js +3 -3
- package/dist/esm/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.js +8 -3
- package/dist/esm/src/components/ui/Chart/components/LegendSvg/LegendSvg.js +1 -1
- package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.js +17 -6
- package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.js +40 -10
- package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +43 -13
- package/dist/esm/src/components/ui/ChartAreaInteractive/chartHistories.js +44 -0
- package/dist/esm/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.js +32 -7
- package/dist/esm/src/components/ui/Page/PageTabs/PageTabs.styl.js +2 -2
- package/dist/esm/src/components/ui/Page/PageXScroll/PageXScroll.js +50 -15
- package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.js +212 -0
- package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.js +123 -0
- package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.styl.js +7 -0
- package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.js +29 -0
- package/dist/esm/src/index.js +3 -1
- package/dist/esm/src/utils/chartConnectionPoint.js +31 -16
- package/dist/esm/types/src/components/ui/AnalysesSelector/AnalysesSelector.d.ts +1 -1
- package/dist/esm/types/src/components/ui/AnalysesSelector/AnalysesSelector.types.d.ts +12 -0
- package/dist/esm/types/src/components/ui/AnalysesSelector/index.d.ts +1 -1
- package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +8 -0
- package/dist/esm/types/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.d.ts +8 -1
- package/dist/esm/types/src/components/ui/Chart/components/LegendSvg/LegendSvg.d.ts +2 -0
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.d.ts +1 -1
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.d.ts +5 -0
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +19 -1
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/chartHistories.d.ts +40 -0
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/index.d.ts +1 -0
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.d.ts +6 -1
- package/dist/esm/types/src/components/ui/Page/PageXScroll/PageXScroll.d.ts +1 -1
- package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.d.ts +3 -0
- package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.d.ts +65 -0
- package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.d.ts +20 -0
- package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.types.d.ts +85 -0
- package/dist/esm/types/src/components/ui/StackedAreaChart/index.d.ts +2 -0
- package/dist/esm/types/src/docs/pages/StackedAreaChartPage.d.ts +1 -0
- package/dist/esm/types/src/index.d.ts +1 -0
- package/dist/esm/types/src/utils/chartConnectionPoint.d.ts +11 -3
- package/dist/esm/types/tests/chartHistories.test.d.ts +1 -0
- package/dist/esm/types/tests/pageXScroll.test.d.ts +1 -0
- package/dist/esm/types/tests/stackedAreaChart.test.d.ts +1 -0
- package/package.json +1 -1
- package/src/components/ui/AnalysesSelector/AnalysesSelector.tsx +50 -22
- package/src/components/ui/AnalysesSelector/AnalysesSelector.types.ts +13 -0
- package/src/components/ui/AnalysesSelector/index.ts +1 -0
- package/src/components/ui/Chart/components/BaseChartWrapper.tsx +71 -52
- package/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.tsx +21 -1
- package/src/components/ui/Chart/components/LegendSvg/LegendSvg.tsx +3 -1
- package/src/components/ui/ChartAreaInteractive/AGENT.md +2 -0
- package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.ts +27 -5
- package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.tsx +64 -10
- package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +86 -30
- package/src/components/ui/ChartAreaInteractive/chartHistories.ts +63 -0
- package/src/components/ui/ChartAreaInteractive/index.ts +1 -0
- package/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.ts +52 -6
- package/src/components/ui/Page/AGENT.md +2 -0
- package/src/components/ui/Page/PageTabs/PageTabs.styl +8 -0
- package/src/components/ui/Page/PageXScroll/PageXScroll.tsx +57 -13
- package/src/components/ui/StackedAreaChart/AGENT.md +26 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.ts +268 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.styl +32 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.styl.d.ts +13 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.tsx +82 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.tsx +416 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.types.ts +97 -0
- package/src/components/ui/StackedAreaChart/index.ts +2 -0
- package/src/docs/pages/ChartAreaInteractivePage.tsx +67 -0
- package/src/docs/pages/StackedAreaChartPage.tsx +141 -0
- package/src/docs/registry.ts +6 -0
- package/src/index.ts +1 -0
- package/src/utils/chartConnectionPoint.ts +41 -18
- package/src/components/ui/Chart/chart-types.csv +0 -33
|
@@ -9,14 +9,21 @@ import { CHART_MARGINS } from './ChartAreaInteractive.constants.js';
|
|
|
9
9
|
import { filterDataForTimeRange, shortDateFormatter, longDateFormatter } from './ChartAreaInteractive.helpers.js';
|
|
10
10
|
import S from './ChartAreaInteractive.styl.js';
|
|
11
11
|
import { TimeRangeBrushHost } from './TimeRangeBrushLayer.js';
|
|
12
|
+
import { forecastHistoryKey } from './chartHistories.js';
|
|
12
13
|
import { PinOverlay } from './overlays/PinOverlay/PinOverlay.js';
|
|
13
14
|
import { IntervalsOverlay } from './overlays/IntervalsOverlay/IntervalsOverlay.js';
|
|
14
15
|
import { ThresholdsOverlay } from './overlays/ThresholdsOverlay/ThresholdsOverlay.js';
|
|
15
16
|
|
|
17
|
+
/** The bridge's `historyKeyFor`, from serialised {@link ForecastHistoryKeys}. */
|
|
18
|
+
function historyKeyLookup(serialised) {
|
|
19
|
+
const { byId, other } = JSON.parse(serialised);
|
|
20
|
+
const map = new Map(byId);
|
|
21
|
+
return id => (map.has(id) ? map.get(id) : other);
|
|
22
|
+
}
|
|
16
23
|
const chartConfig = {
|
|
17
24
|
// Chart now supports light/dark themes with dynamic colors
|
|
18
25
|
};
|
|
19
|
-
function ChartAreaInteractive({ className, chartContainerClassName, legendClassName, xAxisClassName, yAxisClassName, timeRange, onTimeRangeChange, pinMonth, onPinMonthChange, onPreviewMonthChange, chartData, forecastData, error, loading = false, isDarkTheme = false, footerActions, mode, selectedForecast, upperQuantiles, lowerQuantiles, selectedLowerQuantile, selectedUpperQuantile, onLowerQuantileChange, onUpperQuantileChange, lowerThreshold, upperThreshold, onLowerThresholdChange, onUpperThresholdChange, discreteThresholdValues, headerActions, excludeLegendIds, loadingAnalyses, onLegendClick, onAnalysisSelect, disableTimeRangeSelector, enableTimeRangeBrush = false, forecastLineStyle = 'dashed', selectedAnalysisId, chartRenderId, toggleLegendSeries, ensureAnalysisSeriesVisible, overlayForecastData = {}, hiddenSeries, disableForecastHistoricalBridge, overlayElements: overlayElementsProp, ...restProps }) {
|
|
26
|
+
function ChartAreaInteractive({ className, chartContainerClassName, legendClassName, xAxisClassName, yAxisClassName, timeRange, onTimeRangeChange, pinMonth, onPinMonthChange, onPreviewMonthChange, chartData, forecastData, historyData, error, loading = false, isDarkTheme = false, footerActions, mode, selectedForecast, upperQuantiles, lowerQuantiles, selectedLowerQuantile, selectedUpperQuantile, onLowerQuantileChange, onUpperQuantileChange, lowerThreshold, upperThreshold, onLowerThresholdChange, onUpperThresholdChange, discreteThresholdValues, headerActions, excludeLegendIds, loadingAnalyses, onLegendClick, onAnalysisSelect, disableTimeRangeSelector, enableTimeRangeBrush = false, forecastLineStyle = 'dashed', selectedAnalysisId, chartRenderId, toggleLegendSeries, ensureAnalysisSeriesVisible, overlayForecastData = {}, hiddenSeries, disableForecastHistoricalBridge, overlayElements: overlayElementsProp, ...restProps }) {
|
|
20
27
|
const seriesHidden = hiddenSeries ?? new Set();
|
|
21
28
|
const hiddenSeriesRef = useRef(seriesHidden);
|
|
22
29
|
const prevSelectedAnalysisIdRef = useRef(selectedAnalysisId);
|
|
@@ -39,25 +46,47 @@ function ChartAreaInteractive({ className, chartContainerClassName, legendClassN
|
|
|
39
46
|
ensureAnalysisSeriesVisible(selectedAnalysisId);
|
|
40
47
|
}
|
|
41
48
|
}, [selectedAnalysisId, ensureAnalysisSeriesVisible]);
|
|
42
|
-
const
|
|
49
|
+
const anchorAnalysisId = useMemo(() => {
|
|
43
50
|
const raw = selectedAnalysisId ?? selectedForecast?.id ?? null;
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
51
|
+
const id = raw == null ? null : typeof raw === 'number' ? raw : Number(raw);
|
|
52
|
+
return id != null && Number.isFinite(id) ? id : null;
|
|
53
|
+
}, [selectedAnalysisId, selectedForecast?.id]);
|
|
54
|
+
// The history the anchored forecast joins, as a string, so the time filter
|
|
55
|
+
// does not rerun when the host passes new but equal arrays.
|
|
56
|
+
const anchorHistoryKey = useMemo(() => anchorAnalysisId == null
|
|
57
|
+
? undefined
|
|
58
|
+
: forecastHistoryKey(forecastData?.find(f => f.id === anchorAnalysisId), historyData), [anchorAnalysisId, forecastData, historyData]);
|
|
59
|
+
const timeFilteredChartData = useMemo(() => {
|
|
60
|
+
const anchorForecastLoaded = anchorAnalysisId != null &&
|
|
47
61
|
chartData.some(row => {
|
|
48
|
-
const value = row[`forecast_${
|
|
62
|
+
const value = row[`forecast_${anchorAnalysisId}`];
|
|
49
63
|
return typeof value === 'number' && Number.isFinite(value);
|
|
50
64
|
});
|
|
51
|
-
const opts =
|
|
52
|
-
? { endDateAnchorAnalysisId:
|
|
65
|
+
const opts = anchorAnalysisId != null && anchorForecastLoaded
|
|
66
|
+
? { endDateAnchorAnalysisId: anchorAnalysisId, anchorHistoryKey }
|
|
53
67
|
: undefined;
|
|
54
68
|
return filterDataForTimeRange(chartData, timeRange, opts);
|
|
55
|
-
}, [chartData, timeRange,
|
|
69
|
+
}, [chartData, timeRange, anchorAnalysisId, anchorHistoryKey]);
|
|
70
|
+
// Which history each forecast joins, as a string, so the bridge does not
|
|
71
|
+
// rerun when the host passes a new but equal historyData array.
|
|
72
|
+
const forecastHistoryKeys = useMemo(() => JSON.stringify({
|
|
73
|
+
byId: (forecastData ?? []).map(f => [
|
|
74
|
+
f.id,
|
|
75
|
+
forecastHistoryKey(f, historyData),
|
|
76
|
+
]),
|
|
77
|
+
other: forecastHistoryKey(undefined, historyData),
|
|
78
|
+
}), [forecastData, historyData]);
|
|
56
79
|
const bridgedChartData = useMemo(() => disableForecastHistoricalBridge
|
|
57
80
|
? timeFilteredChartData
|
|
58
81
|
: ensureChartForecastBridge(timeFilteredChartData, {
|
|
59
82
|
forecastSeriesIds: forecastData?.map(f => f.id),
|
|
60
|
-
|
|
83
|
+
historyKeyFor: historyKeyLookup(forecastHistoryKeys),
|
|
84
|
+
}), [
|
|
85
|
+
timeFilteredChartData,
|
|
86
|
+
disableForecastHistoricalBridge,
|
|
87
|
+
forecastData,
|
|
88
|
+
forecastHistoryKeys,
|
|
89
|
+
]);
|
|
61
90
|
// Extract quantileBands from restProps
|
|
62
91
|
// const quantileBands = (restProps as any).quantileBands;
|
|
63
92
|
const getLoadingMessage = () => {
|
|
@@ -77,6 +106,7 @@ function ChartAreaInteractive({ className, chartContainerClassName, legendClassN
|
|
|
77
106
|
xAxisClassName,
|
|
78
107
|
yAxisClassName,
|
|
79
108
|
chartData: bridgedChartData,
|
|
109
|
+
historyData,
|
|
80
110
|
chartClassName: S.chartContainer,
|
|
81
111
|
// chartClassName: cn(S.chartContainer, chartContainerClassName),
|
|
82
112
|
legendClassName,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
|
|
2
2
|
import { memo, useMemo } from 'react';
|
|
3
3
|
import { Line } from 'recharts';
|
|
4
|
+
import { HISTORY_SERIES_KEY, historySeriesKey } from './chartHistories.js';
|
|
4
5
|
|
|
5
6
|
const ANIMATION_DURATION = 300;
|
|
6
7
|
// Colors for different forecast series
|
|
@@ -17,13 +18,26 @@ const FORECAST_COLORS_MAP = {
|
|
|
17
18
|
const FORECAST_LINE_COLORS = Object.keys(FORECAST_COLORS_MAP);
|
|
18
19
|
const getForecastColor = (index) => FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length];
|
|
19
20
|
const getForecastQuantileBandColor = (index) => FORECAST_COLORS_MAP[FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length]];
|
|
21
|
+
/** Default colour of the history at `index`: the forecast palette from its far end. */
|
|
22
|
+
function getHistoryColor(index) {
|
|
23
|
+
const n = FORECAST_LINE_COLORS.length;
|
|
24
|
+
return FORECAST_LINE_COLORS[n - 1 - (index % n)];
|
|
25
|
+
}
|
|
26
|
+
/** `historyData` with the defaults applied, in order (empty without it). */
|
|
27
|
+
function resolveHistoryLines(histories) {
|
|
28
|
+
return (histories ?? []).map((h, index) => ({
|
|
29
|
+
dataKey: historySeriesKey(h.id),
|
|
30
|
+
name: h.name || String(h.id),
|
|
31
|
+
color: h.color ?? getHistoryColor(index),
|
|
32
|
+
}));
|
|
33
|
+
}
|
|
20
34
|
/** Same tint logic as intervals/threshold overlays: band fill follows forecast line hex when known. */
|
|
21
35
|
function resolveQuantileBandFillForForecastLine(lineColor, forecastIndex) {
|
|
22
36
|
const mapped = FORECAST_COLORS_MAP[lineColor];
|
|
23
37
|
return mapped ?? getForecastQuantileBandColor(forecastIndex);
|
|
24
38
|
}
|
|
25
39
|
// Memoized component for chart lines - only re-renders when data/analyses/hiddenSeries change
|
|
26
|
-
const ChartLines = memo(({ chartData, forecastData, hiddenSeries, isDarkTheme, shouldAnimate, historicalLineColor = isDarkTheme ? '#ffffff' : '#000000', showLegend = true, forecastLineStyle = 'dashed', disableAnimation = false, disableHistoricalAnimation = false, }) => {
|
|
40
|
+
const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, isDarkTheme, shouldAnimate, historicalLineColor = isDarkTheme ? '#ffffff' : '#000000', showLegend = true, forecastLineStyle = 'dashed', disableAnimation = false, disableHistoricalAnimation = false, }) => {
|
|
27
41
|
const dotStroke = isDarkTheme ? '#000000' : '#FFFFFF';
|
|
28
42
|
const activeDotHistorical = {
|
|
29
43
|
r: 6,
|
|
@@ -37,16 +51,32 @@ const ChartLines = memo(({ chartData, forecastData, hiddenSeries, isDarkTheme, s
|
|
|
37
51
|
...activeDotHistorical,
|
|
38
52
|
fill: color,
|
|
39
53
|
});
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
54
|
+
// One entry per history line: the single `historical` line, or one per
|
|
55
|
+
// `historyData` item under `historical_<id>`.
|
|
56
|
+
const historyLines = useMemo(() => historyData?.length
|
|
57
|
+
? resolveHistoryLines(historyData)
|
|
58
|
+
: [
|
|
59
|
+
{
|
|
60
|
+
dataKey: HISTORY_SERIES_KEY,
|
|
61
|
+
name: 'Historical Data',
|
|
62
|
+
color: historicalLineColor,
|
|
63
|
+
},
|
|
64
|
+
], [historyData, historicalLineColor]);
|
|
65
|
+
// Memoize last index per history line to avoid recalculating on every render call
|
|
66
|
+
const lastHistoryIndices = useMemo(() => {
|
|
67
|
+
const indices = {};
|
|
68
|
+
historyLines.forEach(({ dataKey }) => {
|
|
69
|
+
indices[dataKey] = -1;
|
|
70
|
+
for (let i = chartData.length - 1; i >= 0; i--) {
|
|
71
|
+
const value = chartData[i][dataKey];
|
|
72
|
+
if (value !== undefined && value !== null) {
|
|
73
|
+
indices[dataKey] = i;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
46
76
|
}
|
|
47
|
-
}
|
|
48
|
-
return
|
|
49
|
-
}, [chartData]);
|
|
77
|
+
});
|
|
78
|
+
return indices;
|
|
79
|
+
}, [chartData, historyLines]);
|
|
50
80
|
// Memoize last forecast indices per forecast ID
|
|
51
81
|
const lastForecastIndices = useMemo(() => {
|
|
52
82
|
const indices = {};
|
|
@@ -73,14 +103,14 @@ const ChartLines = memo(({ chartData, forecastData, hiddenSeries, isDarkTheme, s
|
|
|
73
103
|
}
|
|
74
104
|
return null;
|
|
75
105
|
};
|
|
76
|
-
const
|
|
106
|
+
const renderHistoryDot = (props, dataKey, color) => renderDot(props, lastHistoryIndices[dataKey] ?? -1, dataKey, color);
|
|
77
107
|
const renderForecastDot = (props, id, color) => renderDot(props, lastForecastIndices[id] ?? -1, `forecast_${id}`, color);
|
|
78
108
|
const animationActive = Boolean(shouldAnimate) && !disableAnimation;
|
|
79
109
|
const historicalAnimationActive = animationActive && !disableHistoricalAnimation;
|
|
80
110
|
const forecastAnimationActive = animationActive;
|
|
81
111
|
const animationDuration = disableAnimation ? 0 : ANIMATION_DURATION;
|
|
82
112
|
const valueAnimationEnabled = !disableAnimation;
|
|
83
|
-
return (jsxs(Fragment, { children: [jsx(Line, { type: "monotone", dataKey:
|
|
113
|
+
return (jsxs(Fragment, { children: [historyLines.map(({ dataKey, name, color }) => (jsx(Line, { type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1, dot: props => renderHistoryDot(props, dataKey, color), activeDot: { ...activeDotHistorical, fill: color }, name: name, legendType: showLegend === false ? 'none' : undefined, strokeDasharray: "0", hide: hiddenSeries?.has(dataKey), isAnimationActive: historicalAnimationActive, animationDuration: animationDuration, animateNewValues: valueAnimationEnabled, animationBegin: 0, animationEasing: "ease-out" }, dataKey))), forecastData?.map((data, index) => {
|
|
84
114
|
const { id, name, color = FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length], } = data;
|
|
85
115
|
const dataKey = `forecast_${id}`;
|
|
86
116
|
return (jsx(Line, { type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1, strokeDasharray: forecastLineStyle === 'dashed' ? '4 2' : '0', dot: props => renderForecastDot(props, id, color), activeDot: activeDotForecast(color), name: `${name || `${id}`}`, legendType: showLegend === false ? 'none' : undefined, 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}`));
|
|
@@ -88,4 +118,4 @@ const ChartLines = memo(({ chartData, forecastData, hiddenSeries, isDarkTheme, s
|
|
|
88
118
|
});
|
|
89
119
|
ChartLines.displayName = 'ChartLines';
|
|
90
120
|
|
|
91
|
-
export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, resolveQuantileBandFillForForecastLine };
|
|
121
|
+
export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, getHistoryColor, resolveHistoryLines, resolveQuantileBandFillForForecastLine };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Several history lines in one chart (one per product).
|
|
3
|
+
*
|
|
4
|
+
* Without `historyData` a chart has one history line under the `historical`
|
|
5
|
+
* key, and every forecast joins it. With `historyData`, each history has its
|
|
6
|
+
* own line under `historical_<id>`, and a forecast joins a history only when
|
|
7
|
+
* it can say which one: its `continues` names the history, or the chart has
|
|
8
|
+
* exactly one. Otherwise the forecast starts on its own first point.
|
|
9
|
+
*/
|
|
10
|
+
/** The single history line's key, when the chart has no `historyData`. */
|
|
11
|
+
const HISTORY_SERIES_KEY = 'historical';
|
|
12
|
+
/** Data key of one history line in `chartData` rows. */
|
|
13
|
+
function historySeriesKey(id) {
|
|
14
|
+
return `${HISTORY_SERIES_KEY}_${id}`;
|
|
15
|
+
}
|
|
16
|
+
/** True for `historical` and for every `historical_<id>` key. */
|
|
17
|
+
function isHistorySeriesKey(key) {
|
|
18
|
+
return key === HISTORY_SERIES_KEY || key.startsWith(`${HISTORY_SERIES_KEY}_`);
|
|
19
|
+
}
|
|
20
|
+
/** The data keys of the chart's history lines, in order. */
|
|
21
|
+
function historySeriesKeys(histories) {
|
|
22
|
+
return histories?.length
|
|
23
|
+
? histories.map(h => historySeriesKey(h.id))
|
|
24
|
+
: [HISTORY_SERIES_KEY];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The history line a forecast joins, or null when it joins none.
|
|
28
|
+
*
|
|
29
|
+
* - No `historyData`: the single `historical` line, as before.
|
|
30
|
+
* - `continues` set: that history, or none when no history has that id.
|
|
31
|
+
* - Otherwise: the only history when there is exactly one, else none.
|
|
32
|
+
*/
|
|
33
|
+
function forecastHistoryKey(forecast, histories) {
|
|
34
|
+
if (!histories?.length)
|
|
35
|
+
return HISTORY_SERIES_KEY;
|
|
36
|
+
const continues = forecast?.continues;
|
|
37
|
+
if (continues != null) {
|
|
38
|
+
const match = histories.find(h => String(h.id) === String(continues));
|
|
39
|
+
return match ? historySeriesKey(match.id) : null;
|
|
40
|
+
}
|
|
41
|
+
return histories.length === 1 ? historySeriesKey(histories[0].id) : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { HISTORY_SERIES_KEY, forecastHistoryKey, historySeriesKey, historySeriesKeys, isHistorySeriesKey };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { useRef, useMemo } from 'react';
|
|
2
|
+
import { forecastHistoryKey, isHistorySeriesKey } from '../chartHistories.js';
|
|
2
3
|
|
|
3
4
|
/** Serialize hidden series keys for stable cache comparison. */
|
|
4
5
|
function serializeHiddenSeries(hiddenSeries) {
|
|
@@ -12,8 +13,8 @@ function serializeHiddenSeries(hiddenSeries) {
|
|
|
12
13
|
function isKeyExcludedFromYScale(key, hiddenSeries) {
|
|
13
14
|
if (!hiddenSeries || hiddenSeries.size === 0)
|
|
14
15
|
return false;
|
|
15
|
-
if (key
|
|
16
|
-
return hiddenSeries.has(
|
|
16
|
+
if (isHistorySeriesKey(key)) {
|
|
17
|
+
return hiddenSeries.has(key);
|
|
17
18
|
}
|
|
18
19
|
if (key.startsWith('forecast_')) {
|
|
19
20
|
return hiddenSeries.has(key);
|
|
@@ -29,7 +30,7 @@ function isKeyExcludedFromYScale(key, hiddenSeries) {
|
|
|
29
30
|
return false;
|
|
30
31
|
}
|
|
31
32
|
/** Pure Y-range calculation from chart data points. */
|
|
32
|
-
function calculateChartYRange(dataToUse, { excludeQuantileBands, forecastId, hiddenSeries, includeHiddenInYScale = false, }) {
|
|
33
|
+
function calculateChartYRange(dataToUse, { excludeQuantileBands, forecastId, forecastHistoryKey, hiddenSeries, includeHiddenInYScale = false, }) {
|
|
33
34
|
const allValues = [];
|
|
34
35
|
dataToUse.forEach(point => {
|
|
35
36
|
Object.entries(point).forEach(([key, value]) => {
|
|
@@ -44,6 +45,10 @@ function calculateChartYRange(dataToUse, { excludeQuantileBands, forecastId, hid
|
|
|
44
45
|
if (forecastId !== undefined) {
|
|
45
46
|
if (key.startsWith('forecast_') && key !== `forecast_${forecastId}`)
|
|
46
47
|
return;
|
|
48
|
+
if (forecastHistoryKey !== undefined &&
|
|
49
|
+
isHistorySeriesKey(key) &&
|
|
50
|
+
key !== forecastHistoryKey)
|
|
51
|
+
return;
|
|
47
52
|
// Exclude q{quantile}_{otherAnalysisId} - only include selected forecast's quantiles
|
|
48
53
|
if (key.startsWith('q') && !key.endsWith(`_${forecastId}`))
|
|
49
54
|
return;
|
|
@@ -86,8 +91,16 @@ function calculateChartYRange(dataToUse, { excludeQuantileBands, forecastId, hid
|
|
|
86
91
|
if (allValues.length === 0) {
|
|
87
92
|
return { yMin: 0, yMax: 100 };
|
|
88
93
|
}
|
|
89
|
-
|
|
90
|
-
|
|
94
|
+
// A loop, not Math.min(...values): one value per row and line can exceed
|
|
95
|
+
// the engine's argument limit.
|
|
96
|
+
let min = Infinity;
|
|
97
|
+
let max = -Infinity;
|
|
98
|
+
for (const v of allValues) {
|
|
99
|
+
if (v < min)
|
|
100
|
+
min = v;
|
|
101
|
+
if (v > max)
|
|
102
|
+
max = v;
|
|
103
|
+
}
|
|
91
104
|
const diff = max - min;
|
|
92
105
|
return {
|
|
93
106
|
yMin: min - diff * 0.1,
|
|
@@ -105,9 +118,15 @@ function useChartYRange({ baseChartProps, chartData, disableRescaleWhenQuantileC
|
|
|
105
118
|
const stableYRangeRef = useRef(null);
|
|
106
119
|
const prevBaseChartDataRef = useRef(baseChartProps.chartData);
|
|
107
120
|
const prevHiddenSeriesKeyRef = useRef(serializeHiddenSeries(hiddenSeries));
|
|
121
|
+
// With several histories, the selected forecast scales with its own only.
|
|
122
|
+
const { forecastData, historyData } = baseChartProps;
|
|
123
|
+
const selectedHistoryKey = useMemo(() => selectedForecastId !== undefined && historyData?.length
|
|
124
|
+
? forecastHistoryKey(forecastData?.find(f => f.id === selectedForecastId), historyData)
|
|
125
|
+
: undefined, [selectedForecastId, forecastData, historyData]);
|
|
108
126
|
const calculateYRange = (dataToUse, excludeBands, forecastId) => calculateChartYRange(dataToUse, {
|
|
109
127
|
excludeQuantileBands: excludeBands,
|
|
110
128
|
forecastId,
|
|
129
|
+
forecastHistoryKey: forecastId === selectedForecastId ? selectedHistoryKey : undefined,
|
|
111
130
|
hiddenSeries,
|
|
112
131
|
includeHiddenInYScale,
|
|
113
132
|
});
|
|
@@ -130,7 +149,8 @@ function useChartYRange({ baseChartProps, chartData, disableRescaleWhenQuantileC
|
|
|
130
149
|
prevBaseChartDataRef.current = baseChartProps.chartData;
|
|
131
150
|
stableYRangeRef.current = null;
|
|
132
151
|
}
|
|
133
|
-
if (stableYRangeRef.current?.forecastId !== selectedForecastId
|
|
152
|
+
if (stableYRangeRef.current?.forecastId !== selectedForecastId ||
|
|
153
|
+
stableYRangeRef.current?.historyKey !== selectedHistoryKey) {
|
|
134
154
|
stableYRangeRef.current = null;
|
|
135
155
|
}
|
|
136
156
|
const hiddenSeriesKey = serializeHiddenSeries(hiddenSeries);
|
|
@@ -150,6 +170,7 @@ function useChartYRange({ baseChartProps, chartData, disableRescaleWhenQuantileC
|
|
|
150
170
|
stableYRangeRef.current = {
|
|
151
171
|
...result,
|
|
152
172
|
forecastId: selectedForecastId,
|
|
173
|
+
historyKey: selectedHistoryKey,
|
|
153
174
|
};
|
|
154
175
|
}
|
|
155
176
|
return result;
|
|
@@ -163,6 +184,7 @@ function useChartYRange({ baseChartProps, chartData, disableRescaleWhenQuantileC
|
|
|
163
184
|
selectedForecastId,
|
|
164
185
|
hiddenSeries,
|
|
165
186
|
includeHiddenInYScale,
|
|
187
|
+
selectedHistoryKey,
|
|
166
188
|
]);
|
|
167
189
|
// When disableRescaleWhenQuantileChanges is false, calculate from transformed data
|
|
168
190
|
const dynamicRange = useMemo(() => {
|
|
@@ -188,11 +210,14 @@ function useChartYRange({ baseChartProps, chartData, disableRescaleWhenQuantileC
|
|
|
188
210
|
selectedForecastId,
|
|
189
211
|
hiddenSeries,
|
|
190
212
|
includeHiddenInYScale,
|
|
213
|
+
selectedHistoryKey,
|
|
191
214
|
]);
|
|
192
215
|
// Return appropriate range
|
|
193
216
|
if (disableRescaleWhenQuantileChanges) {
|
|
194
217
|
const cached = stableYRangeRef.current;
|
|
195
|
-
const cachedMatchesForecast = cached &&
|
|
218
|
+
const cachedMatchesForecast = cached &&
|
|
219
|
+
cached.forecastId === selectedForecastId &&
|
|
220
|
+
cached.historyKey === selectedHistoryKey;
|
|
196
221
|
return cachedMatchesForecast
|
|
197
222
|
? { yMin: cached.yMin, yMax: cached.yMax }
|
|
198
223
|
: (stableRange ?? { yMin: 0, yMax: 100 });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import styleInject from 'style-inject';
|
|
2
2
|
|
|
3
|
-
var css_248z = ".PageTabs_root__0c-ao{gap:var(--p-6);margin-bottom:var(--p-10);max-width:100%;width:var(--page-width)}.PageTabs_scrollbar__-2Uze{max-height:12px}.PageTabs_list__fNzQB{max-width:100%}.PageTabs_list__fNzQB.PageTabs_withPaddings__pt93u{padding-left:var(--page-x-padding);padding-right:var(--page-x-padding)}.PageTabs_variant-button__3oueI .PageTabs_listInner__cZ4lf,.PageTabs_variant-outline__vdIR7 .PageTabs_listInner__cZ4lf{gap:var(--p-2)}.PageTabs_content__6XOr3{display:flex;flex-direction:column;position:relative}.PageTabs_content__6XOr3[hidden]{display:none!important}";
|
|
4
|
-
var S = {"root":"PageTabs_root__0c-ao","scrollbar":"PageTabs_scrollbar__-2Uze","list":"PageTabs_list__fNzQB","withPaddings":"PageTabs_withPaddings__pt93u","variant-button":"PageTabs_variant-button__3oueI","
|
|
3
|
+
var css_248z = ".PageTabs_root__0c-ao{gap:var(--p-6);margin-bottom:var(--p-10);max-width:100%;width:var(--page-width)}.PageTabs_scrollbar__-2Uze{max-height:12px}.PageTabs_list__fNzQB{max-width:100%}.PageTabs_list__fNzQB.PageTabs_withPaddings__pt93u{padding-left:var(--page-x-padding);padding-right:var(--page-x-padding)}.PageTabs_listInner__cZ4lf{--focus-outline-offset:calc(var(--focus-outline-width, 2px)*-1 - 2px)}.PageTabs_variant-button__3oueI .PageTabs_listInner__cZ4lf,.PageTabs_variant-outline__vdIR7 .PageTabs_listInner__cZ4lf{gap:var(--p-2)}.PageTabs_content__6XOr3{display:flex;flex-direction:column;position:relative}.PageTabs_content__6XOr3[hidden]{display:none!important}";
|
|
4
|
+
var S = {"root":"PageTabs_root__0c-ao","scrollbar":"PageTabs_scrollbar__-2Uze","list":"PageTabs_list__fNzQB","withPaddings":"PageTabs_withPaddings__pt93u","listInner":"PageTabs_listInner__cZ4lf","variant-button":"PageTabs_variant-button__3oueI","variant-outline":"PageTabs_variant-outline__vdIR7","content":"PageTabs_content__6XOr3"};
|
|
5
5
|
styleInject(css_248z);
|
|
6
6
|
|
|
7
7
|
export { S as default };
|
|
@@ -1,34 +1,69 @@
|
|
|
1
1
|
import { jsx } from 'react/jsx-runtime';
|
|
2
|
-
import { useState, useEffect } from 'react';
|
|
2
|
+
import { useState, useRef, useCallback, useEffect } from 'react';
|
|
3
3
|
import S from './PageXScroll.styl.js';
|
|
4
4
|
import { Scroll } from '@homecode/ui';
|
|
5
5
|
import cn from 'classnames';
|
|
6
6
|
|
|
7
|
+
/** The inset used until the row has been measured (on the server, and on the
|
|
8
|
+
* first client render). */
|
|
9
|
+
const DEFAULT_PAGE_X_PADDING = 24;
|
|
10
|
+
/**
|
|
11
|
+
* The page's side padding as the cascade resolves it for this row, in px: the
|
|
12
|
+
* width of the spacer `.inner::before` draws, which is `var(--page-x-padding)`.
|
|
13
|
+
* Reading the spacer, not the variable on `:root`, means an app that sets
|
|
14
|
+
* `--page-x-padding` on any ancestor of the row (or inside a media query)
|
|
15
|
+
* gets the same inset in the scrollbar and fade as in the spacers.
|
|
16
|
+
* Null when the spacer's width is not a length in px (it is not laid out, or
|
|
17
|
+
* a consumer's style gave it something else).
|
|
18
|
+
*/
|
|
19
|
+
function readPageXPadding(inner) {
|
|
20
|
+
const { width } = getComputedStyle(inner, '::before');
|
|
21
|
+
return /^\d+(\.\d+)?px$/.test(width) ? parseFloat(width) : null;
|
|
22
|
+
}
|
|
7
23
|
const scrollSizeMap = {
|
|
8
24
|
sm: 's',
|
|
9
25
|
md: 'm',
|
|
10
26
|
lg: 'l',
|
|
11
27
|
};
|
|
12
|
-
function PageXScroll({ children, className, innerClassName, scrollbarClassName, fullWidth = false, size = 'md', scrollbarOffset, ...props }) {
|
|
13
|
-
const [pageXPadding, setPageXPadding] = useState(
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (value) {
|
|
20
|
-
// Convert rem/px to number (assuming px, if rem multiply by 16)
|
|
21
|
-
const numValue = parseFloat(value);
|
|
22
|
-
setPageXPadding(value.includes('rem') ? numValue * 16 : numValue);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
28
|
+
function PageXScroll({ children, className, innerClassName, scrollbarClassName, fullWidth = false, size = 'md', scrollbarOffset, onInnerRef, ...props }) {
|
|
29
|
+
const [pageXPadding, setPageXPadding] = useState(DEFAULT_PAGE_X_PADDING);
|
|
30
|
+
const innerRef = useRef(null);
|
|
31
|
+
const measure = useCallback(() => {
|
|
32
|
+
const width = innerRef.current && readPageXPadding(innerRef.current);
|
|
33
|
+
if (typeof width === 'number')
|
|
34
|
+
setPageXPadding(width);
|
|
25
35
|
}, []);
|
|
36
|
+
// The caller's callback is read through a ref, so an inline one does not hand
|
|
37
|
+
// Scroll a new handler (and make it observe the row again) on every render.
|
|
38
|
+
const onInnerRefRef = useRef(onInnerRef);
|
|
39
|
+
onInnerRefRef.current = onInnerRef;
|
|
40
|
+
// Measure when Scroll hands the row over, so the order of the effects does
|
|
41
|
+
// not matter.
|
|
42
|
+
const handleInnerRef = useCallback((el) => {
|
|
43
|
+
innerRef.current = el;
|
|
44
|
+
measure();
|
|
45
|
+
onInnerRefRef.current?.(el);
|
|
46
|
+
}, [measure]);
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
// A media query can change `--page-x-padding` when the window is resized.
|
|
49
|
+
// Measuring forces a style recalculation, so once per frame at most.
|
|
50
|
+
let frame = 0;
|
|
51
|
+
const onResize = () => {
|
|
52
|
+
cancelAnimationFrame(frame);
|
|
53
|
+
frame = requestAnimationFrame(measure);
|
|
54
|
+
};
|
|
55
|
+
window.addEventListener('resize', onResize);
|
|
56
|
+
return () => {
|
|
57
|
+
window.removeEventListener('resize', onResize);
|
|
58
|
+
cancelAnimationFrame(frame);
|
|
59
|
+
};
|
|
60
|
+
}, [measure]);
|
|
26
61
|
return (jsx(Scroll, { x: true, size: scrollSizeMap[size], fadeSize: "xl", className: cn(className, S.root, fullWidth && S.fullWidth), innerClassName: cn(innerClassName, S.inner), xScrollbarClassName: scrollbarClassName, offset: {
|
|
27
62
|
x: {
|
|
28
63
|
before: pageXPadding + (scrollbarOffset?.x?.before ?? 0),
|
|
29
64
|
after: pageXPadding + (scrollbarOffset?.x?.after ?? 0),
|
|
30
65
|
},
|
|
31
|
-
}, autoHide: true, ...props, children: children }));
|
|
66
|
+
}, autoHide: true, onInnerRef: handleInnerRef, ...props, children: children }));
|
|
32
67
|
}
|
|
33
68
|
|
|
34
69
|
export { PageXScroll };
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/** Data key of the margin layer. Prefixed so it cannot clash with a layer key. */
|
|
2
|
+
const MARGIN_KEY = '__margin';
|
|
3
|
+
/** 1 when a row from {@link stackRows} has a value for any stacked layer, else 0. */
|
|
4
|
+
const COST_KNOWN_KEY = '__costKnown';
|
|
5
|
+
const num = (v) => typeof v === 'number' && Number.isFinite(v) ? v : null;
|
|
6
|
+
/** Sum of the layers on a row; a missing value counts as 0. */
|
|
7
|
+
function layersTotal(row, layerKeys) {
|
|
8
|
+
let sum = 0;
|
|
9
|
+
for (const key of layerKeys)
|
|
10
|
+
sum += num(row[key]) ?? 0;
|
|
11
|
+
return sum;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Rows ready to stack: every missing layer value becomes 0, and the margin
|
|
15
|
+
* layer (`MARGIN_KEY`) is `pct` percent of the total of `totalKeys` (the
|
|
16
|
+
* layers that are drawn; all layers by default). Without a positive `pct`
|
|
17
|
+
* the margin key is 0, so the layer can stay mounted. `COST_KNOWN_KEY` says
|
|
18
|
+
* whether any of `totalKeys` had a value, so a row with no cost at all is
|
|
19
|
+
* not compared as a cost of 0.
|
|
20
|
+
*/
|
|
21
|
+
function stackRows(rows, layerKeys, marginPct, totalKeys = layerKeys) {
|
|
22
|
+
const pct = num(marginPct);
|
|
23
|
+
return rows.map(row => {
|
|
24
|
+
const next = { ...row };
|
|
25
|
+
for (const key of layerKeys)
|
|
26
|
+
next[key] = num(row[key]) ?? 0;
|
|
27
|
+
next[COST_KNOWN_KEY] = totalKeys.some(key => num(row[key]) != null) ? 1 : 0;
|
|
28
|
+
next[MARGIN_KEY] =
|
|
29
|
+
pct != null && pct > 0 ? layersTotal(next, totalKeys) * (pct / 100) : 0;
|
|
30
|
+
return next;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Each layer's share of the total, in whole percent, at the last row where
|
|
35
|
+
* every layer has a value and the total is above zero; when no row is
|
|
36
|
+
* complete, at the last row with a total. A negative value counts as 0.
|
|
37
|
+
* Rounded by largest remainder, so the shares add up to 100. All zeros when
|
|
38
|
+
* no row has a total.
|
|
39
|
+
*/
|
|
40
|
+
function stackWeights(rows, layerKeys) {
|
|
41
|
+
const positive = (row, key) => Math.max(num(row[key]) ?? 0, 0);
|
|
42
|
+
const totalOf = (row) => layerKeys.reduce((sum, key) => sum + positive(row, key), 0);
|
|
43
|
+
const isComplete = (row) => layerKeys.every(key => num(row[key]) != null);
|
|
44
|
+
let row;
|
|
45
|
+
for (let i = rows.length - 1; i >= 0 && !row; i--) {
|
|
46
|
+
if (isComplete(rows[i]) && totalOf(rows[i]) > 0)
|
|
47
|
+
row = rows[i];
|
|
48
|
+
}
|
|
49
|
+
for (let i = rows.length - 1; i >= 0 && !row; i--) {
|
|
50
|
+
if (totalOf(rows[i]) > 0)
|
|
51
|
+
row = rows[i];
|
|
52
|
+
}
|
|
53
|
+
if (!row)
|
|
54
|
+
return Object.fromEntries(layerKeys.map(key => [key, 0]));
|
|
55
|
+
const total = totalOf(row);
|
|
56
|
+
const shares = layerKeys.map(key => {
|
|
57
|
+
const exact = (positive(row, key) / total) * 100;
|
|
58
|
+
return { key, whole: Math.floor(exact), rest: exact - Math.floor(exact) };
|
|
59
|
+
});
|
|
60
|
+
let left = 100 - shares.reduce((sum, share) => sum + share.whole, 0);
|
|
61
|
+
for (const share of [...shares].sort((x, y) => y.rest - x.rest)) {
|
|
62
|
+
if (left <= 0)
|
|
63
|
+
break;
|
|
64
|
+
share.whole += 1;
|
|
65
|
+
left -= 1;
|
|
66
|
+
}
|
|
67
|
+
return Object.fromEntries(shares.map(share => [share.key, share.whole]));
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The compare values with gaps between two known values filled in a straight
|
|
71
|
+
* line by row, as the chart draws them (the overlays are linear lines). Rows before the first and after the
|
|
72
|
+
* last known value stay null.
|
|
73
|
+
*/
|
|
74
|
+
function bridgedValues(rows, key) {
|
|
75
|
+
const values = rows.map(row => num(row[key]));
|
|
76
|
+
let prev = -1;
|
|
77
|
+
for (let i = 0; i < values.length; i++) {
|
|
78
|
+
const value = values[i];
|
|
79
|
+
if (value == null)
|
|
80
|
+
continue;
|
|
81
|
+
if (prev >= 0 && i - prev > 1) {
|
|
82
|
+
const from = values[prev];
|
|
83
|
+
for (let j = prev + 1; j < i; j++) {
|
|
84
|
+
values[j] = from + ((value - from) * (j - prev)) / (i - prev);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
prev = i;
|
|
88
|
+
}
|
|
89
|
+
return values;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The x ranges where the compare line is above or below the stacked total
|
|
93
|
+
* (the given layers plus the margin on rows from {@link stackRows}). Gaps in
|
|
94
|
+
* the compare line are bridged as the line is drawn; a row with no cost is
|
|
95
|
+
* on neither side. Each run of rows on one side becomes a range from its first
|
|
96
|
+
* row to the row after it (where the side changes), so adjacent ranges meet
|
|
97
|
+
* on a row; a row where the line touches the stack starts the next range.
|
|
98
|
+
* Ranges are whole rows: a crossing between two rows shows at the next, and a
|
|
99
|
+
* run of one row with no compared row after it has no width and is left out.
|
|
100
|
+
* Meant for a point-scale x axis, where a range starts and ends on its rows.
|
|
101
|
+
*/
|
|
102
|
+
function compareZones(rows, xKey, layerKeys, compareKey) {
|
|
103
|
+
const sides = compareSides(rows, layerKeys, compareKey);
|
|
104
|
+
const xOf = (i) => rows[i][xKey];
|
|
105
|
+
const zones = [];
|
|
106
|
+
let i = 0;
|
|
107
|
+
while (i < sides.length) {
|
|
108
|
+
const kind = sides[i];
|
|
109
|
+
if (kind !== 'above' && kind !== 'below') {
|
|
110
|
+
i++;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
let end = i;
|
|
114
|
+
while (end + 1 < sides.length && sides[end + 1] === kind)
|
|
115
|
+
end++;
|
|
116
|
+
const first = sides[i - 1] === 'equal' ? i - 1 : i;
|
|
117
|
+
const last = end + 1 < sides.length && sides[end + 1] != null ? end + 1 : end;
|
|
118
|
+
if (first !== last)
|
|
119
|
+
zones.push({ x1: xOf(first), x2: xOf(last), kind });
|
|
120
|
+
i = end + 1;
|
|
121
|
+
}
|
|
122
|
+
return zones;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* One zone per row on the side the compare line is on (x1 === x2), for a
|
|
126
|
+
* chart that draws each row as its own bar.
|
|
127
|
+
*/
|
|
128
|
+
function compareRowZones(rows, xKey, layerKeys, compareKey) {
|
|
129
|
+
const sides = compareSides(rows, layerKeys, compareKey);
|
|
130
|
+
const zones = [];
|
|
131
|
+
sides.forEach((kind, i) => {
|
|
132
|
+
if (kind !== 'above' && kind !== 'below')
|
|
133
|
+
return;
|
|
134
|
+
const x = rows[i][xKey];
|
|
135
|
+
zones.push({ x1: x, x2: x, kind });
|
|
136
|
+
});
|
|
137
|
+
return zones;
|
|
138
|
+
}
|
|
139
|
+
function compareSides(rows, layerKeys, compareKey) {
|
|
140
|
+
const line = bridgedValues(rows, compareKey);
|
|
141
|
+
return rows.map((row, i) => {
|
|
142
|
+
const value = line[i];
|
|
143
|
+
if (value == null || row[COST_KNOWN_KEY] === 0)
|
|
144
|
+
return null;
|
|
145
|
+
const stack = layersTotal(row, layerKeys) + (num(row[MARGIN_KEY]) ?? 0);
|
|
146
|
+
// Sums of decimals are not exact: 1.8 + 0.6 + 0.45 + 0.45 is not 3.3.
|
|
147
|
+
const tolerance = 1e-9 * Math.max(1, Math.abs(stack), Math.abs(value));
|
|
148
|
+
if (value > stack + tolerance)
|
|
149
|
+
return 'above';
|
|
150
|
+
if (value < stack - tolerance)
|
|
151
|
+
return 'below';
|
|
152
|
+
return 'equal';
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* A value axis from 0 for a top value: at most `maxIntervals` steps of
|
|
157
|
+
* 1, 2, 2.5 or 5 × 10ⁿ, with a little headroom above the top. Small changes
|
|
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.
|
|
160
|
+
*/
|
|
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));
|
|
164
|
+
for (;;) {
|
|
165
|
+
for (const mantissa of [1, 2, 2.5, 5]) {
|
|
166
|
+
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 };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
exponent += 1;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** The highest stacked total (layers plus margin) or line value on any row. */
|
|
177
|
+
function chartTop(rows, layerKeys, lineKeys) {
|
|
178
|
+
let top = 0;
|
|
179
|
+
for (const row of rows) {
|
|
180
|
+
top = Math.max(top, layersTotal(row, layerKeys) + (num(row[MARGIN_KEY]) ?? 0));
|
|
181
|
+
for (const key of lineKeys)
|
|
182
|
+
top = Math.max(top, num(row[key]) ?? 0);
|
|
183
|
+
}
|
|
184
|
+
return top;
|
|
185
|
+
}
|
|
186
|
+
/** A date string: a four-digit year, alone or followed by `-`. */
|
|
187
|
+
const YEAR_RE = /^(\d{4})(?:-|$)/;
|
|
188
|
+
/**
|
|
189
|
+
* The x value of the first row in each year, when x values are date strings
|
|
190
|
+
* (`YYYY` or `YYYY-…`) and span at least `minYears` years; otherwise undefined.
|
|
191
|
+
*/
|
|
192
|
+
function yearTicks(rows, xKey, minYears = 3) {
|
|
193
|
+
const seen = new Set();
|
|
194
|
+
const ticks = [];
|
|
195
|
+
for (const row of rows) {
|
|
196
|
+
const x = row[xKey];
|
|
197
|
+
if (typeof x !== 'string')
|
|
198
|
+
continue;
|
|
199
|
+
const year = YEAR_RE.exec(x)?.[1];
|
|
200
|
+
if (!year || seen.has(year))
|
|
201
|
+
continue;
|
|
202
|
+
seen.add(year);
|
|
203
|
+
ticks.push(x);
|
|
204
|
+
}
|
|
205
|
+
return ticks.length >= minYears ? ticks : undefined;
|
|
206
|
+
}
|
|
207
|
+
/** The year of a year tick's x value, or the value as text. */
|
|
208
|
+
function yearLabel(x) {
|
|
209
|
+
return YEAR_RE.exec(String(x))?.[1] ?? String(x);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export { COST_KNOWN_KEY, MARGIN_KEY, chartTop, compareRowZones, compareZones, layersTotal, stackRows, stackWeights, valueAxis, yearLabel, yearTicks };
|