Skip to content

Commit 84d9038

Browse files
authored
feat: color the line chart by range direction behind a theming flag (#47771)
## **Description** The Token Details Page **line chart** is always drawn in green. This PR adds optional directional colouring for that line chart only: the line is green when the selected range is up and red when it is down, so the chart agrees with the percent-change figure in the header. It introduces **no new colours** — it reuses the existing design-system tokens: the same green (`--color-success-default`) the line already used, and the same red (`--color-error-default`) the percent-change header already uses. The direction is computed at the range level (range open vs. latest price), not from the hovered point, so the colour stays stable as the pointer moves. The behaviour is gated behind a new remote feature flag (`tokenDetailsAdvancedChartsTheming` / LaunchDarkly `token-details-advanced-charts-theming`). When the flag is off, the line is always green exactly as before. **Candlestick mode is unchanged** — it already renders green/red candles. <!-- ## **Related issues** Fixes: --> ## **Manual testing steps** 1. Enable the advanced charts flag and the new `tokenDetailsAdvancedChartsTheming` flag (via `.manifest-overrides.json` remote flag overrides). 2. Open a token's details page and stay in line-chart mode. 3. Select a time range over which the asset is up for the range — verify the line is green. 4. Select a time range over which the asset is down for the range — verify the line is red (the same red shown in the percent-change header). 5. Hover across the chart — verify the line colour does not flip while hovering; it stays the range's direction. 6. Turn the theming flag off — verify the line is always green regardless of direction, matching the previous behaviour. 7. Switch to candlestick mode — verify it is unchanged. ## **Changelog** CHANGELOG entry: null <!-- ## **Screenshots/Recordings** ### **Before** ### **After** --> ## **Pre-merge author checklist** - [ ] 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). - [ ] I've completed the PR template to the best of my ability - [ ] I've included tests if applicable - [ ] 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. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > UI-only chart styling gated by a remote feature flag; default behavior unchanged when the flag is off. > > **Overview** > Adds optional **directional line coloring** on the Token Details advanced **line chart**: when remote flag `tokenDetailsAdvancedChartsTheming` is on, the line uses **`--color-success-default`** for an up range and **`--color-error-default`** for a down range, based on **range open vs live/current price** (not hover). With the flag off, behavior stays **always green**. > > Wires the flag through **`TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG`**, **`getIsAdvancedChartsThemingEnabled`**, and the known flag registry. **`AdvancedChartSection`** passes **`lineColorVar`** into **`AssetChartBody`**, which resolves that CSS variable for Chart.js `borderColor`. **Candle mode is unchanged.** > > Tests cover flag on/off, up/down/unknown range, hover stability, and chart border color resolution. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 1064da1. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent a075985 commit 84d9038

8 files changed

Lines changed: 217 additions & 7 deletions

File tree

‎.github/scripts/known-feature-flag-constants.mts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,11 @@ const FILE_SOURCES: {
8383
file: 'shared/lib/assets/advanced-charts-feature-flags.ts',
8484
exportName: 'TOKEN_DETAILS_ADVANCED_CHARTS_FLAG',
8585
},
86+
{
87+
key: 'TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG',
88+
file: 'shared/lib/assets/advanced-charts-feature-flags.ts',
89+
exportName: 'TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG',
90+
},
8691
{
8792
key: 'MONEY_ENABLE_MONEY_ACCOUNT_FLAG_NAME',
8893
file: 'shared/lib/money/feature-flags.ts',

‎shared/lib/assets/advanced-charts-feature-flags.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,12 @@
44
* before it reaches extension state.
55
*/
66
export const TOKEN_DETAILS_ADVANCED_CHARTS_FLAG = 'tokenDetailsAdvancedCharts';
7+
8+
/**
9+
* Client-config / RemoteFeatureFlagController key (camelCase) for colouring the
10+
* Token Details Page line chart by its range direction. LaunchDarkly uses
11+
* kebab-case `token-details-advanced-charts-theming`, which is converted before
12+
* it reaches extension state.
13+
*/
14+
export const TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG =
15+
'tokenDetailsAdvancedChartsTheming';

‎ui/pages/asset/components/chart/advanced-chart-section.test.tsx‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,18 @@ jest.mock('./asset-chart-body', () => ({
5252
prices,
5353
realtimePrice,
5454
onHoverPrice,
55+
lineColorVar,
5556
}: {
5657
prices: { x: number; y: number }[];
5758
realtimePrice?: number;
5859
onHoverPrice: (point: { price?: number; date?: number } | null) => void;
60+
lineColorVar?: string;
5961
}) => (
6062
<div
6163
data-testid="line-chart"
6264
data-points={prices.length}
6365
data-realtime={realtimePrice ?? ''}
66+
data-line-color={lineColorVar ?? ''}
6467
>
6568
<button
6669
type="button"
@@ -167,14 +170,29 @@ function indicatorSlotVisibility(): string {
167170
return screen.getByTestId('advanced-chart-indicator-slot').style.visibility;
168171
}
169172

170-
function render(props: Partial<typeof DEFAULT_PROPS> = {}) {
171-
const store = configureStore({ metamask: { currentLocale: 'en' } });
173+
function render(
174+
props: Partial<typeof DEFAULT_PROPS> = {},
175+
{ themingEnabled = false }: { themingEnabled?: boolean } = {},
176+
) {
177+
const store = configureStore({
178+
metamask: {
179+
currentLocale: 'en',
180+
remoteFeatureFlags: {
181+
tokenDetailsAdvancedChartsTheming: themingEnabled,
182+
},
183+
},
184+
});
172185
return renderWithProvider(
173186
<AdvancedChartSection {...DEFAULT_PROPS} {...props} />,
174187
store,
175188
);
176189
}
177190

191+
/** The CSS variable the line chart was told to draw itself in. */
192+
function lineColor(): string | null {
193+
return screen.getByTestId('line-chart').getAttribute('data-line-color');
194+
}
195+
178196
describe('AdvancedChartSection', () => {
179197
beforeEach(() => {
180198
jest.clearAllMocks();
@@ -274,6 +292,52 @@ describe('AdvancedChartSection', () => {
274292
});
275293
});
276294

295+
describe('line color', () => {
296+
it('always draws the line green when the theming flag is off', () => {
297+
// Range is down (live 50 against an opening price of 100) but the flag is
298+
// off, so the colour must not change.
299+
setupData({ realtimePrice: 50 });
300+
render();
301+
302+
expect(lineColor()).toBe('--color-success-default');
303+
});
304+
305+
it('draws the line green for an up range when the flag is on', () => {
306+
setupData({ realtimePrice: 150 });
307+
render({}, { themingEnabled: true });
308+
309+
expect(lineColor()).toBe('--color-success-default');
310+
});
311+
312+
it('draws the line red for a down range when the flag is on', () => {
313+
setupData({ realtimePrice: 50 });
314+
render({}, { themingEnabled: true });
315+
316+
expect(lineColor()).toBe('--color-error-default');
317+
});
318+
319+
it('falls back to green when the direction is unknown', () => {
320+
// Placeholder data has no trustworthy opening price to compare against.
321+
setupHistorical({ isPlaceholderData: true });
322+
setupData({ realtimePrice: 50 });
323+
render({}, { themingEnabled: true });
324+
325+
expect(lineColor()).toBe('--color-success-default');
326+
});
327+
328+
it('colors by the range direction, not the hovered point', () => {
329+
// Hovering a point below the opening price must not flip an up range red.
330+
setupData({ realtimePrice: 150 });
331+
render({}, { themingEnabled: true });
332+
333+
act(() => {
334+
screen.getByTestId('simulate-hover').click();
335+
});
336+
337+
expect(lineColor()).toBe('--color-success-default');
338+
});
339+
});
340+
277341
describe('candle mode', () => {
278342
beforeEach(() => {
279343
setupPreferences(CHART_TYPE_CANDLE);

‎ui/pages/asset/components/chart/advanced-chart-section.tsx‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import React, { type CSSProperties, useCallback, useState } from 'react';
2+
import { useSelector } from 'react-redux';
23
import { Hex } from '@metamask/utils';
34
import { Box, BoxFlexDirection, Skeleton } from '@metamask/design-system-react';
5+
import { getIsAdvancedChartsThemingEnabled } from '../../../../selectors/multichain/feature-flags';
46
import { useHistoricalPrices } from '../../hooks/useHistoricalPrices';
57
import { computePercentChange } from '../../../../components/app/assets/util/percentChange';
68
import AdvancedChartIframe from './advanced-chart-iframe';
@@ -188,6 +190,23 @@ export const AdvancedChartSection = ({
188190
currency,
189191
};
190192

193+
// Colour the line by the range's overall direction rather than the hovered
194+
// point, so the colour stays stable as the pointer moves across the chart.
195+
// Reuses the existing success/error tokens — the same green as before and
196+
// the same red the percent-change header already uses — and falls back to
197+
// green when the direction is unknown (loading, flat, or missing data).
198+
const isThemingEnabled = useSelector(getIsAdvancedChartsThemingEnabled);
199+
const lineRangeChange = computePercentChange(
200+
realtimePrice ?? currentPrice,
201+
historical.isPlaceholderData ? undefined : historical.data.prices?.[0]?.y,
202+
);
203+
const lineColorVar =
204+
isThemingEnabled &&
205+
typeof lineRangeChange === 'number' &&
206+
lineRangeChange < 0
207+
? '--color-error-default'
208+
: '--color-success-default';
209+
191210
const candleHeader = {
192211
price: ohlcvPrice,
193212
percentChange: ohlcvPercentChange,
@@ -281,6 +300,7 @@ export const AdvancedChartSection = ({
281300
realtimePrice={realtimePrice}
282301
realtimeTimestamp={realtimeTimestamp}
283302
onHoverPrice={setHovered}
303+
lineColorVar={lineColorVar}
284304
/>
285305
</Box>
286306

‎ui/pages/asset/components/chart/asset-chart-body.test.tsx‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,4 +187,46 @@ describe('AssetChartBody', () => {
187187
expect(onHoverPrice).not.toHaveBeenCalled();
188188
});
189189
});
190+
191+
describe('line color', () => {
192+
// The border color is a callback resolved against the canvas at draw time.
193+
// Stub getComputedStyle to echo the requested property so the test asserts
194+
// which CSS variable the chart reads, independent of jsdom's empty values.
195+
const resolveBorderColor = (container: HTMLElement) => {
196+
const chart = Chart.getChart(
197+
container.querySelector('canvas') as HTMLCanvasElement,
198+
);
199+
if (!chart) {
200+
throw new Error('no chart was rendered');
201+
}
202+
const spy = jest.spyOn(window, 'getComputedStyle').mockReturnValue({
203+
getPropertyValue: (property: string) => `resolved(${property})`,
204+
} as unknown as CSSStyleDeclaration);
205+
try {
206+
// Chart.js resolves the root `borderColor` to a string on
207+
// `chart.options`; the original scriptable function is kept on the raw
208+
// config, which is what the chart actually calls at draw time.
209+
const { borderColor } = chart.config.options as {
210+
borderColor: (ctx: { chart: Chart }) => string;
211+
};
212+
return borderColor({ chart });
213+
} finally {
214+
spy.mockRestore();
215+
}
216+
};
217+
218+
it('draws the line in the success token by default', () => {
219+
expect(resolveBorderColor(renderBody().container)).toBe(
220+
'resolved(--color-success-default)',
221+
);
222+
});
223+
224+
it('draws the line in the provided color variable', () => {
225+
expect(
226+
resolveBorderColor(
227+
renderBody({ lineColorVar: '--color-error-default' }).container,
228+
),
229+
).toBe('resolved(--color-error-default)');
230+
});
231+
});
190232
});

‎ui/pages/asset/components/chart/asset-chart-body.tsx‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,12 @@ export type AssetChartBodyProps = {
8080
realtimeTimestamp?: number;
8181
/** Called with the hovered data point, and with null once the pointer leaves. */
8282
onHoverPrice?: (point: HoveredPoint | null) => void;
83+
/**
84+
* CSS custom property the line is drawn in, resolved against the canvas.
85+
* Defaults to the success (green) token so existing callers are unaffected;
86+
* the advanced chart passes the error (red) token when its range is down.
87+
*/
88+
lineColorVar?: string;
8389
/** Rendered below the chart, inside the box that carries the loading treatment. */
8490
children?: ReactNode;
8591
};
@@ -102,6 +108,7 @@ export const AssetChartBody = ({
102108
realtimePrice,
103109
realtimeTimestamp,
104110
onHoverPrice,
111+
lineColorVar = '--color-success-default',
105112
children,
106113
}: AssetChartBodyProps) => {
107114
const prevIsPlaceholderData = usePrevious(isPlaceholderData);
@@ -162,9 +169,7 @@ export const AssetChartBody = ({
162169
const options = {
163170
...initialChartOptions,
164171
borderColor: ({ chart }) =>
165-
getComputedStyle(chart.canvas)
166-
.getPropertyValue('--color-success-default')
167-
.trim(),
172+
getComputedStyle(chart.canvas).getPropertyValue(lineColorVar).trim(),
168173
transitions: {
169174
active: { animation },
170175
default: { animation },

‎ui/selectors/multichain/feature-flags.test.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
import { EXTENSION_TRUST_AND_SECURITY_TDP_FLAG } from '../../../shared/lib/assets/security-trust-feature-flags';
2-
import { TOKEN_DETAILS_ADVANCED_CHARTS_FLAG } from '../../../shared/lib/assets/advanced-charts-feature-flags';
2+
import {
3+
TOKEN_DETAILS_ADVANCED_CHARTS_FLAG,
4+
TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG,
5+
} from '../../../shared/lib/assets/advanced-charts-feature-flags';
36
import {
47
BFT_CHILD_PREFERENCES,
58
getIsAdvancedChartsEnabled,
9+
getIsAdvancedChartsThemingEnabled,
610
getIsBasicFunctionalityConsolidationEnabled,
711
getIsBasicFunctionalityToggleEnabled,
812
getIsFullscreenRedesignEnabled,
@@ -522,6 +526,43 @@ describe('getIsAdvancedChartsEnabled', () => {
522526
});
523527
});
524528

529+
describe('getIsAdvancedChartsThemingEnabled', () => {
530+
it('returns true for a version-gated flag whose minimumVersion is satisfied', () => {
531+
expect(
532+
getIsAdvancedChartsThemingEnabled(
533+
buildState({
534+
[TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG]: {
535+
enabled: true,
536+
minimumVersion: '0.0.0',
537+
},
538+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
539+
}) as any,
540+
),
541+
).toBe(true);
542+
});
543+
544+
it('returns false when the version-gated flag is explicitly disabled', () => {
545+
expect(
546+
getIsAdvancedChartsThemingEnabled(
547+
buildState({
548+
[TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG]: {
549+
enabled: false,
550+
minimumVersion: '0.0.0',
551+
},
552+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
553+
}) as any,
554+
),
555+
).toBe(false);
556+
});
557+
558+
it('returns false when the flag is missing', () => {
559+
expect(
560+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
561+
getIsAdvancedChartsThemingEnabled(buildState() as any),
562+
).toBe(false);
563+
});
564+
});
565+
525566
describe('getIsFullscreenRedesignEnabled', () => {
526567
it('returns false when the flag is missing', () => {
527568
expect(

‎ui/selectors/multichain/feature-flags.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import { createSelector } from 'reselect';
44
import { isMultichainFeatureEnabled } from '../../../shared/lib/multichain-feature-flags';
55
import { getBooleanFeatureFlag } from '../../../shared/lib/remote-feature-flag-utils';
66
import { EXTENSION_TRUST_AND_SECURITY_TDP_FLAG } from '../../../shared/lib/assets/security-trust-feature-flags';
7-
import { TOKEN_DETAILS_ADVANCED_CHARTS_FLAG } from '../../../shared/lib/assets/advanced-charts-feature-flags';
7+
import {
8+
TOKEN_DETAILS_ADVANCED_CHARTS_FLAG,
9+
TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG,
10+
} from '../../../shared/lib/assets/advanced-charts-feature-flags';
811
import { getRemoteFeatureFlags } from '../../../shared/lib/selectors/remote-feature-flags';
912

1013
export {
@@ -228,3 +231,24 @@ export const getIsAdvancedChartsEnabled = createSelector(
228231
return getBooleanFeatureFlag(rawFlagValue, false);
229232
},
230233
);
234+
235+
/**
236+
* Selector that returns whether the Token Details Page line chart should be
237+
* coloured by its range direction (green when the range is up, red when it is
238+
* down) rather than always green.
239+
*
240+
* Reuses the existing `--color-success-default` / `--color-error-default`
241+
* tokens; it introduces no new colours and does not affect candle mode, which
242+
* already draws green/red candles.
243+
*
244+
* @param _state - The MetaMask state object
245+
* @returns boolean - True when directional line-chart colouring should apply.
246+
*/
247+
export const getIsAdvancedChartsThemingEnabled = createSelector(
248+
getRemoteFeatureFlags,
249+
(remoteFeatureFlags) => {
250+
const rawFlagValue =
251+
remoteFeatureFlags[TOKEN_DETAILS_ADVANCED_CHARTS_THEMING_FLAG];
252+
return getBooleanFeatureFlag(rawFlagValue, false);
253+
},
254+
);

0 commit comments

Comments
 (0)