-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathOddsChart.tsx
More file actions
260 lines (230 loc) Β· 8.85 KB
/
Copy pathOddsChart.tsx
File metadata and controls
260 lines (230 loc) Β· 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"use client";
import { useEffect, useState, useCallback } from "react";
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
TooltipProps,
} from "recharts";
import Skeleton from "./Skeleton";
import { useChartTheme } from "./ChartThemeProvider";
// ββ Types βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export type TimeRange = "1H" | "6H" | "1D" | "All";
export interface OddsPoint {
timestamp: string;
yes: number;
no: number;
}
interface Props {
marketId: number;
/** Optional pre-loaded data (SSR / testing) */
initialData?: OddsPoint[];
/** Override fetch function (testing) */
fetcher?: (marketId: number, range: TimeRange) => Promise<OddsPoint[]>;
}
// ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const RANGES: TimeRange[] = ["1H", "6H", "1D", "All"];
// ββ Mock data generator (used until real API exists) ββββββββββββββββββββββββββ
function generateMockData(range: TimeRange): OddsPoint[] {
const pointsMap: Record<TimeRange, number> = { "1H": 12, "6H": 24, "1D": 48, All: 96 };
const intervalMs: Record<TimeRange, number> = {
"1H": 5 * 60 * 1000,
"6H": 15 * 60 * 1000,
"1D": 30 * 60 * 1000,
All: 60 * 60 * 1000,
};
const points = pointsMap[range];
const interval = intervalMs[range];
const now = Date.now();
let yes = 50 + (Math.random() - 0.5) * 20;
return Array.from({ length: points }, (_, i) => {
yes = Math.max(5, Math.min(95, yes + (Math.random() - 0.5) * 6));
const no = parseFloat((100 - yes).toFixed(1));
const ts = new Date(now - (points - i) * interval);
const label =
range === "All" || range === "1D"
? ts.toLocaleDateString([], { month: "short", day: "numeric" })
: ts.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
return { timestamp: label, yes: parseFloat(yes.toFixed(1)), no };
});
}
// ββ Default fetcher (real API) ββββββββββββββββββββββββββββββββββββββββββββββββ
async function defaultFetcher(marketId: number, range: TimeRange): Promise<OddsPoint[]> {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/markets/${marketId}/stats?range=${range}`
);
if (!res.ok) throw new Error("Failed to fetch odds history");
return res.json();
}
// ββ Crosshair Tooltip βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function CrosshairTooltip({ active, payload, label }: TooltipProps<number, string>) {
const colors = useChartTheme();
if (!active || !payload?.length) return null;
const yes = payload.find((p) => p.dataKey === "yes");
const no = payload.find((p) => p.dataKey === "no");
return (
<div
data-testid="odds-tooltip"
style={{
backgroundColor: colors.tooltipBg,
borderColor: colors.tooltipBorder,
color: "white",
}}
className="rounded-lg px-3 py-2 text-xs shadow-xl space-y-1"
>
<p className="text-gray-400">{label}</p>
{yes && (
<p style={{ color: colors.yes }} className="font-semibold">
YES: {yes.value}%
</p>
)}
{no && (
<p style={{ color: colors.no }} className="font-semibold">
NO: {no.value}%
</p>
)}
</div>
);
}
// ββ OddsChart βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export default function OddsChart({ marketId, initialData, fetcher = defaultFetcher }: Props) {
const [range, setRange] = useState<TimeRange>("1D");
const [data, setData] = useState<OddsPoint[]>(initialData ?? []);
const [loading, setLoading] = useState(!initialData);
const colors = useChartTheme();
const loadData = useCallback(
async (r: TimeRange) => {
setLoading(true);
try {
const result = await fetcher(marketId, r);
setData(result);
} catch {
// Fallback to mock data so the chart is always renderable
setData(generateMockData(r));
} finally {
setLoading(false);
}
},
[marketId, fetcher]
);
useEffect(() => {
if (!initialData) loadData(range);
}, [range, loadData, initialData]);
function handleRangeChange(r: TimeRange) {
setRange(r);
loadData(r);
}
return (
<div
data-testid="odds-chart"
className="bg-gray-900 rounded-xl border border-gray-800 p-4 space-y-3"
>
{/* Header */}
<div className="flex items-center justify-between flex-wrap gap-2">
<h2 className="text-white font-semibold text-base">Odds History</h2>
{/* Time range toggle */}
<div className="flex gap-1" role="group" aria-label="Time range">
{RANGES.map((r) => (
<button
key={r}
data-testid={`range-btn-${r}`}
onClick={() => handleRangeChange(r)}
aria-pressed={range === r}
className={`px-2.5 py-1 rounded-lg text-xs font-medium transition-colors ${
range === r
? "bg-blue-600 text-white"
: "bg-gray-800 text-gray-400 hover:bg-gray-700"
}`}
>
{r}
</button>
))}
</div>
</div>
{/* Legend */}
<div className="flex gap-4 text-xs">
<span className="flex items-center gap-1.5">
<span
className="inline-block w-2.5 h-2.5 rounded-full"
style={{ backgroundColor: colors.yes }}
/>
<span className="text-gray-300">YES</span>
</span>
<span className="flex items-center gap-1.5">
<span
className="inline-block w-2.5 h-2.5 rounded-full"
style={{ backgroundColor: colors.no }}
/>
<span className="text-gray-300">NO</span>
</span>
</div>
{/* Chart or skeleton */}
{loading ? (
<Skeleton data-testid="odds-chart-skeleton" className="h-64 w-full rounded-lg" />
) : (
<div
className="w-full overflow-x-auto touch-pan-x"
style={{ WebkitOverflowScrolling: "touch" }}
>
<div style={{ minWidth: 300 }}>
<ResponsiveContainer width="100%" height={256}>
<AreaChart data={data} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
<defs>
<linearGradient id="gradYes" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={YES_COLOR} stopOpacity={0.35} />
<stop offset="95%" stopColor={YES_COLOR} stopOpacity={0} />
</linearGradient>
<linearGradient id="gradNo" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={NO_COLOR} stopOpacity={0.35} />
<stop offset="95%" stopColor={NO_COLOR} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke={colors.grid} />
<XAxis
dataKey="timestamp"
tick={{ fill: "#6b7280", fontSize: 10 }}
tickLine={false}
axisLine={false}
interval="preserveStartEnd"
/>
<YAxis
domain={[0, 100]}
tick={{ fill: "#6b7280", fontSize: 10 }}
tickLine={false}
axisLine={false}
tickFormatter={(v) => `${v}%`}
/>
<Tooltip
content={<CrosshairTooltip />}
cursor={{ stroke: "#4b5563", strokeWidth: 1, strokeDasharray: "4 2" }}
/>
<Area
type="monotone"
dataKey="yes"
stroke={YES_COLOR}
strokeWidth={2}
fill="url(#gradYes)"
dot={false}
activeDot={{ r: 4, fill: YES_COLOR }}
/>
<Area
type="monotone"
dataKey="no"
stroke={NO_COLOR}
strokeWidth={2}
fill="url(#gradNo)"
dot={false}
activeDot={{ r: 4, fill: NO_COLOR }}
/>
</AreaChart>
</ResponsiveContainer>
</div>
</div>
)}
</div>
);
}