@sybilion/uilib 1.7.2 → 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.
Files changed (85) hide show
  1. package/dist/agent-glossary/content-prompt.generated.ts +2 -0
  2. package/dist/agent-glossary/content.generated.ts +2 -0
  3. package/dist/agent-glossary/content.md +2 -0
  4. package/dist/agent-glossary/content.prompt.md +2 -0
  5. package/dist/agent-glossary/workspace.generated.ts +1 -0
  6. package/dist/agent-glossary/workspace.index.md +1 -0
  7. package/dist/agent-glossary/workspace.md +1 -0
  8. package/dist/esm/src/components/ui/AnalysesSelector/AnalysesSelector.js +37 -20
  9. package/dist/esm/src/components/ui/Chart/Chart.styl.js +2 -2
  10. package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +46 -51
  11. package/dist/esm/src/components/ui/Chart/components/ChartContainer.js +2 -2
  12. package/dist/esm/src/components/ui/Chart/components/ChartGrid.js +2 -2
  13. package/dist/esm/src/components/ui/Chart/components/ChartLegendContent.js +2 -2
  14. package/dist/esm/src/components/ui/Chart/components/ChartLegendItem.js +2 -2
  15. package/dist/esm/src/components/ui/Chart/components/ChartTooltipContent.js +2 -2
  16. package/dist/esm/src/components/ui/Chart/components/ChartTooltipItem.js +3 -3
  17. package/dist/esm/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.js +8 -3
  18. package/dist/esm/src/components/ui/Chart/components/LegendSvg/LegendSvg.js +1 -1
  19. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.js +17 -6
  20. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.js +40 -10
  21. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +43 -13
  22. package/dist/esm/src/components/ui/ChartAreaInteractive/chartHistories.js +44 -0
  23. package/dist/esm/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.js +32 -7
  24. package/dist/esm/src/components/ui/Page/PageTabs/PageTabs.styl.js +2 -2
  25. package/dist/esm/src/components/ui/Page/PageXScroll/PageXScroll.js +50 -15
  26. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.js +212 -0
  27. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.js +123 -0
  28. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.styl.js +7 -0
  29. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.js +29 -0
  30. package/dist/esm/src/index.js +3 -1
  31. package/dist/esm/src/utils/chartConnectionPoint.js +31 -16
  32. package/dist/esm/types/src/components/ui/AnalysesSelector/AnalysesSelector.d.ts +1 -1
  33. package/dist/esm/types/src/components/ui/AnalysesSelector/AnalysesSelector.types.d.ts +12 -0
  34. package/dist/esm/types/src/components/ui/AnalysesSelector/index.d.ts +1 -1
  35. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +8 -0
  36. package/dist/esm/types/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.d.ts +8 -1
  37. package/dist/esm/types/src/components/ui/Chart/components/LegendSvg/LegendSvg.d.ts +2 -0
  38. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.d.ts +1 -1
  39. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.d.ts +5 -0
  40. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +19 -1
  41. package/dist/esm/types/src/components/ui/ChartAreaInteractive/chartHistories.d.ts +40 -0
  42. package/dist/esm/types/src/components/ui/ChartAreaInteractive/index.d.ts +1 -0
  43. package/dist/esm/types/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.d.ts +6 -1
  44. package/dist/esm/types/src/components/ui/Page/PageXScroll/PageXScroll.d.ts +1 -1
  45. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.d.ts +3 -0
  46. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.d.ts +65 -0
  47. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.d.ts +20 -0
  48. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.types.d.ts +85 -0
  49. package/dist/esm/types/src/components/ui/StackedAreaChart/index.d.ts +2 -0
  50. package/dist/esm/types/src/docs/pages/StackedAreaChartPage.d.ts +1 -0
  51. package/dist/esm/types/src/index.d.ts +1 -0
  52. package/dist/esm/types/src/utils/chartConnectionPoint.d.ts +11 -3
  53. package/dist/esm/types/tests/chartHistories.test.d.ts +1 -0
  54. package/dist/esm/types/tests/pageXScroll.test.d.ts +1 -0
  55. package/dist/esm/types/tests/stackedAreaChart.test.d.ts +1 -0
  56. package/package.json +1 -1
  57. package/src/components/ui/AnalysesSelector/AnalysesSelector.tsx +50 -22
  58. package/src/components/ui/AnalysesSelector/AnalysesSelector.types.ts +13 -0
  59. package/src/components/ui/AnalysesSelector/index.ts +1 -0
  60. package/src/components/ui/Chart/components/BaseChartWrapper.tsx +71 -52
  61. package/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.tsx +21 -1
  62. package/src/components/ui/Chart/components/LegendSvg/LegendSvg.tsx +3 -1
  63. package/src/components/ui/ChartAreaInteractive/AGENT.md +2 -0
  64. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.ts +27 -5
  65. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.tsx +64 -10
  66. package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +86 -30
  67. package/src/components/ui/ChartAreaInteractive/chartHistories.ts +63 -0
  68. package/src/components/ui/ChartAreaInteractive/index.ts +1 -0
  69. package/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.ts +52 -6
  70. package/src/components/ui/Page/AGENT.md +2 -0
  71. package/src/components/ui/Page/PageTabs/PageTabs.styl +8 -0
  72. package/src/components/ui/Page/PageXScroll/PageXScroll.tsx +57 -13
  73. package/src/components/ui/StackedAreaChart/AGENT.md +26 -0
  74. package/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.ts +268 -0
  75. package/src/components/ui/StackedAreaChart/StackedAreaChart.styl +32 -0
  76. package/src/components/ui/StackedAreaChart/StackedAreaChart.styl.d.ts +13 -0
  77. package/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.tsx +82 -0
  78. package/src/components/ui/StackedAreaChart/StackedAreaChart.tsx +416 -0
  79. package/src/components/ui/StackedAreaChart/StackedAreaChart.types.ts +97 -0
  80. package/src/components/ui/StackedAreaChart/index.ts +2 -0
  81. package/src/docs/pages/ChartAreaInteractivePage.tsx +67 -0
  82. package/src/docs/pages/StackedAreaChartPage.tsx +141 -0
  83. package/src/docs/registry.ts +6 -0
  84. package/src/index.ts +1 -0
  85. package/src/utils/chartConnectionPoint.ts +41 -18
@@ -19,8 +19,25 @@ import {
19
19
  import S from './ChartAreaInteractive.styl';
20
20
  import { ChartAreaInteractiveProps } from './ChartAreaInteractive.types';
21
21
  import { TimeRangeBrushHost } from './TimeRangeBrushLayer';
22
+ import { forecastHistoryKey } from './chartHistories';
22
23
  import { IntervalsOverlay, PinOverlay, ThresholdsOverlay } from './overlays';
23
24
 
25
+ type ForecastHistoryKeys = {
26
+ /** [forecastId, history key or null] for each `forecastData` item. */
27
+ byId: [number, string | null][];
28
+ /** For a forecast that is only in `chartData`: no `continues` to go on. */
29
+ other: string | null;
30
+ };
31
+
32
+ /** The bridge's `historyKeyFor`, from serialised {@link ForecastHistoryKeys}. */
33
+ function historyKeyLookup(
34
+ serialised: string,
35
+ ): (forecastId: number) => string | null {
36
+ const { byId, other }: ForecastHistoryKeys = JSON.parse(serialised);
37
+ const map = new Map(byId);
38
+ return id => (map.has(id) ? map.get(id)! : other);
39
+ }
40
+
24
41
  export const chartConfig = {
25
42
  // Chart now supports light/dark themes with dynamic colors
26
43
  } satisfies ChartConfig;
@@ -38,6 +55,7 @@ export function ChartAreaInteractive({
38
55
  onPreviewMonthChange,
39
56
  chartData,
40
57
  forecastData,
58
+ historyData,
41
59
  error,
42
60
  loading = false,
43
61
  isDarkTheme = false,
@@ -99,23 +117,52 @@ export function ChartAreaInteractive({
99
117
  }
100
118
  }, [selectedAnalysisId, ensureAnalysisSeriesVisible]);
101
119
 
102
- const timeFilteredChartData = useMemo(() => {
120
+ const anchorAnalysisId = useMemo(() => {
103
121
  const raw = selectedAnalysisId ?? selectedForecast?.id ?? null;
104
- const anchorId =
105
- raw == null ? null : typeof raw === 'number' ? raw : Number(raw);
122
+ const id = raw == null ? null : typeof raw === 'number' ? raw : Number(raw);
123
+ return id != null && Number.isFinite(id) ? id : null;
124
+ }, [selectedAnalysisId, selectedForecast?.id]);
125
+
126
+ // The history the anchored forecast joins, as a string, so the time filter
127
+ // does not rerun when the host passes new but equal arrays.
128
+ const anchorHistoryKey = useMemo(
129
+ () =>
130
+ anchorAnalysisId == null
131
+ ? undefined
132
+ : forecastHistoryKey(
133
+ forecastData?.find(f => f.id === anchorAnalysisId),
134
+ historyData,
135
+ ),
136
+ [anchorAnalysisId, forecastData, historyData],
137
+ );
138
+
139
+ const timeFilteredChartData = useMemo(() => {
106
140
  const anchorForecastLoaded =
107
- anchorId != null &&
108
- Number.isFinite(anchorId) &&
141
+ anchorAnalysisId != null &&
109
142
  chartData.some(row => {
110
- const value = row[`forecast_${anchorId}`];
143
+ const value = row[`forecast_${anchorAnalysisId}`];
111
144
  return typeof value === 'number' && Number.isFinite(value);
112
145
  });
113
146
  const opts =
114
- anchorId != null && Number.isFinite(anchorId) && anchorForecastLoaded
115
- ? { endDateAnchorAnalysisId: anchorId }
147
+ anchorAnalysisId != null && anchorForecastLoaded
148
+ ? { endDateAnchorAnalysisId: anchorAnalysisId, anchorHistoryKey }
116
149
  : undefined;
117
150
  return filterDataForTimeRange(chartData, timeRange, opts);
118
- }, [chartData, timeRange, selectedAnalysisId, selectedForecast?.id]);
151
+ }, [chartData, timeRange, anchorAnalysisId, anchorHistoryKey]);
152
+
153
+ // Which history each forecast joins, as a string, so the bridge does not
154
+ // rerun when the host passes a new but equal historyData array.
155
+ const forecastHistoryKeys = useMemo(
156
+ () =>
157
+ JSON.stringify({
158
+ byId: (forecastData ?? []).map(f => [
159
+ f.id,
160
+ forecastHistoryKey(f, historyData),
161
+ ]),
162
+ other: forecastHistoryKey(undefined, historyData),
163
+ } satisfies ForecastHistoryKeys),
164
+ [forecastData, historyData],
165
+ );
119
166
 
120
167
  const bridgedChartData = useMemo(
121
168
  () =>
@@ -123,8 +170,14 @@ export function ChartAreaInteractive({
123
170
  ? timeFilteredChartData
124
171
  : ensureChartForecastBridge(timeFilteredChartData, {
125
172
  forecastSeriesIds: forecastData?.map(f => f.id),
173
+ historyKeyFor: historyKeyLookup(forecastHistoryKeys),
126
174
  }),
127
- [timeFilteredChartData, disableForecastHistoricalBridge, forecastData],
175
+ [
176
+ timeFilteredChartData,
177
+ disableForecastHistoricalBridge,
178
+ forecastData,
179
+ forecastHistoryKeys,
180
+ ],
128
181
  );
129
182
 
130
183
  // Extract quantileBands from restProps
@@ -151,6 +204,7 @@ export function ChartAreaInteractive({
151
204
  xAxisClassName,
152
205
  yAxisClassName,
153
206
  chartData: bridgedChartData,
207
+ historyData,
154
208
  chartClassName: S.chartContainer,
155
209
  // chartClassName: cn(S.chartContainer, chartContainerClassName),
156
210
  legendClassName,
@@ -3,6 +3,11 @@ import { memo, useMemo } from 'react';
3
3
  import { Line } from 'recharts';
4
4
 
5
5
  import { ChartDataPoint } from './ChartAreaInteractive.types';
6
+ import {
7
+ HISTORY_SERIES_KEY,
8
+ HistoryItemData,
9
+ historySeriesKey,
10
+ } from './chartHistories';
6
11
 
7
12
  export interface LineConfig {
8
13
  dataKey: string;
@@ -20,6 +25,11 @@ export type ForecastItemData = {
20
25
  tooltip?: string;
21
26
  dimmed?: boolean;
22
27
  updated_at?: string;
28
+ /**
29
+ * Id of the history (`historyData`) this forecast continues. With several
30
+ * histories, a forecast joins one only when this names it.
31
+ */
32
+ continues?: string | number;
23
33
  };
24
34
 
25
35
  export type Dot = {
@@ -52,6 +62,26 @@ export const getForecastQuantileBandColor = (index: number) =>
52
62
  FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length]
53
63
  ];
54
64
 
65
+ /** A history line as drawn: data key, label and colour with defaults applied. */
66
+ export type HistoryLine = { dataKey: string; name: string; color: string };
67
+
68
+ /** Default colour of the history at `index`: the forecast palette from its far end. */
69
+ export function getHistoryColor(index: number): string {
70
+ const n = FORECAST_LINE_COLORS.length;
71
+ return FORECAST_LINE_COLORS[n - 1 - (index % n)];
72
+ }
73
+
74
+ /** `historyData` with the defaults applied, in order (empty without it). */
75
+ export function resolveHistoryLines(
76
+ histories?: HistoryItemData[],
77
+ ): HistoryLine[] {
78
+ return (histories ?? []).map((h, index) => ({
79
+ dataKey: historySeriesKey(h.id),
80
+ name: h.name || String(h.id),
81
+ color: h.color ?? getHistoryColor(index),
82
+ }));
83
+ }
84
+
55
85
  /** Same tint logic as intervals/threshold overlays: band fill follows forecast line hex when known. */
56
86
  export function resolveQuantileBandFillForForecastLine(
57
87
  lineColor: string,
@@ -67,6 +97,7 @@ export const ChartLines = memo(
67
97
  ({
68
98
  chartData,
69
99
  forecastData,
100
+ historyData,
70
101
  hiddenSeries,
71
102
  isDarkTheme,
72
103
  shouldAnimate,
@@ -78,6 +109,8 @@ export const ChartLines = memo(
78
109
  }: {
79
110
  chartData: ChartDataPoint[];
80
111
  forecastData?: ForecastItemData[];
112
+ /** Several history lines (one per product). Omit for the single `historical` line. */
113
+ historyData?: HistoryItemData[];
81
114
  hiddenSeries?: Set<string>;
82
115
  isDarkTheme: boolean;
83
116
  shouldAnimate?: boolean;
@@ -103,16 +136,37 @@ export const ChartLines = memo(
103
136
  fill: color,
104
137
  });
105
138
 
106
- // Memoize last historical index to avoid recalculating on every render call
107
- const lastHistoricalIndex = useMemo(() => {
108
- for (let i = chartData.length - 1; i >= 0; i--) {
109
- const value = chartData[i].historical;
110
- if (value !== undefined && value !== null) {
111
- return i;
139
+ // One entry per history line: the single `historical` line, or one per
140
+ // `historyData` item under `historical_<id>`.
141
+ const historyLines = useMemo(
142
+ () =>
143
+ historyData?.length
144
+ ? resolveHistoryLines(historyData)
145
+ : [
146
+ {
147
+ dataKey: HISTORY_SERIES_KEY,
148
+ name: 'Historical Data',
149
+ color: historicalLineColor,
150
+ },
151
+ ],
152
+ [historyData, historicalLineColor],
153
+ );
154
+
155
+ // Memoize last index per history line to avoid recalculating on every render call
156
+ const lastHistoryIndices = useMemo(() => {
157
+ const indices: Record<string, number> = {};
158
+ historyLines.forEach(({ dataKey }) => {
159
+ indices[dataKey] = -1;
160
+ for (let i = chartData.length - 1; i >= 0; i--) {
161
+ const value = chartData[i][dataKey];
162
+ if (value !== undefined && value !== null) {
163
+ indices[dataKey] = i;
164
+ break;
165
+ }
112
166
  }
113
- }
114
- return -1;
115
- }, [chartData]);
167
+ });
168
+ return indices;
169
+ }, [chartData, historyLines]);
116
170
 
117
171
  // Memoize last forecast indices per forecast ID
118
172
  const lastForecastIndices = useMemo(() => {
@@ -149,8 +203,8 @@ export const ChartLines = memo(
149
203
  return null;
150
204
  };
151
205
 
152
- const renderHistoricalDot = (props: any) =>
153
- renderDot(props, lastHistoricalIndex, 'historical', historicalLineColor);
206
+ const renderHistoryDot = (props: any, dataKey: string, color: string) =>
207
+ renderDot(props, lastHistoryIndices[dataKey] ?? -1, dataKey, color);
154
208
 
155
209
  const renderForecastDot = (props: any, id: number, color: string) =>
156
210
  renderDot(props, lastForecastIndices[id] ?? -1, `forecast_${id}`, color);
@@ -164,25 +218,27 @@ export const ChartLines = memo(
164
218
 
165
219
  return (
166
220
  <>
167
- {/* Historical Data Line */}
168
- <Line
169
- key="historical"
170
- type="monotone"
171
- dataKey="historical"
172
- stroke={historicalLineColor}
173
- strokeWidth={1}
174
- dot={props => renderHistoricalDot(props)}
175
- activeDot={activeDotHistorical}
176
- name="Historical Data"
177
- legendType={showLegend === false ? 'none' : undefined}
178
- strokeDasharray="0"
179
- hide={hiddenSeries?.has('historical')}
180
- isAnimationActive={historicalAnimationActive}
181
- animationDuration={animationDuration}
182
- animateNewValues={valueAnimationEnabled}
183
- animationBegin={0}
184
- animationEasing="ease-out"
185
- />
221
+ {/* History lines */}
222
+ {historyLines.map(({ dataKey, name, color }) => (
223
+ <Line
224
+ key={dataKey}
225
+ type="monotone"
226
+ dataKey={dataKey}
227
+ stroke={color}
228
+ strokeWidth={1}
229
+ dot={props => renderHistoryDot(props, dataKey, color)}
230
+ activeDot={{ ...activeDotHistorical, fill: color }}
231
+ name={name}
232
+ legendType={showLegend === false ? 'none' : undefined}
233
+ strokeDasharray="0"
234
+ hide={hiddenSeries?.has(dataKey)}
235
+ isAnimationActive={historicalAnimationActive}
236
+ animationDuration={animationDuration}
237
+ animateNewValues={valueAnimationEnabled}
238
+ animationBegin={0}
239
+ animationEasing="ease-out"
240
+ />
241
+ ))}
186
242
 
187
243
  {/* Forecast Lines */}
188
244
  {forecastData?.map((data: ForecastItemData, index: number) => {
@@ -0,0 +1,63 @@
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
+
11
+ /** The single history line's key, when the chart has no `historyData`. */
12
+ export const HISTORY_SERIES_KEY = 'historical';
13
+
14
+ export type HistoryItemData = {
15
+ /** Unique within the chart. The line's data key is `historical_<id>`. */
16
+ id: string | number;
17
+ /** Legend and tooltip label. Defaults to the id (also when empty). */
18
+ name?: string;
19
+ /**
20
+ * Line colour. Defaults to the forecast palette taken from its far end, so
21
+ * histories and forecasts differ while there are 8 lines or fewer (the
22
+ * palette's size). To pair a product's history and forecast, pass the same
23
+ * colour to both.
24
+ */
25
+ color?: string;
26
+ };
27
+
28
+ /** Data key of one history line in `chartData` rows. */
29
+ export function historySeriesKey(id: string | number): string {
30
+ return `${HISTORY_SERIES_KEY}_${id}`;
31
+ }
32
+
33
+ /** True for `historical` and for every `historical_<id>` key. */
34
+ export function isHistorySeriesKey(key: string): boolean {
35
+ return key === HISTORY_SERIES_KEY || key.startsWith(`${HISTORY_SERIES_KEY}_`);
36
+ }
37
+
38
+ /** The data keys of the chart's history lines, in order. */
39
+ export function historySeriesKeys(histories?: HistoryItemData[]): string[] {
40
+ return histories?.length
41
+ ? histories.map(h => historySeriesKey(h.id))
42
+ : [HISTORY_SERIES_KEY];
43
+ }
44
+
45
+ /**
46
+ * The history line a forecast joins, or null when it joins none.
47
+ *
48
+ * - No `historyData`: the single `historical` line, as before.
49
+ * - `continues` set: that history, or none when no history has that id.
50
+ * - Otherwise: the only history when there is exactly one, else none.
51
+ */
52
+ export function forecastHistoryKey(
53
+ forecast: { continues?: string | number } | undefined,
54
+ histories?: HistoryItemData[],
55
+ ): string | null {
56
+ if (!histories?.length) return HISTORY_SERIES_KEY;
57
+ const continues = forecast?.continues;
58
+ if (continues != null) {
59
+ const match = histories.find(h => String(h.id) === String(continues));
60
+ return match ? historySeriesKey(match.id) : null;
61
+ }
62
+ return histories.length === 1 ? historySeriesKey(histories[0].id) : null;
63
+ }
@@ -16,4 +16,5 @@ export {
16
16
  } from './ChartAreaInteractive.helpers';
17
17
  export * from './ChartAreaInteractive.types';
18
18
  export * from './ChartLines';
19
+ export * from './chartHistories';
19
20
  export type { OverlayMode } from './ChartAreaInteractive.types';
@@ -2,6 +2,10 @@ import { useMemo, useRef } from 'react';
2
2
 
3
3
  import { BaseChartWrapperProps } from '#uilib/components/ui/Chart/components/BaseChartWrapper';
4
4
  import { ChartDataPoint } from '#uilib/components/ui/ChartAreaInteractive/ChartAreaInteractive.types';
5
+ import {
6
+ forecastHistoryKey as historyKeyOfForecast,
7
+ isHistorySeriesKey,
8
+ } from '#uilib/components/ui/ChartAreaInteractive/chartHistories';
5
9
 
6
10
  interface UseChartYRangeOptions {
7
11
  baseChartProps: BaseChartWrapperProps;
@@ -14,6 +18,11 @@ interface UseChartYRangeOptions {
14
18
  export interface CalculateChartYRangeOptions {
15
19
  excludeQuantileBands: boolean;
16
20
  forecastId?: number;
21
+ /**
22
+ * With `forecastId`: the history line that forecast joins (null: none).
23
+ * Other history lines are left out. Omitted: every history line counts.
24
+ */
25
+ forecastHistoryKey?: string | null;
17
26
  hiddenSeries?: Set<string>;
18
27
  includeHiddenInYScale?: boolean;
19
28
  }
@@ -33,8 +42,8 @@ export function isKeyExcludedFromYScale(
33
42
  ): boolean {
34
43
  if (!hiddenSeries || hiddenSeries.size === 0) return false;
35
44
 
36
- if (key === 'historical') {
37
- return hiddenSeries.has('historical');
45
+ if (isHistorySeriesKey(key)) {
46
+ return hiddenSeries.has(key);
38
47
  }
39
48
 
40
49
  if (key.startsWith('forecast_')) {
@@ -60,6 +69,7 @@ export function calculateChartYRange(
60
69
  {
61
70
  excludeQuantileBands,
62
71
  forecastId,
72
+ forecastHistoryKey,
63
73
  hiddenSeries,
64
74
  includeHiddenInYScale = false,
65
75
  }: CalculateChartYRangeOptions,
@@ -82,6 +92,12 @@ export function calculateChartYRange(
82
92
  if (forecastId !== undefined) {
83
93
  if (key.startsWith('forecast_') && key !== `forecast_${forecastId}`)
84
94
  return;
95
+ if (
96
+ forecastHistoryKey !== undefined &&
97
+ isHistorySeriesKey(key) &&
98
+ key !== forecastHistoryKey
99
+ )
100
+ return;
85
101
  // Exclude q{quantile}_{otherAnalysisId} - only include selected forecast's quantiles
86
102
  if (key.startsWith('q') && !key.endsWith(`_${forecastId}`)) return;
87
103
  }
@@ -132,8 +148,14 @@ export function calculateChartYRange(
132
148
  return { yMin: 0, yMax: 100 };
133
149
  }
134
150
 
135
- const min = Math.min(...allValues);
136
- const max = Math.max(...allValues);
151
+ // A loop, not Math.min(...values): one value per row and line can exceed
152
+ // the engine's argument limit.
153
+ let min = Infinity;
154
+ let max = -Infinity;
155
+ for (const v of allValues) {
156
+ if (v < min) min = v;
157
+ if (v > max) max = v;
158
+ }
137
159
  const diff = max - min;
138
160
 
139
161
  return {
@@ -161,10 +183,24 @@ export function useChartYRange({
161
183
  yMin: number;
162
184
  yMax: number;
163
185
  forecastId?: number;
186
+ historyKey?: string | null;
164
187
  } | null>(null);
165
188
  const prevBaseChartDataRef = useRef(baseChartProps.chartData);
166
189
  const prevHiddenSeriesKeyRef = useRef(serializeHiddenSeries(hiddenSeries));
167
190
 
191
+ // With several histories, the selected forecast scales with its own only.
192
+ const { forecastData, historyData } = baseChartProps;
193
+ const selectedHistoryKey = useMemo(
194
+ () =>
195
+ selectedForecastId !== undefined && historyData?.length
196
+ ? historyKeyOfForecast(
197
+ forecastData?.find(f => f.id === selectedForecastId),
198
+ historyData,
199
+ )
200
+ : undefined,
201
+ [selectedForecastId, forecastData, historyData],
202
+ );
203
+
168
204
  const calculateYRange = (
169
205
  dataToUse: ChartDataPoint[],
170
206
  excludeBands: boolean,
@@ -173,6 +209,8 @@ export function useChartYRange({
173
209
  calculateChartYRange(dataToUse, {
174
210
  excludeQuantileBands: excludeBands,
175
211
  forecastId,
212
+ forecastHistoryKey:
213
+ forecastId === selectedForecastId ? selectedHistoryKey : undefined,
176
214
  hiddenSeries,
177
215
  includeHiddenInYScale,
178
216
  });
@@ -200,7 +238,10 @@ export function useChartYRange({
200
238
  prevBaseChartDataRef.current = baseChartProps.chartData;
201
239
  stableYRangeRef.current = null;
202
240
  }
203
- if (stableYRangeRef.current?.forecastId !== selectedForecastId) {
241
+ if (
242
+ stableYRangeRef.current?.forecastId !== selectedForecastId ||
243
+ stableYRangeRef.current?.historyKey !== selectedHistoryKey
244
+ ) {
204
245
  stableYRangeRef.current = null;
205
246
  }
206
247
  const hiddenSeriesKey = serializeHiddenSeries(hiddenSeries);
@@ -227,6 +268,7 @@ export function useChartYRange({
227
268
  stableYRangeRef.current = {
228
269
  ...result,
229
270
  forecastId: selectedForecastId,
271
+ historyKey: selectedHistoryKey,
230
272
  };
231
273
  }
232
274
 
@@ -241,6 +283,7 @@ export function useChartYRange({
241
283
  selectedForecastId,
242
284
  hiddenSeries,
243
285
  includeHiddenInYScale,
286
+ selectedHistoryKey,
244
287
  ]);
245
288
 
246
289
  // When disableRescaleWhenQuantileChanges is false, calculate from transformed data
@@ -271,13 +314,16 @@ export function useChartYRange({
271
314
  selectedForecastId,
272
315
  hiddenSeries,
273
316
  includeHiddenInYScale,
317
+ selectedHistoryKey,
274
318
  ]);
275
319
 
276
320
  // Return appropriate range
277
321
  if (disableRescaleWhenQuantileChanges) {
278
322
  const cached = stableYRangeRef.current;
279
323
  const cachedMatchesForecast =
280
- cached && cached.forecastId === selectedForecastId;
324
+ cached &&
325
+ cached.forecastId === selectedForecastId &&
326
+ cached.historyKey === selectedHistoryKey;
281
327
  return cachedMatchesForecast
282
328
  ? { yMin: cached!.yMin, yMax: cached!.yMax }
283
329
  : (stableRange ?? { yMin: 0, yMax: 100 });
@@ -114,6 +114,8 @@ Pass `columns={[node1, node2, …]}`. For 3–4 equal columns, omit `fill`; do n
114
114
 
115
115
  Horizontal scroll strip; used inside `PageTabs` and anywhere a overflowing row needs page-aligned padding. Props: `size`, `fullWidth`, `innerClassName`, `scrollbarClassName`.
116
116
 
117
+ The inset before and after the row is `--page-x-padding`, as the cascade resolves it for the row: an app that needs another inset sets that variable on `:root` or on any ancestor of the row (for example `0` when a layout around the row already has its own gutter), and the spacers, the scrollbar and the fade all follow. The scrollbar and the fade read it when the row mounts and when the window is resized, so a value that changes in a media query follows too; one changed another way after mount (a class toggled on an ancestor) shows in the spacers at once and in the scrollbar and fade at the next resize. The row's tabs draw their keyboard focus ring inside themselves, since the scrolling row would clip a ring drawn outside.
118
+
117
119
  ### SectionHeader
118
120
 
119
121
  In-section title block (`title`, `description`, `actions`). Use **inside** `PageContentSection`, not as a replacement for `PageHeader`.
@@ -14,6 +14,14 @@
14
14
  padding-left var(--page-x-padding)
15
15
  padding-right var(--page-x-padding)
16
16
 
17
+ // The row scrolls, so it clips whatever is drawn outside the tabs, and the
18
+ // shared focus ring (2px wide, 2px outside) would lose its top and bottom.
19
+ // Draw it inside the tab instead, its outer edge 2px in so that it clears the
20
+ // link variant's 2px underline. A value set on a tab itself still wins; one set
21
+ // higher up does not, because the ring has to stay inside.
22
+ .listInner
23
+ --focus-outline-offset calc(-1 * var(--focus-outline-width, 2px) - 2px)
24
+
17
25
  .variant-button
18
26
  .variant-outline
19
27
  .listInner
@@ -1,9 +1,27 @@
1
- import { useEffect, useState } from 'react';
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
2
 
3
3
  import S from './PageXScroll.styl';
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
+ /**
12
+ * The page's side padding as the cascade resolves it for this row, in px: the
13
+ * width of the spacer `.inner::before` draws, which is `var(--page-x-padding)`.
14
+ * Reading the spacer, not the variable on `:root`, means an app that sets
15
+ * `--page-x-padding` on any ancestor of the row (or inside a media query)
16
+ * gets the same inset in the scrollbar and fade as in the spacers.
17
+ * Null when the spacer's width is not a length in px (it is not laid out, or
18
+ * a consumer's style gave it something else).
19
+ */
20
+ function readPageXPadding(inner: Element): number | null {
21
+ const { width } = getComputedStyle(inner, '::before');
22
+ return /^\d+(\.\d+)?px$/.test(width) ? parseFloat(width) : null;
23
+ }
24
+
7
25
  const scrollSizeMap = {
8
26
  sm: 's',
9
27
  md: 'm',
@@ -36,23 +54,48 @@ export function PageXScroll({
36
54
  fullWidth = false,
37
55
  size = 'md',
38
56
  scrollbarOffset,
57
+ onInnerRef,
39
58
  ...props
40
59
  }: PageXScrollProps) {
41
- const [pageXPadding, setPageXPadding] = useState(24); // Default fallback
60
+ const [pageXPadding, setPageXPadding] = useState(DEFAULT_PAGE_X_PADDING);
61
+ const innerRef = useRef<HTMLDivElement | null>(null);
42
62
 
43
- useEffect(() => {
44
- if (typeof window !== 'undefined') {
45
- const value = getComputedStyle(document.documentElement)
46
- .getPropertyValue('--page-x-padding')
47
- .trim();
48
- if (value) {
49
- // Convert rem/px to number (assuming px, if rem multiply by 16)
50
- const numValue = parseFloat(value);
51
- setPageXPadding(value.includes('rem') ? numValue * 16 : numValue);
52
- }
53
- }
63
+ const measure = useCallback(() => {
64
+ const width = innerRef.current && readPageXPadding(innerRef.current);
65
+ if (typeof width === 'number') setPageXPadding(width);
54
66
  }, []);
55
67
 
68
+ // The caller's callback is read through a ref, so an inline one does not hand
69
+ // Scroll a new handler (and make it observe the row again) on every render.
70
+ const onInnerRefRef = useRef(onInnerRef);
71
+ onInnerRefRef.current = onInnerRef;
72
+
73
+ // Measure when Scroll hands the row over, so the order of the effects does
74
+ // not matter.
75
+ const handleInnerRef = useCallback(
76
+ (el: HTMLDivElement | null) => {
77
+ innerRef.current = el;
78
+ measure();
79
+ onInnerRefRef.current?.(el);
80
+ },
81
+ [measure],
82
+ );
83
+
84
+ useEffect(() => {
85
+ // A media query can change `--page-x-padding` when the window is resized.
86
+ // Measuring forces a style recalculation, so once per frame at most.
87
+ let frame = 0;
88
+ const onResize = () => {
89
+ cancelAnimationFrame(frame);
90
+ frame = requestAnimationFrame(measure);
91
+ };
92
+ window.addEventListener('resize', onResize);
93
+ return () => {
94
+ window.removeEventListener('resize', onResize);
95
+ cancelAnimationFrame(frame);
96
+ };
97
+ }, [measure]);
98
+
56
99
  return (
57
100
  <Scroll
58
101
  x
@@ -68,6 +111,7 @@ export function PageXScroll({
68
111
  },
69
112
  }}
70
113
  autoHide
114
+ onInnerRef={handleInnerRef}
71
115
  {...props}
72
116
  >
73
117
  {children}
@@ -0,0 +1,26 @@
1
+ StackedAreaChart shows how a total is built from parts over time: cost layers stacked bottom first, an optional margin layer on top, and lines drawn over the stack (for example the prices actually paid). An overlay with `compare` shades the ranges where it sits above or below the stacked total.
2
+
3
+ ## When to use
4
+
5
+ - A should-cost or cost-breakdown view: raw material, energy, labour and freight adding up to a cost, next to what was paid.
6
+ - Any time series where the parts and the total both matter.
7
+
8
+ ## When not to use
9
+
10
+ - Categories without an x order; use BarChart in stacked mode.
11
+ - A single total over time; use ChartAreaInteractive.
12
+ - Parts that can be negative: the stack assumes every layer is zero or more.
13
+
14
+ ## Do
15
+
16
+ - Pass rows in x order, with layer and overlay values as numbers (a numeric string counts as missing). Missing layer values stack as 0; overlay gaps are bridged, and the compare zones follow the bridged line.
17
+ - Expect zones to change at rows: a crossing between two rows shows at the next row. Hiding a layer or the compare line in the legend updates the margin, the zones and the weights to match what is drawn.
18
+ - Give each layer a `label`; the legend and tooltip use it.
19
+ - Keep `margin.pct` in the host's state and pass it on every change; the margin layer stays mounted, so typing does not redraw the chart.
20
+ - Set `yearTicks` for multi-year monthly data so the axis reads one label per year.
21
+ - Pass `hiddenKeys` and `onToggleKey` when the host must remember which series are hidden.
22
+
23
+ ## Don't
24
+
25
+ - Set `compare` on more than one overlay; only the first is used.
26
+ - Rely on areas for one or two rows; below `barsBelow` rows (default 3) the stack draws as bars.