@sybilion/uilib 1.8.5 → 1.8.7

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 (46) hide show
  1. package/dist/agent-glossary/content-prompt.generated.ts +27 -0
  2. package/dist/agent-glossary/content.generated.ts +27 -0
  3. package/dist/agent-glossary/content.index.md +1 -0
  4. package/dist/agent-glossary/content.md +27 -0
  5. package/dist/agent-glossary/content.prompt.md +27 -0
  6. package/dist/agent-glossary/workspace.generated.ts +1 -0
  7. package/dist/agent-glossary/workspace.index.md +1 -0
  8. package/dist/agent-glossary/workspace.md +1 -0
  9. package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +3 -1
  10. package/dist/esm/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.js +5 -1
  11. package/dist/esm/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.js +2 -2
  12. package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +15 -5
  13. package/dist/esm/src/components/ui/DropdownMenu/DropdownMenu.styl.js +2 -2
  14. package/dist/esm/src/components/ui/WorkspaceAppSwitcher/WorkspaceAppSwitcher.styl.js +1 -1
  15. package/dist/esm/src/components/widgets/BacktestChart/BacktestChart.js +113 -0
  16. package/dist/esm/src/components/widgets/BacktestChart/BacktestChart.styl.js +7 -0
  17. package/dist/esm/src/components/widgets/BacktestChart/backtestChart.helpers.js +134 -0
  18. package/dist/esm/src/index.js +3 -1
  19. package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +3 -2
  20. package/dist/esm/types/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.d.ts +2 -0
  21. package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +16 -1
  22. package/dist/esm/types/src/components/widgets/BacktestChart/BacktestChart.d.ts +37 -0
  23. package/dist/esm/types/src/components/widgets/BacktestChart/backtestChart.helpers.d.ts +61 -0
  24. package/dist/esm/types/src/components/widgets/BacktestChart/index.d.ts +2 -0
  25. package/dist/esm/types/src/docs/pages/BacktestChartPage.d.ts +1 -0
  26. package/dist/esm/types/src/index.d.ts +1 -0
  27. package/dist/esm/types/tests/backtestChart.test.d.ts +1 -0
  28. package/package.json +1 -1
  29. package/src/components/ui/Chart/components/BaseChartWrapper.tsx +6 -2
  30. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl +4 -0
  31. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.d.ts +1 -0
  32. package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.tsx +7 -1
  33. package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +30 -4
  34. package/src/components/ui/DropdownMenu/AGENT.md +2 -0
  35. package/src/components/ui/DropdownMenu/DropdownMenu.styl +17 -4
  36. package/src/components/ui/WorkspaceAppSwitcher/WorkspaceAppSwitcher.styl +0 -1
  37. package/src/components/widgets/BacktestChart/AGENT.md +24 -0
  38. package/src/components/widgets/BacktestChart/BacktestChart.styl +23 -0
  39. package/src/components/widgets/BacktestChart/BacktestChart.styl.d.ts +9 -0
  40. package/src/components/widgets/BacktestChart/BacktestChart.tsx +247 -0
  41. package/src/components/widgets/BacktestChart/backtestChart.helpers.ts +172 -0
  42. package/src/components/widgets/BacktestChart/index.ts +8 -0
  43. package/src/docs/pages/BacktestChartPage.tsx +94 -0
  44. package/src/docs/pages/DropdownMenuPage.tsx +128 -14
  45. package/src/docs/registry.ts +6 -0
  46. package/src/index.ts +1 -0
@@ -0,0 +1,247 @@
1
+ import cn from 'classnames';
2
+ import { type ReactNode, useCallback, useMemo, useState } from 'react';
3
+
4
+ import { BaseChartWrapper } from '#uilib/components/ui/Chart/components/BaseChartWrapper';
5
+ import {
6
+ SeriesLegend,
7
+ type SeriesLegendItem,
8
+ } from '#uilib/components/ui/Chart/components/SeriesLegend';
9
+ import type { ForecastItemData } from '#uilib/components/ui/ChartAreaInteractive/ChartLines';
10
+ import { HISTORY_SERIES_KEY } from '#uilib/components/ui/ChartAreaInteractive/chartHistories';
11
+
12
+ import S from './BacktestChart.styl';
13
+ import {
14
+ type BacktestOrigin,
15
+ type BacktestPoint,
16
+ type BacktestScore,
17
+ backtestBaselineId,
18
+ backtestBaselineKey,
19
+ backtestForecastId,
20
+ backtestForecastKey,
21
+ backtestScore,
22
+ buildBacktestRows,
23
+ } from './backtestChart.helpers';
24
+
25
+ /** The legend's three groups; each hides or shows all of its lines. */
26
+ type Group = 'actual' | 'forecast' | 'baseline';
27
+
28
+ const DEFAULT_WINDOWS = [24, 12];
29
+
30
+ const PERCENT = new Intl.NumberFormat('en-GB', { maximumFractionDigits: 1 });
31
+ const defaultFormatPercent = (v: number) => `${PERCENT.format(v)}%`;
32
+
33
+ export type BacktestChartProps = {
34
+ /** The actual values, one per month. */
35
+ actuals: BacktestPoint[];
36
+ /** The past months forecasts were made from, each cut to one horizon. */
37
+ origins: BacktestOrigin[];
38
+ /**
39
+ * The score windows under the chart: the last N calendar months up to the
40
+ * latest actual (default: 24 and 12).
41
+ */
42
+ windows?: number[];
43
+ actualLabel?: string;
44
+ forecastLabel?: string;
45
+ baselineLabel?: string;
46
+ actualColor?: string;
47
+ forecastColor?: string;
48
+ baselineColor?: string;
49
+ /** One score line; the default says "removes X% of the error". */
50
+ renderScore?: (score: BacktestScore) => ReactNode;
51
+ formatPercent?: (value: number) => string;
52
+ formatNumber?: (value: number) => string;
53
+ formatDate?: (value: string, detailed?: boolean) => string;
54
+ height?: number;
55
+ /** Draw the lines at once, with no animation. */
56
+ disableAnimation?: boolean;
57
+ isDarkTheme?: boolean;
58
+ renderId?: string;
59
+ className?: string;
60
+ };
61
+
62
+ /**
63
+ * A backtest: the actual values (solid), and from each origin the forecast
64
+ * out to its horizon (dashed, with a dot where it lands) and the last value
65
+ * held flat over the same months (dotted, the baseline). Under it, for each
66
+ * window, how much of the baseline's error the forecast removes.
67
+ */
68
+ export function BacktestChart({
69
+ actuals,
70
+ origins,
71
+ windows = DEFAULT_WINDOWS,
72
+ actualLabel = 'Actual',
73
+ forecastLabel = 'Forecast',
74
+ baselineLabel = 'Last price held flat',
75
+ actualColor,
76
+ forecastColor = 'var(--sb-cyan-400)',
77
+ baselineColor = 'var(--sb-gray-400)',
78
+ renderScore,
79
+ formatPercent = defaultFormatPercent,
80
+ formatNumber,
81
+ formatDate,
82
+ height = 300,
83
+ disableAnimation = false,
84
+ isDarkTheme = false,
85
+ renderId = 'backtest',
86
+ className,
87
+ }: BacktestChartProps) {
88
+ const [hiddenGroups, setHiddenGroups] = useState<ReadonlySet<Group>>(
89
+ () => new Set(),
90
+ );
91
+ const toggle = useCallback((group: string) => {
92
+ setHiddenGroups(prev => {
93
+ const next = new Set(prev);
94
+ if (next.has(group as Group)) next.delete(group as Group);
95
+ else next.add(group as Group);
96
+ return next;
97
+ });
98
+ }, []);
99
+
100
+ const chartData = useMemo(
101
+ () => buildBacktestRows(actuals, origins),
102
+ [actuals, origins],
103
+ );
104
+ const historyColor = actualColor ?? (isDarkTheme ? '#ffffff' : '#000000');
105
+
106
+ const forecastData = useMemo<ForecastItemData[]>(
107
+ () =>
108
+ origins.flatMap((_, i) => [
109
+ // The baseline first, so each forecast is drawn over it.
110
+ {
111
+ id: backtestBaselineId(i),
112
+ name: baselineLabel,
113
+ color: baselineColor,
114
+ lineStyle: 'dotted' as const,
115
+ endDot: false,
116
+ },
117
+ {
118
+ id: backtestForecastId(i),
119
+ name: forecastLabel,
120
+ color: forecastColor,
121
+ lineStyle: 'dashed' as const,
122
+ endDot: true,
123
+ },
124
+ ]),
125
+ [origins, baselineLabel, baselineColor, forecastLabel, forecastColor],
126
+ );
127
+
128
+ // The chart hides lines by data key; the legend hides whole groups.
129
+ const hiddenSeries = useMemo(() => {
130
+ const keys = new Set<string>();
131
+ if (hiddenGroups.has('actual')) keys.add(HISTORY_SERIES_KEY);
132
+ origins.forEach((_, i) => {
133
+ if (hiddenGroups.has('forecast')) keys.add(backtestForecastKey(i));
134
+ if (hiddenGroups.has('baseline')) keys.add(backtestBaselineKey(i));
135
+ });
136
+ return keys;
137
+ }, [hiddenGroups, origins]);
138
+
139
+ const legend = useMemo<SeriesLegendItem[]>(
140
+ () => [
141
+ { dataKey: 'actual', label: actualLabel, color: historyColor },
142
+ {
143
+ dataKey: 'forecast',
144
+ label: forecastLabel,
145
+ color: forecastColor,
146
+ dashed: true,
147
+ },
148
+ {
149
+ dataKey: 'baseline',
150
+ label: baselineLabel,
151
+ color: baselineColor,
152
+ dotted: true,
153
+ },
154
+ ],
155
+ [
156
+ actualLabel,
157
+ historyColor,
158
+ forecastLabel,
159
+ forecastColor,
160
+ baselineLabel,
161
+ baselineColor,
162
+ ],
163
+ );
164
+
165
+ const scores = useMemo(
166
+ () =>
167
+ [...new Set(windows)]
168
+ .map(months => backtestScore(actuals, origins, months))
169
+ .filter((s): s is BacktestScore => s !== null),
170
+ [windows, actuals, origins],
171
+ );
172
+
173
+ const scoreLine =
174
+ renderScore ??
175
+ ((s: BacktestScore) => defaultScoreLine(s, formatPercent, baselineLabel));
176
+
177
+ return (
178
+ <div className={cn(S.root, className)}>
179
+ <BaseChartWrapper
180
+ className={S.chart}
181
+ chartData={chartData}
182
+ historicalLineColor={historyColor}
183
+ forecastData={forecastData}
184
+ hiddenSeries={hiddenSeries}
185
+ // Each origin's lines share a month with its neighbours': a tooltip
186
+ // would list them all.
187
+ showTooltip={false}
188
+ showLegend={false}
189
+ showEndDots={false}
190
+ connectHistoryNulls
191
+ connectForecastNulls
192
+ renderId={renderId}
193
+ hasCombinedData={chartData.length > 0}
194
+ loading={false}
195
+ isDarkTheme={isDarkTheme}
196
+ height={height}
197
+ disableAnimation={disableAnimation}
198
+ formatNumber={formatNumber}
199
+ formatDate={formatDate}
200
+ />
201
+ {chartData.length > 0 ? (
202
+ <SeriesLegend
203
+ items={legend}
204
+ hiddenSeries={hiddenGroups as ReadonlySet<string>}
205
+ onToggle={toggle}
206
+ />
207
+ ) : null}
208
+ {scores.length > 0 ? (
209
+ <ul className={S.scores}>
210
+ {scores.map(s => (
211
+ <li key={s.months}>{scoreLine(s)}</li>
212
+ ))}
213
+ </ul>
214
+ ) : null}
215
+ </div>
216
+ );
217
+ }
218
+
219
+ function defaultScoreLine(
220
+ s: BacktestScore,
221
+ formatPercent: (value: number) => string,
222
+ baselineLabel: string,
223
+ ): ReactNode {
224
+ // Mid-sentence: the first letter drops its capital, unless the label
225
+ // starts with an acronym ("EUR spot held flat").
226
+ const baseline = /^.[A-Z]/.test(baselineLabel)
227
+ ? baselineLabel
228
+ : baselineLabel.charAt(0).toLowerCase() + baselineLabel.slice(1);
229
+ const head =
230
+ s.errorRemoved === null
231
+ ? s.forecastError > 0
232
+ ? `more error than the ${baseline}`
233
+ : null
234
+ : formatPercent(Math.abs(s.errorRemoved)) === formatPercent(0)
235
+ ? `about the same error as the ${baseline}`
236
+ : s.errorRemoved > 0
237
+ ? `removes ${formatPercent(s.errorRemoved)} of the error`
238
+ : `${formatPercent(-s.errorRemoved)} more error than the ${baseline}`;
239
+ return (
240
+ <>
241
+ <strong>Last {s.months} months:</strong> {head ? `${head} · ` : null}
242
+ MAPE {formatPercent(s.forecastError)} forecast,{' '}
243
+ {formatPercent(s.baselineError)} {baseline} ({s.count}{' '}
244
+ {s.count === 1 ? 'forecast' : 'forecasts'})
245
+ </>
246
+ );
247
+ }
@@ -0,0 +1,172 @@
1
+ import type { ChartDataPoint } from '#uilib/components/ui/ChartAreaInteractive/ChartAreaInteractive.types';
2
+ import { HISTORY_SERIES_KEY } from '#uilib/components/ui/ChartAreaInteractive/chartHistories';
3
+
4
+ /** One month's value: `date` is a sortable ISO date (`2024-03-01`). */
5
+ export type BacktestPoint = { date: string; value: number };
6
+
7
+ /**
8
+ * One backtest origin: a past month a forecast was made from.
9
+ * The baseline holds `value`, the last price known then, flat over the
10
+ * forecast's months.
11
+ */
12
+ export type BacktestOrigin = {
13
+ /** The month the forecast was made in: the last month with a known value. */
14
+ date: string;
15
+ /** The value known at `date`, held flat as the baseline. */
16
+ value: number;
17
+ /**
18
+ * The forecast for the months after `date`, in date order. Its last point
19
+ * is where it lands: the month the scores compare with the actual value.
20
+ */
21
+ forecast: BacktestPoint[];
22
+ };
23
+
24
+ /** One window's scores: mean absolute percentage error at the landing month. */
25
+ export type BacktestScore = {
26
+ /** The window: the last `months` calendar months up to the latest actual. */
27
+ months: number;
28
+ /** How many forecasts landed in the window with an actual to compare. */
29
+ count: number;
30
+ /** The forecast's MAPE, in percent. */
31
+ forecastError: number;
32
+ /** The held-flat baseline's MAPE, in percent. */
33
+ baselineError: number;
34
+ /**
35
+ * How much of the baseline's error the forecast removes, in percent
36
+ * (negative: the forecast has more error). Null when the baseline has none.
37
+ */
38
+ errorRemoved: number | null;
39
+ };
40
+
41
+ /** The data key of origin `index`'s forecast line. */
42
+ export const backtestForecastKey = (index: number) =>
43
+ `forecast_${backtestForecastId(index)}`;
44
+ /** The data key of origin `index`'s held-flat line. */
45
+ export const backtestBaselineKey = (index: number) =>
46
+ `forecast_${backtestBaselineId(index)}`;
47
+ export const backtestForecastId = (index: number) => index * 2;
48
+ export const backtestBaselineId = (index: number) => index * 2 + 1;
49
+
50
+ /** A date's calendar month as a number (year × 12 + month), or NaN. */
51
+ function monthIndex(date: string): number {
52
+ const m = /^(\d{4})-(\d{2})/.exec(date);
53
+ const month = m ? Number(m[2]) : 0;
54
+ return m && month >= 1 && month <= 12
55
+ ? Number(m[1]) * 12 + month - 1
56
+ : Number.NaN;
57
+ }
58
+
59
+ /** The first day of month `index` (monthIndex's inverse). */
60
+ function monthStart(index: number): string {
61
+ const y = Math.floor(index / 12);
62
+ const m = (index % 12) + 1;
63
+ return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-01`;
64
+ }
65
+
66
+ /**
67
+ * The chart's rows, one per calendar month from the first to the last, keyed
68
+ * `YYYY-MM-01` (a month with no value has a row of its own, so the x axis
69
+ * spaces months evenly): the actuals under `historical`, and for each origin
70
+ * its forecast (from the origin's value through every forecast month) and its
71
+ * baseline (the origin's value on the same months), each under its own key.
72
+ * A date that is not `YYYY-MM…` is left out.
73
+ */
74
+ export function buildBacktestRows(
75
+ actuals: BacktestPoint[],
76
+ origins: BacktestOrigin[],
77
+ ): ChartDataPoint[] {
78
+ const byMonth = new Map<number, ChartDataPoint>();
79
+ const row = (date: string) => {
80
+ const i = monthIndex(date);
81
+ if (!Number.isFinite(i)) return undefined;
82
+ let r = byMonth.get(i);
83
+ if (!r) {
84
+ r = { date: monthStart(i) };
85
+ byMonth.set(i, r);
86
+ }
87
+ return r;
88
+ };
89
+ for (const a of actuals) {
90
+ if (!Number.isFinite(a.value)) continue;
91
+ const r = row(a.date);
92
+ if (r) r[HISTORY_SERIES_KEY] = a.value;
93
+ }
94
+ origins.forEach((o, i) => {
95
+ if (o.forecast.length === 0) return;
96
+ const fKey = backtestForecastKey(i);
97
+ const bKey = backtestBaselineKey(i);
98
+ const start = row(o.date);
99
+ if (start) {
100
+ start[fKey] = o.value;
101
+ start[bKey] = o.value;
102
+ }
103
+ for (const p of o.forecast) {
104
+ const r = row(p.date);
105
+ if (!r) continue;
106
+ r[fKey] = p.value;
107
+ r[bKey] = o.value;
108
+ }
109
+ });
110
+ if (byMonth.size === 0) return [];
111
+ const first = Math.min(...byMonth.keys());
112
+ const last = Math.max(...byMonth.keys());
113
+ const rows: ChartDataPoint[] = [];
114
+ for (let i = first; i <= last; i++) {
115
+ rows.push(byMonth.get(i) ?? { date: monthStart(i) });
116
+ }
117
+ return rows;
118
+ }
119
+
120
+ /**
121
+ * The scores for the last `months` calendar months up to the latest actual:
122
+ * every origin whose forecast lands in one of them, against that month's
123
+ * actual. Dates match by calendar month (`2024-03-01` and `2024-03-31` are
124
+ * one month). Null when the actuals span fewer months than the window, or
125
+ * no forecast lands in it with a non-zero actual to compare.
126
+ */
127
+ export function backtestScore(
128
+ actuals: BacktestPoint[],
129
+ origins: BacktestOrigin[],
130
+ months: number,
131
+ ): BacktestScore | null {
132
+ const actualByMonth = new Map<number, number>();
133
+ for (const a of actuals) {
134
+ const i = monthIndex(a.date);
135
+ if (Number.isFinite(i) && Number.isFinite(a.value)) {
136
+ actualByMonth.set(i, a.value);
137
+ }
138
+ }
139
+ if (months <= 0 || actualByMonth.size === 0) return null;
140
+ const last = Math.max(...actualByMonth.keys());
141
+ const first = Math.min(...actualByMonth.keys());
142
+ if (last - first + 1 < months) return null;
143
+ const from = last - months + 1;
144
+ let forecastSum = 0;
145
+ let baselineSum = 0;
146
+ let count = 0;
147
+ for (const o of origins) {
148
+ const landing = o.forecast[o.forecast.length - 1];
149
+ if (!landing) continue;
150
+ const i = monthIndex(landing.date);
151
+ if (!(i >= from && i <= last)) continue;
152
+ const actual = actualByMonth.get(i);
153
+ if (actual === undefined || actual === 0 || !Number.isFinite(actual)) {
154
+ continue;
155
+ }
156
+ if (!Number.isFinite(landing.value) || !Number.isFinite(o.value)) continue;
157
+ forecastSum += Math.abs((landing.value - actual) / actual);
158
+ baselineSum += Math.abs((o.value - actual) / actual);
159
+ count += 1;
160
+ }
161
+ if (count === 0) return null;
162
+ const forecastError = (forecastSum / count) * 100;
163
+ const baselineError = (baselineSum / count) * 100;
164
+ return {
165
+ months,
166
+ count,
167
+ forecastError,
168
+ baselineError,
169
+ errorRemoved:
170
+ baselineError > 0 ? (1 - forecastError / baselineError) * 100 : null,
171
+ };
172
+ }
@@ -0,0 +1,8 @@
1
+ export { BacktestChart, type BacktestChartProps } from './BacktestChart';
2
+ export {
3
+ type BacktestOrigin,
4
+ type BacktestPoint,
5
+ type BacktestScore,
6
+ backtestScore,
7
+ buildBacktestRows,
8
+ } from './backtestChart.helpers';
@@ -0,0 +1,94 @@
1
+ import { useMemo, useState } from 'react';
2
+
3
+ import { PageContentSection } from '#uilib/components/ui/Page';
4
+ import { Tabs, TabsList, TabsTrigger } from '#uilib/components/ui/Tabs';
5
+ import {
6
+ BacktestChart,
7
+ type BacktestOrigin,
8
+ type BacktestPoint,
9
+ } from '#uilib/components/widgets/BacktestChart';
10
+ import BacktestChartGuidance from '#uilib/components/widgets/BacktestChart/AGENT.md';
11
+ import { useTheme } from '#uilib/contexts/theme-context';
12
+
13
+ import { AppPageHeader } from '../components/AppPageHeader/AppPageHeader';
14
+ import { DocsGuidance } from '../components/DocsGuidance/DocsGuidance';
15
+ import { DocsHeaderActions } from '../docsHeaderActions';
16
+
17
+ const HORIZONS = [1, 3, 6] as const;
18
+
19
+ function monthKey(i: number): string {
20
+ const y = 2021 + Math.floor(i / 12);
21
+ return `${y}-${String((i % 12) + 1).padStart(2, '0')}-01`;
22
+ }
23
+
24
+ /** An invented monthly price. */
25
+ const ACTUALS: BacktestPoint[] = Array.from({ length: 48 }, (_, i) => ({
26
+ date: monthKey(i),
27
+ value: 100 + i * 0.8 + Math.sin(i * 0.45) * 9,
28
+ }));
29
+
30
+ /** A forecast that sees the trend and part of the swing, made each month. */
31
+ function buildOrigins(horizon: number): BacktestOrigin[] {
32
+ const origins: BacktestOrigin[] = [];
33
+ for (let o = 12; o + horizon < ACTUALS.length; o++) {
34
+ origins.push({
35
+ date: ACTUALS[o].date,
36
+ value: ACTUALS[o].value,
37
+ forecast: Array.from({ length: horizon }, (_, k) => {
38
+ const i = o + k + 1;
39
+ return {
40
+ date: ACTUALS[i].date,
41
+ value: 100 + i * 0.8 + Math.sin(i * 0.45 - 0.3) * 7,
42
+ };
43
+ }),
44
+ });
45
+ }
46
+ return origins;
47
+ }
48
+
49
+ export default function BacktestChartPage() {
50
+ const { isDarkMode } = useTheme();
51
+ const [horizon, setHorizon] = useState<number>(3);
52
+ const origins = useMemo(() => buildOrigins(horizon), [horizon]);
53
+ return (
54
+ <>
55
+ <AppPageHeader
56
+ breadcrumbs={[{ label: 'Backtest chart' }]}
57
+ title="BacktestChart"
58
+ subheader="Past forecasts for one horizon against the last value held flat, with how much of its error they remove."
59
+ actions={<DocsHeaderActions />}
60
+ />
61
+ <DocsGuidance source={BacktestChartGuidance} />
62
+ <PageContentSection>
63
+ <div
64
+ style={{
65
+ display: 'flex',
66
+ flexDirection: 'column',
67
+ gap: 16,
68
+ width: '100%',
69
+ }}
70
+ >
71
+ <Tabs
72
+ value={String(horizon)}
73
+ onValueChange={v => setHorizon(Number(v))}
74
+ >
75
+ <TabsList>
76
+ {HORIZONS.map(h => (
77
+ <TabsTrigger key={h} value={String(h)}>
78
+ {h}m
79
+ </TabsTrigger>
80
+ ))}
81
+ </TabsList>
82
+ </Tabs>
83
+ <BacktestChart
84
+ key={horizon}
85
+ actuals={ACTUALS}
86
+ origins={origins}
87
+ isDarkTheme={isDarkMode}
88
+ formatNumber={v => v.toFixed(0)}
89
+ />
90
+ </div>
91
+ </PageContentSection>
92
+ </>
93
+ );
94
+ }
@@ -1,10 +1,19 @@
1
+ import { useState } from 'react';
2
+
1
3
  import { Button } from '#uilib/components/ui/Button';
2
4
  import {
3
5
  DropdownMenu,
6
+ DropdownMenuCheckboxItem,
4
7
  DropdownMenuContent,
5
8
  DropdownMenuItem,
6
9
  DropdownMenuLabel,
10
+ DropdownMenuPortal,
11
+ DropdownMenuRadioGroup,
12
+ DropdownMenuRadioItem,
7
13
  DropdownMenuSeparator,
14
+ DropdownMenuSub,
15
+ DropdownMenuSubContent,
16
+ DropdownMenuSubTrigger,
8
17
  DropdownMenuTrigger,
9
18
  } from '#uilib/components/ui/DropdownMenu';
10
19
  import DropdownMenuGuidance from '#uilib/components/ui/DropdownMenu/AGENT.md';
@@ -14,6 +23,102 @@ import { AppPageHeader } from '../components/AppPageHeader/AppPageHeader';
14
23
  import { DocsGuidance } from '../components/DocsGuidance/DocsGuidance';
15
24
  import { DocsHeaderActions } from '../docsHeaderActions';
16
25
 
26
+ const FILTER_OPTIONS = [
27
+ {
28
+ key: 'product',
29
+ label: 'Product',
30
+ options: ['Resin A', 'Steel coil', 'Copper wire'],
31
+ },
32
+ {
33
+ key: 'supplier',
34
+ label: 'Supplier',
35
+ options: ['Company A', 'Company B', 'Company C'],
36
+ },
37
+ { key: 'customer', label: 'Customer', options: ['Company D', 'Company E'] },
38
+ ] as const;
39
+
40
+ type FilterKey = (typeof FILTER_OPTIONS)[number]['key'];
41
+
42
+ const DATE_RANGES = [
43
+ 'Last 7 days',
44
+ 'Last 30 days',
45
+ 'Last 90 days',
46
+ 'This year',
47
+ ];
48
+
49
+ function FilterByMenu() {
50
+ const [selected, setSelected] = useState<Record<FilterKey, string[]>>({
51
+ product: [],
52
+ supplier: [],
53
+ customer: [],
54
+ });
55
+ const [dateRange, setDateRange] = useState(DATE_RANGES[1]);
56
+
57
+ const toggle = (key: FilterKey, option: string, checked: boolean) =>
58
+ setSelected(prev => ({
59
+ ...prev,
60
+ [key]: checked
61
+ ? [...prev[key], option]
62
+ : prev[key].filter(o => o !== option),
63
+ }));
64
+
65
+ return (
66
+ <DropdownMenu>
67
+ <DropdownMenuTrigger asChild>
68
+ <Button type="button" variant="outline">
69
+ Filter by
70
+ </Button>
71
+ </DropdownMenuTrigger>
72
+ <DropdownMenuContent>
73
+ {FILTER_OPTIONS.map(({ key, label, options }) => (
74
+ <DropdownMenuSub key={key}>
75
+ <DropdownMenuSubTrigger>{label}</DropdownMenuSubTrigger>
76
+ {/* SubContent is not portalled by default; inside the parent's
77
+ scroll box it would be clipped, so wrap it in a portal. */}
78
+ <DropdownMenuPortal>
79
+ <DropdownMenuSubContent>
80
+ {options.map(option => (
81
+ <DropdownMenuCheckboxItem
82
+ key={option}
83
+ checked={selected[key].includes(option)}
84
+ onCheckedChange={checked =>
85
+ toggle(key, option, checked === true)
86
+ }
87
+ onSelect={e => e.preventDefault()}
88
+ >
89
+ {option}
90
+ </DropdownMenuCheckboxItem>
91
+ ))}
92
+ </DropdownMenuSubContent>
93
+ </DropdownMenuPortal>
94
+ </DropdownMenuSub>
95
+ ))}
96
+ <DropdownMenuSub>
97
+ <DropdownMenuSubTrigger>Date range</DropdownMenuSubTrigger>
98
+ <DropdownMenuPortal>
99
+ <DropdownMenuSubContent>
100
+ <DropdownMenuRadioGroup
101
+ value={dateRange}
102
+ onValueChange={setDateRange}
103
+ >
104
+ {DATE_RANGES.map(range => (
105
+ <DropdownMenuRadioItem
106
+ key={range}
107
+ value={range}
108
+ onSelect={e => e.preventDefault()}
109
+ >
110
+ {range}
111
+ </DropdownMenuRadioItem>
112
+ ))}
113
+ </DropdownMenuRadioGroup>
114
+ </DropdownMenuSubContent>
115
+ </DropdownMenuPortal>
116
+ </DropdownMenuSub>
117
+ </DropdownMenuContent>
118
+ </DropdownMenu>
119
+ );
120
+ }
121
+
17
122
  export default function DropdownMenuPage() {
18
123
  return (
19
124
  <>
@@ -24,20 +129,29 @@ export default function DropdownMenuPage() {
24
129
  actions={<DocsHeaderActions />}
25
130
  />
26
131
  <DocsGuidance source={DropdownMenuGuidance} />
27
- <PageContentSection>
28
- <DropdownMenu>
29
- <DropdownMenuTrigger asChild>
30
- <Button type="button" variant="outline">
31
- Open menu
32
- </Button>
33
- </DropdownMenuTrigger>
34
- <DropdownMenuContent>
35
- <DropdownMenuLabel>Actions</DropdownMenuLabel>
36
- <DropdownMenuSeparator />
37
- <DropdownMenuItem onSelect={() => {}}>Item one</DropdownMenuItem>
38
- <DropdownMenuItem onSelect={() => {}}>Item two</DropdownMenuItem>
39
- </DropdownMenuContent>
40
- </DropdownMenu>
132
+ <PageContentSection
133
+ style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}
134
+ >
135
+ <section>
136
+ <h3 style={{ marginBottom: '1rem' }}>Basic</h3>
137
+ <DropdownMenu>
138
+ <DropdownMenuTrigger asChild>
139
+ <Button type="button" variant="outline">
140
+ Open menu
141
+ </Button>
142
+ </DropdownMenuTrigger>
143
+ <DropdownMenuContent>
144
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
145
+ <DropdownMenuSeparator />
146
+ <DropdownMenuItem onSelect={() => {}}>Item one</DropdownMenuItem>
147
+ <DropdownMenuItem onSelect={() => {}}>Item two</DropdownMenuItem>
148
+ </DropdownMenuContent>
149
+ </DropdownMenu>
150
+ </section>
151
+ <section>
152
+ <h3 style={{ marginBottom: '1rem' }}>Nested (sub-menus)</h3>
153
+ <FilterByMenu />
154
+ </section>
41
155
  </PageContentSection>
42
156
  </>
43
157
  );
@@ -308,6 +308,12 @@ export const DOC_REGISTRY: DocEntry[] = [
308
308
  section: 'Widgets',
309
309
  load: () => import('./pages/DriverMapPage'),
310
310
  },
311
+ {
312
+ slug: 'backtest-chart',
313
+ title: 'BacktestChart',
314
+ section: 'Widgets',
315
+ load: () => import('./pages/BacktestChartPage'),
316
+ },
311
317
  {
312
318
  slug: 'drivers-comparison-chart',
313
319
  title: 'DriversComparisonChart',