-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChart.tsx
More file actions
362 lines (335 loc) · 9.25 KB
/
Chart.tsx
File metadata and controls
362 lines (335 loc) · 9.25 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import {
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
import {
CandlestickSeries,
createChart,
type CandlestickSeriesPartialOptions,
type ChartOptions,
type DeepPartial,
type IChartApi,
type ISeriesApi,
type UTCTimestamp,
} from "lightweight-charts";
import { describeError, TIMEFRAMES, type Candle, type Timeframe } from "./api";
import { useMagnetic, useOhlc, useThemeObserver, useTimeframe } from "./hooks";
import { RetryButton } from "./RetryButton";
const TF_LABELS: Record<Timeframe, string> = {
"1D": "1-day",
"7D": "7-day",
"30D": "30-day",
"1Y": "1-year",
};
// CoinGecko OHLC granularity is fixed by window (free tier):
// 1-2d → 30m candles, 3-30d → 4h, 31+d → 4d. Surfacing this avoids the
// common "why is the 1D chart so jagged?" confusion during review.
const TF_CANDLE: Record<Timeframe, string> = {
"1D": "30-minute candles",
"7D": "4-hour candles",
"30D": "4-hour candles",
"1Y": "4-day candles",
};
export function Chart() {
const [timeframe, setTimeframe] = useTimeframe();
const query = useOhlc(timeframe);
const cardProps = {
timeframe,
onTimeframeChange: setTimeframe,
isFetching: query.isFetching,
};
if (query.isPending) {
return (
<ChartCard {...cardProps}>
<ChartSkeleton />
</ChartCard>
);
}
if (query.isError && !query.data) {
const { heading, message } = describeError(query.error);
return (
<ChartCard {...cardProps} variant="error" heading={heading}>
<p className="card__error-msg">{message}</p>
<RetryButton onClick={() => query.refetch()} fetching={query.isFetching} />
</ChartCard>
);
}
if (query.data.length === 0) {
return (
<ChartCard {...cardProps}>
<div className="chart-empty" role="status">
No candles for this timeframe
</div>
</ChartCard>
);
}
// isRefreshing = refetch or timeframe-swap in progress while the previous
// candles are still visible (keepPreviousData in useOhlc holds them). Drives
// the chart-canvas crossfade so tf changes feel like a dissolve, not a snap.
const isRefreshing = query.isFetching && !query.isPending;
return (
<ChartCard {...cardProps}>
<ChartCanvas data={query.data} isRefreshing={isRefreshing} />
</ChartCard>
);
}
interface ChartCardProps {
children: ReactNode;
timeframe: Timeframe;
onTimeframeChange: (t: Timeframe) => void;
isFetching: boolean;
variant?: "error";
heading?: string;
}
function ChartCard({
children,
timeframe,
onTimeframeChange,
isFetching,
variant,
heading,
}: ChartCardProps) {
const isError = variant === "error";
return (
<section
className={`card chart-card${isError ? " card--error" : ""}`}
aria-label={`Bitcoin ${TF_LABELS[timeframe]} price history`}
role={isError ? "alert" : undefined}
>
<header className="card__head">
<div className="card__meta">
<span className={isError ? "eyebrow eyebrow--error" : "eyebrow"}>
{heading ?? "Price History"}
</span>
<span
className={`dot ${isFetching ? "dot--live" : ""}`}
aria-hidden="true"
/>
</div>
<TimeframeSwitcher value={timeframe} onChange={onTimeframeChange} />
</header>
{children}
{!isError && (
<p className="eyebrow chart-meta">
source · CoinGecko · {TF_CANDLE[timeframe]}
</p>
)}
</section>
);
}
function cssVar(name: string): string {
return getComputedStyle(document.documentElement)
.getPropertyValue(name)
.trim();
}
function baseChartOptions(): DeepPartial<ChartOptions> {
return {
autoSize: true,
layout: {
background: { color: "transparent" },
textColor: cssVar("--fg-mute"),
fontFamily: cssVar("--font-mono"),
fontSize: 11,
},
grid: {
vertLines: { color: cssVar("--border") },
horzLines: { color: cssVar("--border") },
},
crosshair: { mode: 1 },
timeScale: {
borderVisible: false,
timeVisible: true,
secondsVisible: false,
},
rightPriceScale: { borderVisible: false },
};
}
function seriesColors(): CandlestickSeriesPartialOptions {
const up = cssVar("--up");
const down = cssVar("--down");
return {
upColor: up,
downColor: down,
borderUpColor: up,
borderDownColor: down,
wickUpColor: up,
wickDownColor: down,
borderVisible: true,
};
}
function ChartCanvas({ data, isRefreshing }: { data: Candle[]; isRefreshing: boolean }) {
const containerRef = useRef<HTMLDivElement | null>(null);
const chartRef = useRef<IChartApi | null>(null);
const seriesRef = useRef<ISeriesApi<"Candlestick"> | null>(null);
const theme = useThemeObserver();
// Mount once — create chart + candlestick series. Cleanup tears down cleanly
// so React StrictMode's double-invoke in dev doesn't leak a canvas.
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const chart = createChart(container, baseChartOptions());
const series = chart.addSeries(CandlestickSeries, seriesColors());
chartRef.current = chart;
seriesRef.current = series;
return () => {
chart.remove();
chartRef.current = null;
seriesRef.current = null;
};
}, []);
// Push new data — replaces the full window, then re-frames.
useEffect(() => {
const series = seriesRef.current;
const chart = chartRef.current;
if (!series || !chart) return;
series.setData(
data.map((c) => ({
time: c.time as UTCTimestamp,
open: c.open,
high: c.high,
low: c.low,
close: c.close,
}))
);
chart.timeScale().fitContent();
}, [data]);
// Recolor on theme swap without remount.
useEffect(() => {
const chart = chartRef.current;
const series = seriesRef.current;
if (!chart || !series) return;
chart.applyOptions(baseChartOptions());
series.applyOptions(seriesColors());
}, [theme]);
return (
<div
ref={containerRef}
className="chart-canvas"
data-refreshing={isRefreshing ? "true" : undefined}
aria-hidden="true"
/>
);
}
function TimeframeSwitcher({
value,
onChange,
}: {
value: Timeframe;
onChange: (next: Timeframe) => void;
}) {
const containerRef = useRef<HTMLDivElement | null>(null);
const btnRefs = useRef<Partial<Record<Timeframe, HTMLButtonElement | null>>>({});
const [pill, setPill] = useState({ x: 0, w: 0 });
// Measure active button position before paint — no flash at stale coords.
useLayoutEffect(() => {
const btn = btnRefs.current[value];
if (!btn) return;
setPill({ x: btn.offsetLeft, w: btn.offsetWidth });
}, [value]);
// Re-measure on container resize (window resize, font metrics change, etc.)
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const ro = new ResizeObserver(() => {
const btn = btnRefs.current[value];
if (!btn) return;
setPill({ x: btn.offsetLeft, w: btn.offsetWidth });
});
ro.observe(container);
return () => ro.disconnect();
}, [value]);
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
const idx = TIMEFRAMES.indexOf(value);
const dir = e.key === "ArrowRight" ? 1 : -1;
const next = TIMEFRAMES[(idx + dir + TIMEFRAMES.length) % TIMEFRAMES.length];
onChange(next);
btnRefs.current[next]?.focus();
};
return (
<div
ref={containerRef}
className="tfs"
role="tablist"
aria-label="Chart timeframe"
onKeyDown={onKeyDown}
>
<span
className="tfs__pill"
aria-hidden="true"
style={{ transform: `translateX(${pill.x}px)`, width: `${pill.w}px` }}
/>
{TIMEFRAMES.map((t) => (
<TimeframeButton
key={t}
timeframe={t}
active={t === value}
onRef={(el) => {
btnRefs.current[t] = el;
}}
onClick={() => onChange(t)}
/>
))}
</div>
);
}
function TimeframeButton({
timeframe,
active,
onRef,
onClick,
}: {
timeframe: Timeframe;
active: boolean;
onRef: (el: HTMLButtonElement | null) => void;
onClick: () => void;
}) {
const ref = useRef<HTMLButtonElement | null>(null);
useMagnetic(ref, 0.22);
return (
<button
ref={(el) => {
ref.current = el;
onRef(el);
}}
className="tfs__btn"
type="button"
role="tab"
aria-selected={active}
aria-label={TF_LABELS[timeframe]}
tabIndex={active ? 0 : -1}
data-interactive
onClick={onClick}
>
{timeframe}
</button>
);
}
function ChartSkeleton() {
const heights = useMemo(() => {
const out: number[] = [];
let v = 0.55;
for (let i = 0; i < 24; i++) {
v = Math.min(0.95, Math.max(0.25, v + Math.sin(i * 1.7) * 0.12));
out.push(Math.round(v * 100));
}
return out;
}, []);
return (
<div className="chart-skeleton" aria-busy="true" aria-label="Loading chart">
{heights.map((h, i) => (
<span
key={i}
className="chart-skeleton__bar skeleton"
style={{ height: `${h}%` }}
/>
))}
</div>
);
}