|
1 | | -import type { Nullish } from "@pythnetwork/shared-lib/types"; |
2 | | -import { isNullOrUndefined } from "@pythnetwork/shared-lib/util"; |
3 | 1 | import { capitalCase } from "change-case"; |
4 | | -import { |
5 | | - Chart, |
6 | | - CategoryScale, |
7 | | - LinearScale, |
8 | | - LineController, |
9 | | - LineElement, |
10 | | - PointElement, |
11 | | - Tooltip, |
12 | | - Legend, |
13 | | - TimeScale, |
14 | | -} from "chart.js"; |
15 | | -import { formatDate } from "date-fns"; |
16 | | -import { useEffect, useLayoutEffect, useRef, useState } from "react"; |
17 | | - |
18 | | -import classes from "./index.module.scss"; |
| 2 | +import type { |
| 3 | + IChartApi, |
| 4 | + ISeriesApi, |
| 5 | + LineData, |
| 6 | + UTCTimestamp, |
| 7 | +} from "lightweight-charts"; |
| 8 | +import { createChart, LineSeries } from "lightweight-charts"; |
| 9 | +import { useEffect, useLayoutEffect, useRef } from "react"; |
| 10 | + |
19 | 11 | import type { AppStateContextVal } from "../../context/pyth-pro-demo"; |
20 | 12 | import { usePythProAppStateContext } from "../../context/pyth-pro-demo"; |
21 | | -import { getColorForSymbol, isAllowedSymbol } from "../../util/pyth-pro-demo"; |
22 | | - |
23 | | -Chart.register( |
24 | | - CategoryScale, |
25 | | - LinearScale, |
26 | | - LineController, |
27 | | - LineElement, |
28 | | - PointElement, |
29 | | - Tooltip, |
30 | | - Legend, |
31 | | - TimeScale, |
32 | | -); |
33 | | - |
34 | | -type ChartJSPoint = { x: number; y: number }; |
| 13 | +import { |
| 14 | + getColorForSymbol, |
| 15 | + getThemeCssVar, |
| 16 | + isAllowedSymbol, |
| 17 | +} from "../../util/pyth-pro-demo"; |
35 | 18 |
|
36 | 19 | type PythProDemoPriceChartImplProps = Pick< |
37 | 20 | AppStateContextVal, |
38 | 21 | "dataSourcesInUse" | "metrics" | "selectedSource" |
39 | 22 | >; |
40 | 23 |
|
41 | | -const MAX_DATA_AGE = 1000 * 60; // hold no more than one minute's worth of data in the chart |
42 | | -const MAX_DATA_POINTS = 3000; // don't keep more than 3K points in memory |
| 24 | +const MAX_DATA_AGE = 1000 * 60; // 1 minute |
| 25 | +const MAX_DATA_POINTS = 3000; |
43 | 26 |
|
44 | | -function PythProDemoPriceChartImpl({ |
| 27 | +export function PythProDemoPriceChartImpl({ |
45 | 28 | dataSourcesInUse, |
46 | 29 | metrics, |
47 | 30 | selectedSource, |
48 | 31 | }: PythProDemoPriceChartImplProps) { |
49 | | - /** state */ |
50 | | - const [canvasRef, setCanvasRef] = |
51 | | - useState<Nullish<HTMLCanvasElement>>(undefined); |
| 32 | + const containerRef = useRef<HTMLDivElement | null>(null); |
| 33 | + const chartRef = useRef<IChartApi>(undefined); |
| 34 | + const seriesMapRef = useRef<Record<string, ISeriesApi<"Line">>>({}); |
52 | 35 |
|
53 | | - /** refs */ |
54 | | - const chartHandlerRef = useRef<Nullish<Chart>>(undefined); |
| 36 | + useLayoutEffect(() => { |
| 37 | + if (!containerRef.current) return; |
55 | 38 |
|
56 | | - /** effects */ |
57 | | - useEffect(() => { |
58 | | - if (!canvasRef) return; |
59 | | - const c = new Chart(canvasRef, { |
60 | | - type: "line", |
61 | | - data: { datasets: [] }, |
62 | | - options: { |
63 | | - animation: false, |
64 | | - elements: { |
65 | | - point: { radius: 0 }, |
66 | | - }, |
67 | | - responsive: true, |
68 | | - maintainAspectRatio: false, |
69 | | - scales: { |
70 | | - x: { |
71 | | - beginAtZero: false, |
72 | | - type: "linear", // push numeric timestamps or indices |
73 | | - grid: { display: true }, |
74 | | - ticks: { |
75 | | - callback(val) { |
76 | | - const num = Number(val); |
77 | | - const d = new Date(); |
78 | | - d.setTime(num); |
79 | | - |
80 | | - return formatDate(d, "pp"); |
81 | | - }, |
82 | | - display: true, |
83 | | - }, |
84 | | - }, |
85 | | - y: { type: "linear", beginAtZero: false, grid: { display: true } }, |
86 | | - }, |
87 | | - plugins: { |
88 | | - legend: { |
89 | | - display: true, |
90 | | - labels: { |
91 | | - generateLabels: (chart) => { |
92 | | - // Start with the default labels |
93 | | - const original = |
94 | | - Chart.defaults.plugins.legend.labels.generateLabels(chart); |
95 | | - |
96 | | - // Map them to whatever text you want |
97 | | - return original.map((label) => ({ |
98 | | - ...label, |
99 | | - text: capitalCase(label.text), |
100 | | - })); |
101 | | - }, |
102 | | - usePointStyle: true, |
103 | | - }, |
104 | | - }, |
105 | | - tooltip: { enabled: false }, |
106 | | - }, |
| 39 | + const grayColor = getThemeCssVar("--theme-palette-gray-800") ?? "#ccc"; |
| 40 | + const grayText = getThemeCssVar("--theme-palette-gray-300") ?? "#f1f1f3"; |
| 41 | + |
| 42 | + const chart = createChart(containerRef.current, { |
| 43 | + layout: { |
| 44 | + attributionLogo: false, // hide TradingView logo |
| 45 | + background: { color: "transparent" }, |
| 46 | + textColor: grayText, |
| 47 | + }, |
| 48 | + grid: { |
| 49 | + horzLines: { color: grayColor }, |
| 50 | + vertLines: { color: grayColor }, |
| 51 | + }, |
| 52 | + rightPriceScale: { |
| 53 | + borderColor: grayColor, |
| 54 | + }, |
| 55 | + timeScale: { |
| 56 | + barSpacing: 3, |
| 57 | + borderColor: grayColor, |
| 58 | + rightOffset: 0, |
| 59 | + secondsVisible: true, |
| 60 | + timeVisible: true, |
107 | 61 | }, |
108 | 62 | }); |
109 | 63 |
|
110 | | - chartHandlerRef.current = c; |
111 | | - }, [canvasRef]); |
| 64 | + chartRef.current = chart; |
| 65 | + |
| 66 | + return () => { |
| 67 | + chart.remove(); |
| 68 | + chartRef.current = undefined; |
| 69 | + seriesMapRef.current = {}; |
| 70 | + }; |
| 71 | + }, []); |
112 | 72 |
|
113 | 73 | useEffect(() => { |
114 | | - if (!chartHandlerRef.current || !isAllowedSymbol(selectedSource)) return; |
115 | | - const { current: c } = chartHandlerRef; |
| 74 | + if (!chartRef.current || !isAllowedSymbol(selectedSource)) return; |
116 | 75 |
|
117 | 76 | for (const dataSource of dataSourcesInUse) { |
118 | 77 | const latest = metrics[dataSource]?.latest; |
119 | 78 | const symbolMetrics = latest?.[selectedSource]; |
120 | | - if ( |
121 | | - isNullOrUndefined(symbolMetrics) || |
122 | | - isNullOrUndefined(symbolMetrics.price) |
123 | | - ) { |
124 | | - continue; |
125 | | - } |
126 | | - |
127 | | - let ds = c.data.datasets.find((d) => d.label === dataSource); |
128 | | - if (!ds) { |
129 | | - ds = { |
130 | | - data: [], |
131 | | - borderColor: getColorForSymbol(dataSource), |
132 | | - label: dataSource, |
133 | | - pointBorderWidth: 1, |
134 | | - pointRadius: 0, |
135 | | - pointHoverRadius: 0, |
136 | | - tension: 0.2, |
137 | | - }; |
138 | | - c.data.datasets.push(ds); |
| 79 | + if (!symbolMetrics?.price) continue; |
| 80 | + |
| 81 | + let series = seriesMapRef.current[dataSource]; |
| 82 | + if (!series) { |
| 83 | + series = chartRef.current.addSeries(LineSeries, { |
| 84 | + priceScaleId: "right", |
| 85 | + title: capitalCase(dataSource), |
| 86 | + }); |
| 87 | + series.applyOptions({ |
| 88 | + color: getColorForSymbol(dataSource), |
| 89 | + lineWidth: 2, |
| 90 | + lineStyle: 0, // solid |
| 91 | + }); |
| 92 | + seriesMapRef.current[dataSource] = series; |
139 | 93 | } |
140 | 94 |
|
141 | | - const lastDataPoint = ds.data.at(-1) as Nullish<ChartJSPoint>; |
| 95 | + const [lastPoint] = series.data().slice(-1); |
142 | 96 | const latestMetricIsFresh = |
143 | | - !lastDataPoint || lastDataPoint.x !== symbolMetrics.timestamp; |
| 97 | + !lastPoint || |
| 98 | + lastPoint.time !== Math.floor(symbolMetrics.timestamp / 1000); |
144 | 99 |
|
145 | | - if (!latestMetricIsFresh) return; |
| 100 | + if (!latestMetricIsFresh) continue; |
146 | 101 |
|
147 | | - ds.data.push({ x: symbolMetrics.timestamp, y: symbolMetrics.price }); |
| 102 | + const newPoint: LineData = { |
| 103 | + time: Math.floor(symbolMetrics.timestamp / 1000) as UTCTimestamp, |
| 104 | + value: symbolMetrics.price, |
| 105 | + }; |
148 | 106 |
|
| 107 | + series.update(newPoint); |
| 108 | + |
| 109 | + // Trim old points |
149 | 110 | const end = symbolMetrics.timestamp; |
150 | 111 | const start = end - MAX_DATA_AGE; |
151 | 112 |
|
152 | | - ds.data = (ds.data as ChartJSPoint[]) |
153 | | - .filter((d) => d.x >= start && d.x <= end) |
| 113 | + const allData = series.data(); |
| 114 | + const trimmed = allData |
| 115 | + .filter( |
| 116 | + (d) => |
| 117 | + (d.time as UTCTimestamp) * 1000 >= start && |
| 118 | + (d.time as UTCTimestamp) * 1000 <= end, |
| 119 | + ) |
154 | 120 | .slice(-MAX_DATA_POINTS); |
155 | 121 |
|
156 | | - // .sort() mutates the original array |
157 | | - c.data.datasets.sort( |
158 | | - (a, b) => a.label?.localeCompare(b.label ?? "") ?? 0, |
159 | | - ); |
160 | | - } |
| 122 | + series.setData(trimmed); |
161 | 123 |
|
162 | | - c.update(); |
| 124 | + // Update visible range so chart fills left-to-right |
| 125 | + chartRef.current.timeScale().setVisibleRange({ |
| 126 | + from: Math.floor(start / 1000) as UTCTimestamp, |
| 127 | + to: Math.floor(end / 1000) as UTCTimestamp, |
| 128 | + }); |
| 129 | + } |
163 | 130 | }); |
164 | 131 |
|
165 | | - useLayoutEffect(() => { |
166 | | - return () => { |
167 | | - chartHandlerRef.current?.destroy(); |
168 | | - }; |
169 | | - }, []); |
| 132 | + if (!isAllowedSymbol(selectedSource)) return; |
170 | 133 |
|
171 | | - if (!isAllowedSymbol(selectedSource)) { |
172 | | - return; |
173 | | - } |
174 | | - return ( |
175 | | - <div className={classes.root}> |
176 | | - <canvas ref={setCanvasRef} /> |
177 | | - </div> |
178 | | - ); |
| 134 | + return <div ref={containerRef} style={{ width: "100%", height: "400px" }} />; |
179 | 135 | } |
180 | 136 |
|
181 | 137 | export function PythProDemoPriceChart() { |
182 | | - /** context */ |
183 | 138 | const { dataSourcesInUse, metrics, selectedSource } = |
184 | 139 | usePythProAppStateContext(); |
185 | 140 |
|
|
0 commit comments