Skip to content

Commit 448dd92

Browse files
authored
refactor: extract asset chart body (#47634)
## **Description** `AssetChart` currently does five things: fetches historical prices, owns the selected time range, owns the price header, builds the Chart.js config, and renders the chart. Upcoming advanced-charts work needs only the last two — it brings its own data source, its own interval selector and its own price header — and without a seam it would have to ask `AssetChart` to switch parts of itself off through a growing set of `hide*` props. This PR extracts the rendering half and changes nothing else. - **`asset-chart-body.tsx` (new)** is data-dumb: given `prices` and `metadata` it owns `Chart.register`, `initialChartOptions`, the placeholder-data animation logic, the `options` object, the empty-state and muted-refetch branches, both `ChartTooltip`s, and the `<Line>`. It fetches nothing and owns no time range. - **`asset-chart.tsx`** keeps `useHistoricalPrices`, the `selectedTimeRange` state and `AssetChartPrice`. Its public props are unchanged, so `asset-page.tsx` is untouched. Everything moved verbatim, including the `--color-success-default` `getComputedStyle` border colour. No behaviour change is intended — any rendering difference is a bug in this PR. Two details worth a reviewer's attention: 1. **Hover.** The mouse handlers used to call `priceRef.current.setPrice` directly. They now call an `onHoverPrice` prop, and `AssetChart` passes `(point) => priceRef?.current?.setPrice(point)`. Same payload, same timing, but the body no longer knows the header exists. 2. **The time-range row is passed as `children`** rather than rendered by the body. That keeps it inside the `data-testid="asset-price-chart"` box where it sits today, so it stays under the loading background treatment and the DOM nesting is identical. `eslint-suppressions.json` is deliberately untouched: the `react-hooks/purity` suppression on `asset-chart.tsx` comes from `date={Date.now()}` in the render, which stayed behind. Coverage: a new `asset-chart-body.test.tsx` exercises the chart / empty-state / loading branches, the muted refetch opacity, the `children` slot position, and the `onHoverPrice` contract. There was no `asset-chart.test.tsx` before, so the strongest guard against an accidental rendering change is `asset-page.test.tsx`'s existing snapshot, which passes untouched. ## **Changelog** CHANGELOG entry: null ## **Related issues** Fixes: [ASSETS-4291](https://consensyssoftware.atlassian.net/browse/ASSETS-4291) ## **Manual testing steps** There is deliberately no visible change, so this is a side-by-side against `main` on a token details page. 1. Build and load the extension, then open any token's details page (for example ETH on Mainnet). 2. Confirm the price header shows the current price and percent change exactly as on `main`. 3. Hover across the chart and confirm the header price and date track the pointer. 4. Move the pointer off the chart and confirm the header reverts to the current price. 5. Confirm the minimum and maximum price tooltips still render above and below the line, horizontally positioned over their data points. 6. Click through all six ranges (1D, 1W, 1M, 3M, 1Y, All) and confirm each loads and the selected pill highlights. 7. While switching ranges, confirm the chart dims during the refetch rather than disappearing. 8. Open a token with no price history and confirm the empty state renders in place of the chart. 9. Confirm the range buttons still sit directly below the chart inside the same container, with no spacing or alignment change. <!-- ## **Screenshots/Recordings** ### **Before** ### **After** --> ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I’ve included tests if applicable - [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [ ] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots. [ASSETS-4291]: https://consensyssoftware.atlassian.net/browse/ASSETS-4291?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
1 parent e17de98 commit 448dd92

3 files changed

Lines changed: 378 additions & 178 deletions

File tree

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import React from 'react';
2+
import { screen, createEvent, fireEvent } from '@testing-library/react';
3+
import { Point } from 'chart.js';
4+
import { renderWithProvider } from '../../../../../test/lib/render-helpers-navigate';
5+
import configureStore from '../../../../store/store';
6+
import {
7+
DEFAULT_USE_HISTORICAL_PRICES_METADATA,
8+
type HistoricalPrices,
9+
} from '../../hooks/useHistoricalPrices';
10+
import { loadingOpacity } from '../../util';
11+
import { AssetChartBody, type AssetChartBodyProps } from './asset-chart-body';
12+
13+
const PRICES: Point[] = [
14+
{ x: 1, y: 10 },
15+
{ x: 2, y: 30 },
16+
{ x: 3, y: 20 },
17+
];
18+
19+
const METADATA: HistoricalPrices['metadata'] = {
20+
minPricePoint: PRICES[0],
21+
maxPricePoint: PRICES[1],
22+
xMin: 1,
23+
xMax: 3,
24+
yMin: 10,
25+
yMax: 30,
26+
};
27+
28+
const renderBody = (overrides: Partial<AssetChartBodyProps> = {}) =>
29+
renderWithProvider(
30+
<AssetChartBody
31+
prices={PRICES}
32+
metadata={METADATA}
33+
loading={false}
34+
isFetching={false}
35+
isPlaceholderData={false}
36+
currency="USD"
37+
currentPrice={25}
38+
{...overrides}
39+
/>,
40+
configureStore({ metamask: { currentLocale: 'en' } }),
41+
);
42+
43+
describe('AssetChartBody', () => {
44+
it('renders the chart when there are prices', () => {
45+
const { container } = renderBody();
46+
47+
expect(screen.getByTestId('asset-price-chart')).toBeInTheDocument();
48+
expect(container.querySelector('canvas')).toBeInTheDocument();
49+
});
50+
51+
it('renders the empty state instead of the chart once loading finishes with no prices', () => {
52+
const { container } = renderBody({
53+
prices: [],
54+
metadata: DEFAULT_USE_HISTORICAL_PRICES_METADATA,
55+
});
56+
57+
expect(screen.getByTestId('asset-price-chart')).toBeInTheDocument();
58+
expect(container.querySelector('canvas')).not.toBeInTheDocument();
59+
});
60+
61+
it('keeps rendering the chart while prices are still loading', () => {
62+
const { container } = renderBody({
63+
prices: [],
64+
metadata: DEFAULT_USE_HISTORICAL_PRICES_METADATA,
65+
loading: true,
66+
});
67+
68+
expect(container.querySelector('canvas')).toBeInTheDocument();
69+
});
70+
71+
it('mutes the chart while refetching over existing prices', () => {
72+
renderBody({ isFetching: true });
73+
74+
expect(
75+
screen.getByTestId('asset-price-chart').firstElementChild,
76+
).toHaveStyle({ opacity: `${loadingOpacity}` });
77+
});
78+
79+
it('renders children below the chart, inside the chart container', () => {
80+
renderBody({ children: <div data-testid="time-ranges" /> });
81+
82+
const chart = screen.getByTestId('asset-price-chart');
83+
const children = screen.getByTestId('time-ranges');
84+
85+
expect(chart).toContainElement(children);
86+
expect(chart.lastElementChild).toBe(children);
87+
});
88+
89+
describe('onHoverPrice', () => {
90+
it('reports the hovered data point', () => {
91+
const onHoverPrice = jest.fn();
92+
const { container } = renderBody({ onHoverPrice });
93+
94+
const canvas = container.querySelector('canvas') as HTMLCanvasElement;
95+
Object.defineProperty(canvas, 'clientWidth', { value: 300 });
96+
97+
const event = createEvent.mouseMove(canvas);
98+
Object.defineProperty(event, 'offsetX', { value: 150 });
99+
fireEvent(canvas, event);
100+
101+
expect(onHoverPrice).toHaveBeenCalledWith({ price: 20, date: 3 });
102+
});
103+
104+
it('reverts to the current price when the pointer leaves', () => {
105+
const onHoverPrice = jest.fn();
106+
const { container } = renderBody({ onHoverPrice, currentPrice: 25 });
107+
108+
fireEvent.mouseOut(
109+
container.querySelector('canvas') as HTMLCanvasElement,
110+
);
111+
112+
expect(onHoverPrice).toHaveBeenCalledWith(
113+
expect.objectContaining({ price: 25 }),
114+
);
115+
});
116+
117+
it('ignores hover while showing placeholder data', () => {
118+
const onHoverPrice = jest.fn();
119+
const { container } = renderBody({
120+
onHoverPrice,
121+
isPlaceholderData: true,
122+
});
123+
124+
const canvas = container.querySelector('canvas') as HTMLCanvasElement;
125+
Object.defineProperty(canvas, 'clientWidth', { value: 300 });
126+
127+
const event = createEvent.mouseMove(canvas);
128+
Object.defineProperty(event, 'offsetX', { value: 150 });
129+
fireEvent(canvas, event);
130+
131+
expect(onHoverPrice).not.toHaveBeenCalled();
132+
});
133+
});
134+
});
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
import React, { ReactNode, useRef } from 'react';
2+
import {
3+
Chart,
4+
LineElement,
5+
LinearScale,
6+
PointElement,
7+
Filler,
8+
ChartOptions,
9+
Decimation,
10+
Point,
11+
} from 'chart.js';
12+
import { Line } from 'react-chartjs-2';
13+
import {
14+
Box,
15+
BoxBackgroundColor,
16+
BoxFlexDirection,
17+
BoxJustifyContent,
18+
} from '@metamask/design-system-react';
19+
import { usePrevious } from '../../../../hooks/usePrevious';
20+
import type { HistoricalPrices } from '../../hooks/useHistoricalPrices';
21+
import { finiteFallback, loadingOpacity } from '../../util';
22+
import ChartTooltip from './chart-tooltip';
23+
import { CrosshairPlugin } from './crosshair-plugin';
24+
import { AssetChartEmptyState } from './asset-chart-empty-state';
25+
26+
Chart.register(
27+
LinearScale,
28+
PointElement,
29+
LineElement,
30+
Filler,
31+
Decimation,
32+
CrosshairPlugin,
33+
);
34+
35+
const initialChartOptions: ChartOptions<'line'> = {
36+
normalized: true,
37+
parsing: false,
38+
aspectRatio: 2.6,
39+
layout: { autoPadding: false, padding: 0 },
40+
animation: { duration: 0 },
41+
elements: {
42+
line: { borderWidth: 1.5 },
43+
point: { pointStyle: false },
44+
},
45+
plugins: {
46+
// Downsample to a maximum number of points
47+
decimation: {
48+
algorithm: 'lttb',
49+
samples: 150,
50+
threshold: 150,
51+
enabled: true,
52+
},
53+
},
54+
};
55+
56+
export type AssetChartBodyProps = {
57+
/** The price data points to plot. */
58+
prices: Point[];
59+
/** Metadata derived from `prices`, used for the chart bounds and tooltips. */
60+
metadata: HistoricalPrices['metadata'];
61+
/** Whether the prices are loading for the first time. */
62+
loading: boolean;
63+
/** Whether a price request is in flight, including background refetches. */
64+
isFetching: boolean;
65+
/** Whether `prices` is react-query placeholder data rather than real prices. */
66+
isPlaceholderData: boolean;
67+
/** The user's display currency, used to format the tooltips. */
68+
currency: string;
69+
/** The asset's current price, reverted to when the pointer leaves the chart. */
70+
currentPrice?: number;
71+
/** Called with the hovered data point, and with the current price on pointer out. */
72+
onHoverPrice?: (point: { price?: number; date?: number }) => void;
73+
/** Rendered below the chart, inside the box that carries the loading treatment. */
74+
children?: ReactNode;
75+
};
76+
77+
/**
78+
* Renders a line chart for a series of prices.
79+
*
80+
* This component fetches nothing and owns no time range: it plots whatever
81+
* prices it is given, and reports hovered points through `onHoverPrice` so the
82+
* caller can drive its own price header.
83+
*/
84+
export const AssetChartBody = ({
85+
prices,
86+
metadata: { minPricePoint, maxPricePoint, xMin, xMax, yMin, yMax },
87+
loading,
88+
isFetching,
89+
isPlaceholderData,
90+
currency,
91+
currentPrice,
92+
onHoverPrice,
93+
children,
94+
}: AssetChartBodyProps) => {
95+
const prevIsPlaceholderData = usePrevious(isPlaceholderData);
96+
const wasPlaceholderData = prevIsPlaceholderData && !isPlaceholderData;
97+
98+
// The cases below are not mutually exclusive
99+
const shouldShowChartEmptyState = !loading && prices.length === 0; // When the chart is not loading anymore and there are no prices, show an empty state
100+
const shouldShowChartMuted =
101+
isFetching && prices.length > 0 && !isPlaceholderData;
102+
103+
const animation =
104+
isPlaceholderData || wasPlaceholderData
105+
? {
106+
x: false,
107+
y: {
108+
from: (ctx: { chart: { scales: { y: { bottom: number } } } }) =>
109+
ctx.chart.scales.y.bottom,
110+
duration: 400,
111+
},
112+
}
113+
: {
114+
x: { type: 'number', duration: 400 },
115+
y: { type: 'number', duration: 400 },
116+
};
117+
118+
const options = {
119+
...initialChartOptions,
120+
borderColor: ({ chart }) =>
121+
getComputedStyle(chart.canvas)
122+
.getPropertyValue('--color-success-default')
123+
.trim(),
124+
transitions: {
125+
active: { animation },
126+
default: { animation },
127+
resize: { animation: { duration: 0 } },
128+
},
129+
scales: {
130+
x: {
131+
min: finiteFallback(xMin, undefined),
132+
max: finiteFallback(xMax, undefined),
133+
display: false,
134+
type: 'linear',
135+
},
136+
y: {
137+
min: isPlaceholderData ? 0 : finiteFallback(yMin, 0),
138+
max: isPlaceholderData ? 1 : finiteFallback(yMax, 1),
139+
display: false,
140+
},
141+
},
142+
} as ChartOptions<'line'>;
143+
144+
const chartRef = useRef<Chart<'line', Point[]>>();
145+
146+
return (
147+
<Box
148+
data-testid="asset-price-chart"
149+
className="flex rounded-lg"
150+
marginTop={4}
151+
backgroundColor={
152+
loading && !prices
153+
? BoxBackgroundColor.BackgroundSection
154+
: BoxBackgroundColor.Transparent
155+
}
156+
flexDirection={BoxFlexDirection.Column}
157+
>
158+
{shouldShowChartEmptyState && <AssetChartEmptyState />}
159+
{!shouldShowChartEmptyState && (
160+
<Box style={{ opacity: shouldShowChartMuted ? loadingOpacity : 1 }}>
161+
<ChartTooltip
162+
point={isPlaceholderData ? undefined : maxPricePoint}
163+
xMin={xMin}
164+
xMax={xMax}
165+
currency={currency}
166+
/>
167+
<Box
168+
style={{ aspectRatio: `${options.aspectRatio}` }}
169+
className="flex"
170+
flexDirection={BoxFlexDirection.Column}
171+
justifyContent={
172+
currentPrice ? BoxJustifyContent.End : BoxJustifyContent.Start
173+
}
174+
>
175+
<Line
176+
ref={chartRef}
177+
data={{ datasets: [{ data: prices, fill: false }] }}
178+
options={options}
179+
// Update the price display on chart hover
180+
onMouseMove={(event) => {
181+
if (isPlaceholderData) {
182+
return;
183+
}
184+
const data = chartRef?.current?.data?.datasets?.[0]?.data;
185+
if (data) {
186+
const target = event.target as HTMLElement;
187+
const index = Math.max(
188+
0,
189+
Math.min(
190+
data.length - 1,
191+
Math.round(
192+
(event.nativeEvent.offsetX / target.clientWidth) *
193+
data.length,
194+
),
195+
),
196+
);
197+
const point = data[index];
198+
if (point) {
199+
onHoverPrice?.({
200+
price: point.y,
201+
date: point.x,
202+
});
203+
}
204+
}
205+
}}
206+
// Revert to current price when not hovering
207+
onMouseOut={() => {
208+
onHoverPrice?.({
209+
price: currentPrice,
210+
date: Date.now(),
211+
});
212+
}}
213+
/>
214+
</Box>
215+
216+
<ChartTooltip
217+
point={isPlaceholderData ? undefined : minPricePoint}
218+
xMin={xMin}
219+
xMax={xMax}
220+
currency={currency}
221+
/>
222+
</Box>
223+
)}
224+
225+
{children}
226+
</Box>
227+
);
228+
};

0 commit comments

Comments
 (0)