@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,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.
@@ -0,0 +1,268 @@
1
+ import type { StackedAreaChartDatum } from './StackedAreaChart.types';
2
+
3
+ /** Data key of the margin layer. Prefixed so it cannot clash with a layer key. */
4
+ export const MARGIN_KEY = '__margin';
5
+ /** 1 when a row from {@link stackRows} has a value for any stacked layer, else 0. */
6
+ export const COST_KNOWN_KEY = '__costKnown';
7
+
8
+ const num = (v: unknown): number | null =>
9
+ typeof v === 'number' && Number.isFinite(v) ? v : null;
10
+
11
+ /** Sum of the layers on a row; a missing value counts as 0. */
12
+ export function layersTotal(
13
+ row: StackedAreaChartDatum,
14
+ layerKeys: readonly string[],
15
+ ): number {
16
+ let sum = 0;
17
+ for (const key of layerKeys) sum += num(row[key]) ?? 0;
18
+ return sum;
19
+ }
20
+
21
+ /**
22
+ * Rows ready to stack: every missing layer value becomes 0, and the margin
23
+ * layer (`MARGIN_KEY`) is `pct` percent of the total of `totalKeys` (the
24
+ * layers that are drawn; all layers by default). Without a positive `pct`
25
+ * the margin key is 0, so the layer can stay mounted. `COST_KNOWN_KEY` says
26
+ * whether any of `totalKeys` had a value, so a row with no cost at all is
27
+ * not compared as a cost of 0.
28
+ */
29
+ export function stackRows(
30
+ rows: readonly StackedAreaChartDatum[],
31
+ layerKeys: readonly string[],
32
+ marginPct?: number | null,
33
+ totalKeys: readonly string[] = layerKeys,
34
+ ): StackedAreaChartDatum[] {
35
+ const pct = num(marginPct);
36
+ return rows.map(row => {
37
+ const next: StackedAreaChartDatum = { ...row };
38
+ for (const key of layerKeys) next[key] = num(row[key]) ?? 0;
39
+ next[COST_KNOWN_KEY] = totalKeys.some(key => num(row[key]) != null) ? 1 : 0;
40
+ next[MARGIN_KEY] =
41
+ pct != null && pct > 0 ? layersTotal(next, totalKeys) * (pct / 100) : 0;
42
+ return next;
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Each layer's share of the total, in whole percent, at the last row where
48
+ * every layer has a value and the total is above zero; when no row is
49
+ * complete, at the last row with a total. A negative value counts as 0.
50
+ * Rounded by largest remainder, so the shares add up to 100. All zeros when
51
+ * no row has a total.
52
+ */
53
+ export function stackWeights(
54
+ rows: readonly StackedAreaChartDatum[],
55
+ layerKeys: readonly string[],
56
+ ): Record<string, number> {
57
+ const positive = (row: StackedAreaChartDatum, key: string) =>
58
+ Math.max(num(row[key]) ?? 0, 0);
59
+ const totalOf = (row: StackedAreaChartDatum) =>
60
+ layerKeys.reduce((sum, key) => sum + positive(row, key), 0);
61
+ const isComplete = (row: StackedAreaChartDatum) =>
62
+ layerKeys.every(key => num(row[key]) != null);
63
+
64
+ let row: StackedAreaChartDatum | undefined;
65
+ for (let i = rows.length - 1; i >= 0 && !row; i--) {
66
+ if (isComplete(rows[i]) && totalOf(rows[i]) > 0) row = rows[i];
67
+ }
68
+ for (let i = rows.length - 1; i >= 0 && !row; i--) {
69
+ if (totalOf(rows[i]) > 0) row = rows[i];
70
+ }
71
+ if (!row) return Object.fromEntries(layerKeys.map(key => [key, 0]));
72
+
73
+ const total = totalOf(row);
74
+ const shares = layerKeys.map(key => {
75
+ const exact = (positive(row, key) / total) * 100;
76
+ return { key, whole: Math.floor(exact), rest: exact - Math.floor(exact) };
77
+ });
78
+ let left = 100 - shares.reduce((sum, share) => sum + share.whole, 0);
79
+ for (const share of [...shares].sort((x, y) => y.rest - x.rest)) {
80
+ if (left <= 0) break;
81
+ share.whole += 1;
82
+ left -= 1;
83
+ }
84
+ return Object.fromEntries(shares.map(share => [share.key, share.whole]));
85
+ }
86
+
87
+ /**
88
+ * The compare values with gaps between two known values filled in a straight
89
+ * line by row, as the chart draws them (the overlays are linear lines). Rows before the first and after the
90
+ * last known value stay null.
91
+ */
92
+ function bridgedValues(
93
+ rows: readonly StackedAreaChartDatum[],
94
+ key: string,
95
+ ): Array<number | null> {
96
+ const values = rows.map(row => num(row[key]));
97
+ let prev = -1;
98
+ for (let i = 0; i < values.length; i++) {
99
+ const value = values[i];
100
+ if (value == null) continue;
101
+ if (prev >= 0 && i - prev > 1) {
102
+ const from = values[prev] as number;
103
+ for (let j = prev + 1; j < i; j++) {
104
+ values[j] = from + ((value - from) * (j - prev)) / (i - prev);
105
+ }
106
+ }
107
+ prev = i;
108
+ }
109
+ return values;
110
+ }
111
+
112
+ export type CompareZone = {
113
+ x1: string | number;
114
+ x2: string | number;
115
+ kind: 'above' | 'below';
116
+ };
117
+
118
+ /**
119
+ * The x ranges where the compare line is above or below the stacked total
120
+ * (the given layers plus the margin on rows from {@link stackRows}). Gaps in
121
+ * the compare line are bridged as the line is drawn; a row with no cost is
122
+ * on neither side. Each run of rows on one side becomes a range from its first
123
+ * row to the row after it (where the side changes), so adjacent ranges meet
124
+ * on a row; a row where the line touches the stack starts the next range.
125
+ * Ranges are whole rows: a crossing between two rows shows at the next, and a
126
+ * run of one row with no compared row after it has no width and is left out.
127
+ * Meant for a point-scale x axis, where a range starts and ends on its rows.
128
+ */
129
+ export function compareZones(
130
+ rows: readonly StackedAreaChartDatum[],
131
+ xKey: string,
132
+ layerKeys: readonly string[],
133
+ compareKey: string,
134
+ ): CompareZone[] {
135
+ const sides = compareSides(rows, layerKeys, compareKey);
136
+ const xOf = (i: number) => rows[i][xKey] as string | number;
137
+
138
+ const zones: CompareZone[] = [];
139
+ let i = 0;
140
+ while (i < sides.length) {
141
+ const kind = sides[i];
142
+ if (kind !== 'above' && kind !== 'below') {
143
+ i++;
144
+ continue;
145
+ }
146
+ let end = i;
147
+ while (end + 1 < sides.length && sides[end + 1] === kind) end++;
148
+ const first = sides[i - 1] === 'equal' ? i - 1 : i;
149
+ const last =
150
+ end + 1 < sides.length && sides[end + 1] != null ? end + 1 : end;
151
+ if (first !== last) zones.push({ x1: xOf(first), x2: xOf(last), kind });
152
+ i = end + 1;
153
+ }
154
+ return zones;
155
+ }
156
+
157
+ /**
158
+ * One zone per row on the side the compare line is on (x1 === x2), for a
159
+ * chart that draws each row as its own bar.
160
+ */
161
+ export function compareRowZones(
162
+ rows: readonly StackedAreaChartDatum[],
163
+ xKey: string,
164
+ layerKeys: readonly string[],
165
+ compareKey: string,
166
+ ): CompareZone[] {
167
+ const sides = compareSides(rows, layerKeys, compareKey);
168
+ const zones: CompareZone[] = [];
169
+ sides.forEach((kind, i) => {
170
+ if (kind !== 'above' && kind !== 'below') return;
171
+ const x = rows[i][xKey] as string | number;
172
+ zones.push({ x1: x, x2: x, kind });
173
+ });
174
+ return zones;
175
+ }
176
+
177
+ function compareSides(
178
+ rows: readonly StackedAreaChartDatum[],
179
+ layerKeys: readonly string[],
180
+ compareKey: string,
181
+ ): Array<CompareZone['kind'] | 'equal' | null> {
182
+ const line = bridgedValues(rows, compareKey);
183
+ return rows.map((row, i) => {
184
+ const value = line[i];
185
+ if (value == null || row[COST_KNOWN_KEY] === 0) return null;
186
+ const stack = layersTotal(row, layerKeys) + (num(row[MARGIN_KEY]) ?? 0);
187
+ // Sums of decimals are not exact: 1.8 + 0.6 + 0.45 + 0.45 is not 3.3.
188
+ const tolerance = 1e-9 * Math.max(1, Math.abs(stack), Math.abs(value));
189
+ if (value > stack + tolerance) return 'above';
190
+ if (value < stack - tolerance) return 'below';
191
+ return 'equal';
192
+ });
193
+ }
194
+
195
+ /**
196
+ * A value axis from 0 for a top value: at most `maxIntervals` steps of
197
+ * 1, 2, 2.5 or 5 × 10ⁿ, with a little headroom above the top. Small changes
198
+ * in the top (a margin being typed) move the axis by one step at most,
199
+ * instead of doubling it the way automatic rounding can.
200
+ */
201
+ export function valueAxis(
202
+ top: number,
203
+ maxIntervals = 5,
204
+ headroom = 0.05,
205
+ ): { max: number; ticks: number[] } {
206
+ const target = Number.isFinite(top) && top > 0 ? top * (1 + headroom) : 1;
207
+ let exponent = Math.floor(Math.log10(target / maxIntervals));
208
+ for (;;) {
209
+ for (const mantissa of [1, 2, 2.5, 5]) {
210
+ const step = mantissa * 10 ** exponent;
211
+ const count = Math.ceil(target / step - 1e-9);
212
+ if (count <= maxIntervals) {
213
+ const ticks = Array.from({ length: count + 1 }, (_, i) =>
214
+ Number((i * step).toPrecision(12)),
215
+ );
216
+ return { max: ticks[ticks.length - 1], ticks };
217
+ }
218
+ }
219
+ exponent += 1;
220
+ }
221
+ }
222
+
223
+ /** The highest stacked total (layers plus margin) or line value on any row. */
224
+ export function chartTop(
225
+ rows: readonly StackedAreaChartDatum[],
226
+ layerKeys: readonly string[],
227
+ lineKeys: readonly string[],
228
+ ): number {
229
+ let top = 0;
230
+ for (const row of rows) {
231
+ top = Math.max(
232
+ top,
233
+ layersTotal(row, layerKeys) + (num(row[MARGIN_KEY]) ?? 0),
234
+ );
235
+ for (const key of lineKeys) top = Math.max(top, num(row[key]) ?? 0);
236
+ }
237
+ return top;
238
+ }
239
+
240
+ /** A date string: a four-digit year, alone or followed by `-`. */
241
+ const YEAR_RE = /^(\d{4})(?:-|$)/;
242
+
243
+ /**
244
+ * The x value of the first row in each year, when x values are date strings
245
+ * (`YYYY` or `YYYY-…`) and span at least `minYears` years; otherwise undefined.
246
+ */
247
+ export function yearTicks(
248
+ rows: readonly StackedAreaChartDatum[],
249
+ xKey: string,
250
+ minYears = 3,
251
+ ): Array<string | number> | undefined {
252
+ const seen = new Set<string>();
253
+ const ticks: Array<string | number> = [];
254
+ for (const row of rows) {
255
+ const x = row[xKey];
256
+ if (typeof x !== 'string') continue;
257
+ const year = YEAR_RE.exec(x)?.[1];
258
+ if (!year || seen.has(year)) continue;
259
+ seen.add(year);
260
+ ticks.push(x);
261
+ }
262
+ return ticks.length >= minYears ? ticks : undefined;
263
+ }
264
+
265
+ /** The year of a year tick's x value, or the value as text. */
266
+ export function yearLabel(x: string | number): string {
267
+ return YEAR_RE.exec(String(x))?.[1] ?? String(x);
268
+ }
@@ -0,0 +1,32 @@
1
+ .root
2
+ width 100%
3
+
4
+ .legend
5
+ flex-wrap wrap
6
+ row-gap 0.5rem
7
+ margin-top 0.75rem
8
+
9
+ .legendButton
10
+ appearance none
11
+ background none
12
+ border 0
13
+ padding 0
14
+ font inherit
15
+ color inherit
16
+ cursor pointer
17
+
18
+ .dimmed
19
+ opacity 0.4
20
+
21
+ .legendExtra
22
+ color var(--muted-foreground)
23
+ font-variant-numeric tabular-nums
24
+
25
+ .legendLine
26
+ width 14px
27
+ height 2px
28
+ flex-shrink 0
29
+ border-radius 1px
30
+
31
+ .legendZone
32
+ border 1px solid var(--border)
@@ -0,0 +1,13 @@
1
+ // This file is automatically generated.
2
+ // Please do not change this file!
3
+ interface CssExports {
4
+ dimmed: string;
5
+ legend: string;
6
+ legendButton: string;
7
+ legendExtra: string;
8
+ legendLine: string;
9
+ legendZone: string;
10
+ root: string;
11
+ }
12
+ export const cssExports: CssExports;
13
+ export default cssExports;
@@ -0,0 +1,81 @@
1
+ import cn from 'classnames';
2
+ import { CSSProperties } from 'react';
3
+
4
+ import type { ChartConfig } from '#uilib/components/ui/Chart';
5
+ import ChartS from '#uilib/components/ui/Chart/Chart.styl';
6
+
7
+ export type TooltipRow = {
8
+ dataKey?: unknown;
9
+ name?: unknown;
10
+ value?: unknown;
11
+ color?: string;
12
+ };
13
+
14
+ /**
15
+ * Tooltip rows in series order, showing real zeros, and colouring each row
16
+ * from the chart config (an area's own colour is its white stack stroke).
17
+ */
18
+ export function StackedTooltip({
19
+ active,
20
+ payload,
21
+ label,
22
+ config,
23
+ valueFormatter,
24
+ labelFormatter,
25
+ }: {
26
+ active?: boolean;
27
+ payload?: ReadonlyArray<TooltipRow>;
28
+ label?: unknown;
29
+ config: ChartConfig;
30
+ valueFormatter?: (value: number) => string;
31
+ labelFormatter?: (value: string | number) => string;
32
+ }) {
33
+ const rows = (payload ?? []).filter(
34
+ row => typeof row.value === 'number' && Number.isFinite(row.value),
35
+ );
36
+ if (!active || rows.length === 0) return null;
37
+ const x = typeof label === 'number' || typeof label === 'string' ? label : '';
38
+ return (
39
+ <div className={ChartS.tooltipContainer}>
40
+ <div className="font-medium">
41
+ {labelFormatter ? labelFormatter(x) : String(x)}
42
+ </div>
43
+ <div className={ChartS.tooltipContentGrid}>
44
+ {rows.map(row => {
45
+ const key = String(row.dataKey ?? row.name);
46
+ const value = row.value as number;
47
+ return (
48
+ <div key={key} className={cn(ChartS.tooltipItem, 'items-center')}>
49
+ <div
50
+ className={cn(ChartS.tooltipIndicator, ChartS['indicator-dot'])}
51
+ style={
52
+ {
53
+ '--color-bg': config[key]?.color ?? row.color,
54
+ '--color-border': config[key]?.color ?? row.color,
55
+ } as CSSProperties
56
+ }
57
+ />
58
+ <div className={cn(ChartS.tooltipContent, 'items-center')}>
59
+ <span
60
+ className={cn(
61
+ 'text-muted-foreground',
62
+ ChartS.tooltipLabelText,
63
+ )}
64
+ >
65
+ {config[key]?.label ?? String(row.name ?? key)}
66
+ </span>
67
+ <span className={ChartS.tooltipValue}>
68
+ {valueFormatter
69
+ ? valueFormatter(value)
70
+ : value.toLocaleString(undefined, {
71
+ maximumFractionDigits: 2,
72
+ })}
73
+ </span>
74
+ </div>
75
+ </div>
76
+ );
77
+ })}
78
+ </div>
79
+ </div>
80
+ );
81
+ }