@sybilion/uilib 1.7.2 → 1.8.1

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 (115) 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.js +4 -1
  10. package/dist/esm/src/components/ui/Chart/Chart.styl.js +2 -2
  11. package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +74 -57
  12. package/dist/esm/src/components/ui/Chart/components/ChartAxes.js +8 -7
  13. package/dist/esm/src/components/ui/Chart/components/ChartContainer.js +2 -2
  14. package/dist/esm/src/components/ui/Chart/components/ChartGrid.js +2 -2
  15. package/dist/esm/src/components/ui/Chart/components/ChartLegendContent.js +2 -2
  16. package/dist/esm/src/components/ui/Chart/components/ChartLegendItem.js +2 -2
  17. package/dist/esm/src/components/ui/Chart/components/ChartPlacedTooltip.js +65 -0
  18. package/dist/esm/src/components/ui/Chart/components/ChartTooltipContent.js +4 -4
  19. package/dist/esm/src/components/ui/Chart/components/ChartTooltipItem.js +24 -8
  20. package/dist/esm/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.js +8 -3
  21. package/dist/esm/src/components/ui/Chart/components/LegendSvg/LegendSvg.js +1 -1
  22. package/dist/esm/src/components/ui/Chart/components/QuantileBands.js +1 -1
  23. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.js +17 -6
  24. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.js +40 -10
  25. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +55 -19
  26. package/dist/esm/src/components/ui/ChartAreaInteractive/chartHistories.js +44 -0
  27. package/dist/esm/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.js +32 -7
  28. package/dist/esm/src/components/ui/Page/PageTabs/PageTabs.styl.js +2 -2
  29. package/dist/esm/src/components/ui/Page/PageXScroll/PageXScroll.js +50 -15
  30. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.js +212 -0
  31. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.js +123 -0
  32. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.styl.js +7 -0
  33. package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.js +28 -0
  34. package/dist/esm/src/components/widgets/DriverCard/DriverPerformanceChart.js +5 -25
  35. package/dist/esm/src/index.js +4 -1
  36. package/dist/esm/src/utils/chartConnectionPoint.js +31 -16
  37. package/dist/esm/types/src/components/ui/AnalysesSelector/AnalysesSelector.d.ts +1 -1
  38. package/dist/esm/types/src/components/ui/AnalysesSelector/AnalysesSelector.types.d.ts +12 -0
  39. package/dist/esm/types/src/components/ui/AnalysesSelector/index.d.ts +1 -1
  40. package/dist/esm/types/src/components/ui/Chart/Chart.d.ts +4 -2
  41. package/dist/esm/types/src/components/ui/Chart/Chart.types.d.ts +5 -0
  42. package/dist/esm/types/src/components/ui/Chart/chartForecastVisualization.types.d.ts +7 -0
  43. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +25 -0
  44. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.test.d.ts +1 -0
  45. package/dist/esm/types/src/components/ui/Chart/components/ChartAxes.d.ts +8 -1
  46. package/dist/esm/types/src/components/ui/Chart/components/ChartAxes.test.d.ts +1 -0
  47. package/dist/esm/types/src/components/ui/Chart/components/ChartPlacedTooltip.d.ts +31 -0
  48. package/dist/esm/types/src/components/ui/Chart/components/ChartPlacedTooltip.test.d.ts +1 -0
  49. package/dist/esm/types/src/components/ui/Chart/components/ChartTooltipContent.d.ts +1 -1
  50. package/dist/esm/types/src/components/ui/Chart/components/ChartTooltipContent.test.d.ts +1 -0
  51. package/dist/esm/types/src/components/ui/Chart/components/ChartTooltipItem.d.ts +2 -1
  52. package/dist/esm/types/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.d.ts +8 -1
  53. package/dist/esm/types/src/components/ui/Chart/components/LegendSvg/LegendSvg.d.ts +2 -0
  54. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.d.ts +1 -1
  55. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.d.ts +5 -0
  56. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +30 -1
  57. package/dist/esm/types/src/components/ui/ChartAreaInteractive/chartHistories.d.ts +40 -0
  58. package/dist/esm/types/src/components/ui/ChartAreaInteractive/index.d.ts +1 -0
  59. package/dist/esm/types/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.d.ts +6 -1
  60. package/dist/esm/types/src/components/ui/Page/PageXScroll/PageXScroll.d.ts +1 -1
  61. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.d.ts +3 -0
  62. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.d.ts +65 -0
  63. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.d.ts +19 -0
  64. package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.types.d.ts +85 -0
  65. package/dist/esm/types/src/components/ui/StackedAreaChart/index.d.ts +2 -0
  66. package/dist/esm/types/src/docs/pages/StackedAreaChartPage.d.ts +1 -0
  67. package/dist/esm/types/src/index.d.ts +1 -0
  68. package/dist/esm/types/src/utils/chartConnectionPoint.d.ts +11 -3
  69. package/dist/esm/types/tests/chartHistories.test.d.ts +1 -0
  70. package/dist/esm/types/tests/pageXScroll.test.d.ts +1 -0
  71. package/dist/esm/types/tests/stackedAreaChart.test.d.ts +1 -0
  72. package/package.json +2 -2
  73. package/src/components/ui/AnalysesSelector/AnalysesSelector.tsx +50 -22
  74. package/src/components/ui/AnalysesSelector/AnalysesSelector.types.ts +13 -0
  75. package/src/components/ui/AnalysesSelector/index.ts +1 -0
  76. package/src/components/ui/Chart/AGENT.md +5 -0
  77. package/src/components/ui/Chart/Chart.tsx +7 -1
  78. package/src/components/ui/Chart/Chart.types.ts +5 -0
  79. package/src/components/ui/Chart/chartForecastVisualization.types.ts +7 -0
  80. package/src/components/ui/Chart/components/BaseChartWrapper.test.tsx +344 -0
  81. package/src/components/ui/Chart/components/BaseChartWrapper.tsx +149 -88
  82. package/src/components/ui/Chart/components/ChartAxes.test.tsx +49 -0
  83. package/src/components/ui/Chart/components/ChartAxes.tsx +36 -20
  84. package/src/components/ui/Chart/components/ChartPlacedTooltip.test.tsx +160 -0
  85. package/src/components/ui/Chart/components/ChartPlacedTooltip.tsx +93 -0
  86. package/src/components/ui/Chart/components/ChartTooltipContent.test.tsx +85 -0
  87. package/src/components/ui/Chart/components/ChartTooltipContent.tsx +2 -0
  88. package/src/components/ui/Chart/components/ChartTooltipItem.tsx +41 -10
  89. package/src/components/ui/Chart/components/CustomChartLegend/CustomChartLegend.tsx +21 -1
  90. package/src/components/ui/Chart/components/LegendSvg/LegendSvg.tsx +3 -1
  91. package/src/components/ui/Chart/components/QuantileBands.tsx +1 -1
  92. package/src/components/ui/ChartAreaInteractive/AGENT.md +4 -0
  93. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.ts +27 -5
  94. package/src/components/ui/ChartAreaInteractive/ChartAreaInteractive.tsx +64 -10
  95. package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +151 -65
  96. package/src/components/ui/ChartAreaInteractive/chartHistories.ts +63 -0
  97. package/src/components/ui/ChartAreaInteractive/index.ts +1 -0
  98. package/src/components/ui/ChartAreaInteractive/overlays/useChartYRange.ts +52 -6
  99. package/src/components/ui/Page/AGENT.md +2 -0
  100. package/src/components/ui/Page/PageTabs/PageTabs.styl +8 -0
  101. package/src/components/ui/Page/PageXScroll/PageXScroll.tsx +57 -13
  102. package/src/components/ui/StackedAreaChart/AGENT.md +26 -0
  103. package/src/components/ui/StackedAreaChart/StackedAreaChart.helpers.ts +268 -0
  104. package/src/components/ui/StackedAreaChart/StackedAreaChart.styl +32 -0
  105. package/src/components/ui/StackedAreaChart/StackedAreaChart.styl.d.ts +13 -0
  106. package/src/components/ui/StackedAreaChart/StackedAreaChart.tooltip.tsx +81 -0
  107. package/src/components/ui/StackedAreaChart/StackedAreaChart.tsx +416 -0
  108. package/src/components/ui/StackedAreaChart/StackedAreaChart.types.ts +97 -0
  109. package/src/components/ui/StackedAreaChart/index.ts +2 -0
  110. package/src/components/widgets/DriverCard/DriverPerformanceChart.tsx +2 -2
  111. package/src/docs/pages/ChartAreaInteractivePage.tsx +67 -0
  112. package/src/docs/pages/StackedAreaChartPage.tsx +141 -0
  113. package/src/docs/registry.ts +6 -0
  114. package/src/index.ts +1 -0
  115. package/src/utils/chartConnectionPoint.ts +41 -18
@@ -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(24); // Default fallback
14
- useEffect(() => {
15
- if (typeof window !== 'undefined') {
16
- const value = getComputedStyle(document.documentElement)
17
- .getPropertyValue('--page-x-padding')
18
- .trim();
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 };
@@ -0,0 +1,123 @@
1
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
2
+ import cn from 'classnames';
3
+ import { forwardRef, useMemo } from 'react';
4
+ import { ChartTooltip } from '../Chart/Chart.js';
5
+ import ChartS from '../Chart/Chart.styl.js';
6
+ import { getChartSeriesColor } from '../Chart/chartSeriesPalette.js';
7
+ import { useLegendState } from '../Chart/hooks/useLegendState.js';
8
+ import { ComposedChart, CartesianGrid, XAxis, YAxis, ReferenceArea, Bar, Area, Line } from 'recharts';
9
+ import { stackRows, stackWeights, valueAxis, chartTop, yearTicks, MARGIN_KEY, yearLabel, compareRowZones, compareZones } from './StackedAreaChart.helpers.js';
10
+ import S from './StackedAreaChart.styl.js';
11
+ import { StackedTooltip } from './StackedAreaChart.tooltip.js';
12
+ import { ChartContainer } from '../Chart/components/ChartContainer.js';
13
+
14
+ const STACK_ID = 'stack';
15
+ const DEFAULT_BARS_BELOW = 3;
16
+ const DEFAULT_MARGIN_COLOR = 'var(--sb-slate-300)';
17
+ const DEFAULT_OVERLAY_COLOR = 'var(--foreground)';
18
+ const ZONE_FILL = {
19
+ above: 'var(--sb-green-100)',
20
+ below: 'var(--sb-red-100)',
21
+ };
22
+ const DEFAULT_ZONE_LABELS = { above: 'above', below: 'below' };
23
+ const NO_OVERLAYS = [];
24
+ /** Joins keys into one memo dependency; a key cannot hold this character. */
25
+ const KEY_SEP = '\u0000';
26
+ /** Each key is prefixed with the separator, so an empty key survives the trip. */
27
+ const joinKeys = (keys) => keys.map(key => KEY_SEP + key).join('');
28
+ const splitKeys = (joined) => joined.split(KEY_SEP).slice(1);
29
+ /**
30
+ * Recharts 3 draws by layer: grid -100, area 100, bar 300, line 400. Zones go
31
+ * over the grid and under the stack.
32
+ */
33
+ const ZONE_Z_INDEX = 50;
34
+ const AXIS_LINE = { stroke: 'var(--border)', strokeWidth: 1 };
35
+ const layerColor = (layer, index) => layer.color ?? getChartSeriesColor(index);
36
+ const overlayColor = (overlay) => overlay.color ?? DEFAULT_OVERLAY_COLOR;
37
+ function LegendEntry({ swatch, label, extra, dimmed, onClick, }) {
38
+ const content = (jsxs(Fragment, { children: [swatch, label, extra != null && jsx("span", { className: S.legendExtra, children: extra })] }));
39
+ return onClick ? (jsx("button", { type: "button", className: cn(ChartS.legendItem, S.legendButton, dimmed && S.dimmed), "aria-pressed": !dimmed, onClick: onClick, children: content })) : (jsx("span", { className: ChartS.legendItem, children: content }));
40
+ }
41
+ const StackedAreaChart = forwardRef(({ className, data, xKey, layers, overlays = NO_OVERLAYS, margin, showWeights = true, yearTicks: yearTicks$1 = false, barsBelow = DEFAULT_BARS_BELOW, zoneLabels = DEFAULT_ZONE_LABELS, hiddenKeys, onToggleKey, showLegend = true, showTooltip = true, showGrid = true, valueFormatter, xTickFormatter, tooltipLabelFormatter, height, ...props }, ref) => {
42
+ const legend = useLegendState();
43
+ const hidden = hiddenKeys ?? legend.hiddenSeries;
44
+ // With hiddenKeys and no onToggleKey nothing can change visibility, so
45
+ // the legend entries are not buttons.
46
+ const toggle = hiddenKeys && !onToggleKey
47
+ ? undefined
48
+ : (key) => {
49
+ onToggleKey?.(key);
50
+ if (!hiddenKeys)
51
+ legend.toggleSeries(key);
52
+ };
53
+ // Keyed on the joined keys, so layers passed inline do not redo the maths.
54
+ const layerKeysJoined = joinKeys(layers.map(l => l.key));
55
+ const visibleKeysJoined = joinKeys(layers.filter(l => !hidden.has(l.key)).map(l => l.key));
56
+ const layerKeys = useMemo(() => splitKeys(layerKeysJoined), [layerKeysJoined]);
57
+ // Recharts leaves hidden layers out of the stack, so the margin and the
58
+ // zones follow the stack that is drawn.
59
+ const visibleKeys = useMemo(() => splitKeys(visibleKeysJoined), [visibleKeysJoined]);
60
+ const marginPct = margin?.pct ?? null;
61
+ const marginOn = marginPct != null && marginPct > 0;
62
+ const marginLabel = margin?.label ?? `margin ${marginPct ?? 0}%`;
63
+ const marginColor = margin?.color ?? DEFAULT_MARGIN_COLOR;
64
+ const rows = useMemo(() => stackRows(data, layerKeys, marginPct, visibleKeys), [data, layerKeys, marginPct, visibleKeys]);
65
+ // Shares of the layers that are drawn, from the data: typing a margin
66
+ // does not change them.
67
+ const weights = useMemo(() => (showWeights ? stackWeights(data, visibleKeys) : undefined), [showWeights, data, visibleKeys]);
68
+ const asBars = rows.length < barsBelow;
69
+ const compareKey = overlays.find(o => o.compare)?.key;
70
+ const zonesOn = compareKey != null && !hidden.has(compareKey);
71
+ const zones = useMemo(() => {
72
+ if (!zonesOn || compareKey == null)
73
+ return [];
74
+ const find = asBars ? compareRowZones : compareZones;
75
+ return find(rows, xKey, visibleKeys, compareKey);
76
+ }, [zonesOn, compareKey, asBars, rows, xKey, visibleKeys]);
77
+ const zoneKinds = ['above', 'below'].filter(kind => zones.some(zone => zone.kind === kind));
78
+ const visibleLinesJoined = joinKeys(overlays.filter(o => !hidden.has(o.key)).map(o => o.key));
79
+ const yAxis = useMemo(() => valueAxis(chartTop(rows, visibleKeys, splitKeys(visibleLinesJoined))), [rows, visibleKeys, visibleLinesJoined]);
80
+ const ticks = useMemo(() => (yearTicks$1 ? yearTicks(data, xKey) : undefined), [yearTicks$1, data, xKey]);
81
+ const config = useMemo(() => {
82
+ const out = {};
83
+ layers.forEach((layer, index) => {
84
+ out[layer.key] = {
85
+ label: layer.label ?? layer.key,
86
+ color: layerColor(layer, index),
87
+ };
88
+ });
89
+ out[MARGIN_KEY] = { label: marginLabel, color: marginColor };
90
+ overlays.forEach(overlay => {
91
+ out[overlay.key] = {
92
+ label: overlay.label ?? overlay.key,
93
+ color: overlayColor(overlay),
94
+ };
95
+ });
96
+ return out;
97
+ }, [layers, overlays, marginLabel, marginColor]);
98
+ const stackProps = {
99
+ stackId: STACK_ID,
100
+ stroke: 'var(--background)',
101
+ strokeWidth: 1,
102
+ isAnimationActive: false,
103
+ };
104
+ return (jsxs("div", { ref: ref, className: cn(S.root, className), ...props, children: [jsx(ChartContainer, { config: config, style: height ? { height: `${height}px` } : undefined, children: jsxs(ComposedChart, { data: rows, accessibilityLayer: true, children: [showGrid && (jsx(CartesianGrid, { stroke: "var(--border)", strokeWidth: 0.6, vertical: false })), jsx(XAxis, { dataKey: xKey,
105
+ // A point scale runs the areas edge to edge and starts and ends
106
+ // each zone on its rows; bars keep a band each.
107
+ scale: asBars ? 'auto' : 'point', ticks: ticks, tickFormatter: ticks ? yearLabel : xTickFormatter, minTickGap: ticks ? 8 : 24, tickLine: false, axisLine: AXIS_LINE }), jsx(YAxis
108
+ // Our own steps: automatic rounding can double the axis when the
109
+ // margin nudges the top past a round number.
110
+ , {
111
+ // Our own steps: automatic rounding can double the axis when the
112
+ // margin nudges the top past a round number.
113
+ domain: [0, yAxis.max], ticks: yAxis.ticks, allowDataOverflow: true, tickFormatter: valueFormatter, width: 56, tickLine: false, axisLine: AXIS_LINE }), showTooltip && (jsx(ChartTooltip, { content: tooltip => (jsx(StackedTooltip, { active: tooltip.active, payload: tooltip.payload, label: tooltip.label, config: config, valueFormatter: valueFormatter, labelFormatter: tooltipLabelFormatter })) })), zones.map(zone => (jsx(ReferenceArea, { x1: zone.x1, x2: zone.x2, fill: ZONE_FILL[zone.kind], fillOpacity: 1, stroke: "none", ifOverflow: "hidden", zIndex: ZONE_Z_INDEX }, `${zone.kind}-${String(zone.x1)}`))), layers.map((layer, index) => asBars ? (jsx(Bar, { dataKey: layer.key, name: layer.key, fill: layerColor(layer, index), maxBarSize: 96, hide: hidden.has(layer.key), ...stackProps }, layer.key)) : (jsx(Area, { type: "monotone", dataKey: layer.key, name: layer.key, fill: layerColor(layer, index), fillOpacity: 1, hide: hidden.has(layer.key), ...stackProps }, layer.key))), margin &&
114
+ (asBars ? (jsx(Bar, { dataKey: MARGIN_KEY, name: MARGIN_KEY, fill: marginColor, maxBarSize: 96, hide: !marginOn, ...stackProps }, MARGIN_KEY)) : (jsx(Area, { type: "monotone", dataKey: MARGIN_KEY, name: MARGIN_KEY, fill: marginColor, fillOpacity: 1, hide: !marginOn, ...stackProps }, MARGIN_KEY))), overlays.map(overlay => {
115
+ const color = overlayColor(overlay);
116
+ return (jsx(Line, { type: "linear", dataKey: overlay.key, name: overlay.key, stroke: color, strokeWidth: 1.75, dot: asBars ? { r: 4, fill: color, stroke: color } : false, activeDot: false, connectNulls: true, isAnimationActive: false, hide: hidden.has(overlay.key) }, overlay.key));
117
+ })] }) }), showLegend && (jsxs("div", { className: cn(ChartS.legendContainer, S.legend), children: [layers.map((layer, index) => (jsx(LegendEntry, { swatch: jsx("span", { className: ChartS.legendIndicator, style: { backgroundColor: layerColor(layer, index) } }), label: layer.label ?? layer.key, extra: weights && !hidden.has(layer.key)
118
+ ? `${weights[layer.key] ?? 0}%`
119
+ : undefined, dimmed: hidden.has(layer.key), onClick: toggle && (() => toggle(layer.key)) }, layer.key))), marginOn && (jsx(LegendEntry, { swatch: jsx("span", { className: ChartS.legendIndicator, style: { backgroundColor: marginColor } }), label: marginLabel })), overlays.map(overlay => (jsx(LegendEntry, { swatch: jsx("span", { className: S.legendLine, style: { backgroundColor: overlayColor(overlay) } }), label: overlay.label ?? overlay.key, dimmed: hidden.has(overlay.key), onClick: toggle && (() => toggle(overlay.key)) }, overlay.key))), zoneKinds.map(kind => (jsx(LegendEntry, { swatch: jsx("span", { className: cn(ChartS.legendIndicator, S.legendZone), style: { backgroundColor: ZONE_FILL[kind] } }), label: zoneLabels[kind] }, kind)))] }))] }));
120
+ });
121
+ StackedAreaChart.displayName = 'StackedAreaChart';
122
+
123
+ export { StackedAreaChart };
@@ -0,0 +1,7 @@
1
+ import styleInject from 'style-inject';
2
+
3
+ var css_248z = ".StackedAreaChart_root__BkxHH{width:100%}.StackedAreaChart_legend__JVlx8{flex-wrap:wrap;margin-top:.75rem;row-gap:.5rem}.StackedAreaChart_legendButton__-nJsf{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;border:0;color:inherit;cursor:pointer;font:inherit;padding:0}.StackedAreaChart_dimmed__L-fX7{opacity:.4}.StackedAreaChart_legendExtra__xGgeV{color:var(--muted-foreground);font-feature-settings:\"tnum\";font-variant-numeric:tabular-nums}.StackedAreaChart_legendLine__UDtNb{border-radius:1px;flex-shrink:0;height:2px;width:14px}.StackedAreaChart_legendZone__-47oB{border:1px solid var(--border)}";
4
+ var S = {"root":"StackedAreaChart_root__BkxHH","legend":"StackedAreaChart_legend__JVlx8","legendButton":"StackedAreaChart_legendButton__-nJsf","dimmed":"StackedAreaChart_dimmed__L-fX7","legendExtra":"StackedAreaChart_legendExtra__xGgeV","legendLine":"StackedAreaChart_legendLine__UDtNb","legendZone":"StackedAreaChart_legendZone__-47oB"};
5
+ styleInject(css_248z);
6
+
7
+ export { S as default };
@@ -0,0 +1,28 @@
1
+ import { jsxs, jsx } from 'react/jsx-runtime';
2
+ import cn from 'classnames';
3
+ import ChartS from '../Chart/Chart.styl.js';
4
+
5
+ /**
6
+ * Tooltip rows in series order, showing real zeros, and colouring each row
7
+ * from the chart config (an area's own colour is its white stack stroke).
8
+ */
9
+ function StackedTooltip({ active, payload, label, config, valueFormatter, labelFormatter, }) {
10
+ const rows = (payload ?? []).filter(row => typeof row.value === 'number' && Number.isFinite(row.value));
11
+ if (!active || rows.length === 0)
12
+ return null;
13
+ const x = typeof label === 'number' || typeof label === 'string' ? label : '';
14
+ return (jsxs("div", { className: ChartS.tooltipContainer, children: [jsx("div", { className: "font-medium", children: labelFormatter ? labelFormatter(x) : String(x) }), jsx("div", { className: ChartS.tooltipContentGrid, children: rows.map(row => {
15
+ const key = String(row.dataKey ?? row.name);
16
+ const value = row.value;
17
+ return (jsxs("div", { className: cn(ChartS.tooltipItem, 'items-center'), children: [jsx("div", { className: cn(ChartS.tooltipIndicator, ChartS['indicator-dot']), style: {
18
+ '--color-bg': config[key]?.color ?? row.color,
19
+ '--color-border': config[key]?.color ?? row.color,
20
+ } }), jsxs("div", { className: cn(ChartS.tooltipContent, 'items-center'), children: [jsx("span", { className: cn('text-muted-foreground', ChartS.tooltipLabelText), children: config[key]?.label ?? String(row.name ?? key) }), jsx("span", { className: ChartS.tooltipValue, children: valueFormatter
21
+ ? valueFormatter(value)
22
+ : value.toLocaleString(undefined, {
23
+ maximumFractionDigits: 2,
24
+ }) })] })] }, key));
25
+ }) })] }));
26
+ }
27
+
28
+ export { StackedTooltip };
@@ -1,32 +1,12 @@
1
1
  import { jsxs, jsx } from 'react/jsx-runtime';
2
2
  import cn from 'classnames';
3
3
  import { useMemo } from 'react';
4
- import { LineChart, CartesianGrid, XAxis, YAxis, Tooltip, Line } from 'recharts';
5
- import '../../ui/Chart/components/BaseChartWrapper.js';
6
- import { ChartContainer } from '../../ui/Chart/components/ChartContainer.js';
7
- import '../../ui/Chart/Chart.context.js';
8
- import '../../ui/Chart/Chart.styl.js';
9
- import '../../ui/AnalysisLineIcon/AnalysisLineIcon.styl.js';
10
- import 'lucide-react';
11
- import '../../ui/Chip/Chip.styl.js';
12
- import '../../ui/LabelWithId/LabelWithId.styl.js';
13
- import '../../ui/Select/Select.js';
14
- import '../../ui/TextShimmer/TextShimmer.js';
15
- import '@phosphor-icons/react';
16
- import '../../ui/AnalysesSelector/AnalysesSelector.styl.js';
17
- import '@radix-ui/react-slot';
18
- import '../../ui/Button/Button.styl.js';
19
- import '../../ui/Input/Input.js';
20
- import '../../ui/Tooltip/Tooltip.js';
21
- import '../../ui/Chart/components/CustomChartLegend/CustomChartLegend.styl.js';
22
- import '../../ui/ChartAreaInteractive/ChartLines.js';
23
- import '../../ui/Skeleton/Skeleton.styl.js';
24
- import 'lightweight-charts';
25
- import '../../ui/Chart/lightweight/LightweightForecastChart.styl.js';
26
- import { ChartEmptyState } from '../../ui/Chart/components/ChartEmptyState/ChartEmptyState.js';
27
- import '../../ui/Chart/components/QuantileBands.js';
4
+ import { LineChart, CartesianGrid, XAxis, YAxis, Line } from 'recharts';
5
+ import { ChartTooltip } from '../../ui/Chart/Chart.js';
28
6
  import S from './DriverPerformanceChart.styl.js';
29
7
  import { generateDriverChartData } from './driverPerformanceChartData.js';
8
+ import { ChartContainer } from '../../ui/Chart/components/ChartContainer.js';
9
+ import { ChartEmptyState } from '../../ui/Chart/components/ChartEmptyState/ChartEmptyState.js';
30
10
 
31
11
  const driverChartConfig = {
32
12
  value: {
@@ -80,7 +60,7 @@ function DriverPerformanceChart({ driver, }) {
80
60
  }
81
61
  return null;
82
62
  };
83
- return (jsxs("div", { className: S.driverChartContainer, children: [jsx(ChartContainer, { config: driverChartConfig, className: cn(S.chartContainer, noSeriesData && S.chartContainerDisabled), children: jsxs(LineChart, { data: chartData, margin: { left: 8, right: 8, top: 8, bottom: -20 }, children: [jsx(CartesianGrid, { vertical: false }), jsx(XAxis, { dataKey: "date", tickLine: false, axisLine: false, tick: false, tickMargin: 0, minTickGap: 0 }), jsx(YAxis, { tickLine: false, axisLine: false, tick: false, tickMargin: 0, minTickGap: 0, width: 0, domain: ['dataMin', 'dataMax'] }), jsx(Tooltip, { cursor: false, content: renderTooltipContent }), jsx(Line, { dataKey: "value", type: "natural", stroke: "var(--color-value)" })] }) }), noSeriesData && (jsx(ChartEmptyState, { variant: "inline", align: "center", status: "No series data", className: S.noDataMessage }))] }));
63
+ return (jsxs("div", { className: S.driverChartContainer, children: [jsx(ChartContainer, { config: driverChartConfig, className: cn(S.chartContainer, noSeriesData && S.chartContainerDisabled), children: jsxs(LineChart, { data: chartData, margin: { left: 8, right: 8, top: 8, bottom: -20 }, children: [jsx(CartesianGrid, { vertical: false }), jsx(XAxis, { dataKey: "date", tickLine: false, axisLine: false, tick: false, tickMargin: 0, minTickGap: 0 }), jsx(YAxis, { tickLine: false, axisLine: false, tick: false, tickMargin: 0, minTickGap: 0, width: 0, domain: ['dataMin', 'dataMax'] }), jsx(ChartTooltip, { cursor: false, content: renderTooltipContent }), jsx(Line, { dataKey: "value", type: "natural", stroke: "var(--color-value)" })] }) }), noSeriesData && (jsx(ChartEmptyState, { variant: "inline", align: "center", status: "No series data", className: S.noDataMessage }))] }));
84
64
  }
85
65
 
86
66
  export { DriverPerformanceChart };
@@ -24,9 +24,11 @@ export { ChartLegend, ChartTooltip } from './components/ui/Chart/Chart.js';
24
24
  export { THEMES } from './components/ui/Chart/Chart.types.js';
25
25
  export { ChartAreaInteractive, chartConfig } from './components/ui/ChartAreaInteractive/ChartAreaInteractive.js';
26
26
  export { DRAG_TIME_RANGE_PREFIX, encodeDragTimeRange, filterDataForTimeRange, findPinPositionForDate, isAnalysisDone, isAnalysisFailed, isAnalysisNotFailed, isTimeRangePreset, longDateFormatter, parseDragTimeRange, shortDateFormatter } from './components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.js';
27
- export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, resolveQuantileBandFillForForecastLine } from './components/ui/ChartAreaInteractive/ChartLines.js';
27
+ export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, getHistoryColor, resolveHistoryLines, resolveQuantileBandFillForForecastLine } from './components/ui/ChartAreaInteractive/ChartLines.js';
28
+ export { HISTORY_SERIES_KEY, forecastHistoryKey, historySeriesKey, historySeriesKeys, isHistorySeriesKey } from './components/ui/ChartAreaInteractive/chartHistories.js';
28
29
  export { DonutChart } from './components/ui/DonutChart/DonutChart.js';
29
30
  export { BarChart } from './components/ui/BarChart/BarChart.js';
31
+ export { StackedAreaChart } from './components/ui/StackedAreaChart/StackedAreaChart.js';
30
32
  export { Checkbox } from './components/ui/Checkbox/Checkbox.js';
31
33
  export { Confirm } from './components/ui/Confirm/Confirm.js';
32
34
  export { Calendar } from './components/ui/DatePicker/Calendar.js';
@@ -157,6 +159,7 @@ export { useChartColors } from './components/ui/Chart/hooks/useChartColors.js';
157
159
  export { useLegendState } from './components/ui/Chart/hooks/useLegendState.js';
158
160
  export { ChartContainer, ChartStyle } from './components/ui/Chart/components/ChartContainer.js';
159
161
  export { ChartTooltipContent } from './components/ui/Chart/components/ChartTooltipContent.js';
162
+ export { NARROW_CHART_PX } from './components/ui/Chart/components/ChartPlacedTooltip.js';
160
163
  export { ChartLegendContent } from './components/ui/Chart/components/ChartLegendContent.js';
161
164
  export { BaseChartWrapper } from './components/ui/Chart/components/BaseChartWrapper.js';
162
165
  export { default as DialogStyles } from './components/ui/Dialog/Dialog.styl.js';
@@ -1,3 +1,10 @@
1
+ import { HISTORY_SERIES_KEY } from '../components/ui/ChartAreaInteractive/chartHistories.js';
2
+
3
+ /** A history line's value on a row, or null when it has none. */
4
+ function historyValueAt(row, key) {
5
+ const v = row[key];
6
+ return v == null || Array.isArray(v) ? null : v;
7
+ }
1
8
  const FORECAST_KEY_RE = /^forecast_(\d+)$/;
2
9
  function collectForecastSeriesIds(chartData) {
3
10
  const ids = new Set();
@@ -21,7 +28,7 @@ function hasForecastValue(point, id) {
21
28
  * First forecast month for bridge logic — skips synthetic connection rows already
22
29
  * injected upstream (forecast equals historical on the month before the next forecast).
23
30
  */
24
- function findFirstForecastDateForBridge(rows, id) {
31
+ function findFirstForecastDateForBridge(rows, id, historyKey) {
25
32
  const dataKey = forecastSeriesKey(id);
26
33
  const withForecast = rows
27
34
  .filter(row => hasForecastValue(row, id))
@@ -34,10 +41,11 @@ function findFirstForecastDateForBridge(rows, id) {
34
41
  }
35
42
  const expectedBridgeDate = normalizeToMonthStart(getPreviousMonth(next.date));
36
43
  const forecastVal = row[dataKey];
44
+ const historyVal = historyValueAt(row, historyKey);
37
45
  const isSyntheticBridge = normalizeToMonthStart(row.date) === expectedBridgeDate &&
38
- row.historical != null &&
46
+ historyVal != null &&
39
47
  typeof forecastVal === 'number' &&
40
- forecastVal === row.historical;
48
+ forecastVal === historyVal;
41
49
  if (!isSyntheticBridge) {
42
50
  return row.date;
43
51
  }
@@ -49,7 +57,8 @@ function findFirstForecastDateForBridge(rows, id) {
49
57
  /**
50
58
  * Injects `forecast_{id}` on the row before each series’ first forecast month (historical value)
51
59
  * so dashed forecast lines meet the historical line. Matches sybilion-client bridge behavior.
52
- * Never overwrites an existing forecast value on that row.
60
+ * Never overwrites an existing forecast value on that row. With several history lines,
61
+ * `historyKeyFor` says which one each forecast joins (null: none).
53
62
  */
54
63
  function ensureChartForecastBridge(chartData, options) {
55
64
  if (options?.disabled || chartData.length === 0) {
@@ -63,9 +72,13 @@ function ensureChartForecastBridge(chartData, options) {
63
72
  return sorted;
64
73
  }
65
74
  const rows = sorted.map(p => ({ ...p }));
75
+ const historyKeyFor = options?.historyKeyFor ?? (() => HISTORY_SERIES_KEY);
66
76
  for (const id of seriesIds) {
77
+ const historyKey = historyKeyFor(id);
78
+ if (historyKey == null)
79
+ continue;
67
80
  const dataKey = forecastSeriesKey(id);
68
- const firstForecastDate = findFirstForecastDateForBridge(rows, id);
81
+ const firstForecastDate = findFirstForecastDateForBridge(rows, id, historyKey);
69
82
  if (!firstForecastDate)
70
83
  continue;
71
84
  const prevMonthRaw = getPreviousMonth(firstForecastDate);
@@ -73,17 +86,15 @@ function ensureChartForecastBridge(chartData, options) {
73
86
  const prevMonthIdx = rows.findIndex(row => normalizeToMonthStart(row.date) === prevMonthNorm);
74
87
  if (prevMonthIdx >= 0) {
75
88
  const existing = rows[prevMonthIdx][dataKey];
76
- const hPrev = rows[prevMonthIdx].historical;
77
- if ((existing === undefined || existing === null) &&
78
- hPrev !== undefined &&
79
- hPrev !== null) {
89
+ const hPrev = historyValueAt(rows[prevMonthIdx], historyKey);
90
+ if ((existing === undefined || existing === null) && hPrev !== null) {
80
91
  rows[prevMonthIdx] = {
81
92
  ...rows[prevMonthIdx],
82
93
  [dataKey]: hPrev,
83
94
  };
84
95
  }
85
96
  }
86
- const lastHist = findLastValidHistoricalChartPoint(rows);
97
+ const lastHist = findLastValidHistoricalChartPoint(rows, historyKey);
87
98
  if (!lastHist)
88
99
  continue;
89
100
  const normLast = normalizeToMonthStart(lastHist.date);
@@ -96,19 +107,23 @@ function ensureChartForecastBridge(chartData, options) {
96
107
  const existingAtLast = rows[idxLast][dataKey];
97
108
  if (existingAtLast !== undefined && existingAtLast !== null)
98
109
  continue;
99
- const hLast = rows[idxLast].historical;
100
- if (hLast !== undefined && hLast !== null) {
110
+ const hLast = historyValueAt(rows[idxLast], historyKey);
111
+ if (hLast !== null) {
101
112
  rows[idxLast] = { ...rows[idxLast], [dataKey]: hLast };
102
113
  }
103
114
  }
104
115
  return rows;
105
116
  }
106
117
  /**
107
- * Find the last valid historical data point from ChartDataPoint array
118
+ * Find the last valid historical data point from ChartDataPoint array, on the
119
+ * single `historical` line or on the history line under `key`.
108
120
  */
109
- function findLastValidHistoricalChartPoint(historical) {
110
- const validPoints = historical.filter(point => point.historical !== null && point.historical !== undefined);
111
- return validPoints.length > 0 ? validPoints[validPoints.length - 1] : null;
121
+ function findLastValidHistoricalChartPoint(historical, key = HISTORY_SERIES_KEY) {
122
+ for (let i = historical.length - 1; i >= 0; i--) {
123
+ if (historyValueAt(historical[i], key) !== null)
124
+ return historical[i];
125
+ }
126
+ return null;
112
127
  }
113
128
  function parseYearMonth(date) {
114
129
  const datePart = String(date).split(' ')[0] ?? date;
@@ -1,2 +1,2 @@
1
1
  import type { AnalysesSelectorProps } from './AnalysesSelector.types';
2
- export declare function AnalysesSelector({ items, selectedIds, onItemToggle, inlineMode, placeholder, disabled, size, variant, darker, className, triggerProps, onFailedItemClick, showHistorical, enableToggleHidden, maxVisibleItems, preventDeselection, hiddenSeries: hiddenSeriesProp, onToggleSeries, isAnalysisInProgress: isAnalysisInProgressProp, rename, }: AnalysesSelectorProps): import("react/jsx-runtime").JSX.Element;
2
+ export declare function AnalysesSelector({ items, selectedIds, onItemToggle, inlineMode, placeholder, disabled, size, variant, darker, className, triggerProps, onFailedItemClick, showHistorical, historicalItems, enableToggleHidden, maxVisibleItems, preventDeselection, hiddenSeries: hiddenSeriesProp, onToggleSeries, isAnalysisInProgress: isAnalysisInProgressProp, rename, }: AnalysesSelectorProps): import("react/jsx-runtime").JSX.Element;