Skip to content

Commit c615545

Browse files
authored
feat: change wide screen view network pill UX and add analytics (#47791)
<!-- Please submit this PR as a draft initially. Do not mark it as "Ready for review" until the template has been completely filled out, and PR status checks have passed at least once. --> ## **Description** Design would like the 'Show more/fewer' buttons to now look like pills and sit at the end of the top row when collapsed, and the end of the full list when expanded. This PR makes those changes, updates the story, adds tests, and adds the relevant analytics. It also slips in a UI fix to increase the coin button sizes. ## **Changelog** <!-- If this PR is not End-User-Facing and should not show up in the CHANGELOG, you can choose to either: 1. Write `CHANGELOG entry: null` 2. Label with `no-changelog` If this PR is End-User-Facing, please write a short User-Facing description in the past tense like: `CHANGELOG entry: Added a new tab for users to see their NFTs` `CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker` (This helps the Release Engineer do their job more quickly and accurately) --> CHANGELOG entry: Update network pill UX shown on wide screens to show pill-like toggle ## **Related issues** Fixes: https://consensyssoftware.atlassian.net/browse/CEUX-1483 ## **Manual testing steps** 1. Verify that the 'More networks' button sits at the end of the row when collapsed, and there is only one row shown 2. Verify the number shown is correct 3. Verify when clicked, all networks show and the button pops to the bottom of the list and shows 'Fewer networks' 4. Verify that Network Changed metrics are emitted with `location = Network Pill` ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** <!-- [screenshots/recordings] --> ### **After** Collapsed: <img width="884" height="237" alt="image" src="https://github.com/user-attachments/assets/bd75eaa1-fca7-410c-8337-7f36e6b26e94" /> Expanded: <img width="886" height="204" alt="image" src="https://github.com/user-attachments/assets/64867156-3640-468e-8bc4-1cc87ede958a" /> ## **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** > Primarily UI, layout measurement, and analytics property tagging; network switching behavior is unchanged aside from optional location in metrics. > > **Overview** > Updates **wide-screen network pill** collapse/expand so the control matches other pills in the row and uses **“Show all (N)”** / **“Show fewer”** copy instead of network-specific strings. > > The selector no longer detects wrap via `offsetTop`; it uses **`getHiddenPillCount`** (pill widths, row width, gap, toggle width) so the toggle can sit **on the same row** when collapsed. **`ResizeObserver`** remeasures when pills or the toggle resize. Hidden trailing pills stay **`inert`** until expanded. Selecting a network from a pill passes **`location: 'Network Pill'`** through `handleSelectNetwork` → **`handleNetworkChange`** for **`NavNetworkSwitched`** metrics (default remains **Network Menu**). > > Also adds **`p-7`** padding on wallet overview coin action buttons and Storybook width constraint so the toggle is visible in stories. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 5940c66. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent fe06b7f commit c615545

11 files changed

Lines changed: 313 additions & 64 deletions

File tree

‎app/_locales/en/messages.json‎

Lines changed: 6 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎app/_locales/en_GB/messages.json‎

Lines changed: 6 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎ui/components/app/assets/asset-list/asset-list-control-bar/use-home-network-filter.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,14 +236,14 @@ export const useHomeNetworkFilter = ({
236236
]);
237237

238238
const handleSelectNetwork = useCallback(
239-
async (chainId: CaipChainId) => {
239+
async (chainId: CaipChainId, location?: string) => {
240240
if (isPending) {
241241
return;
242242
}
243243
onPendingChange?.(true);
244244
onClose?.();
245245
try {
246-
await handleNetworkChange(chainId);
246+
await handleNetworkChange(chainId, location);
247247
} finally {
248248
onPendingChange?.(false);
249249
}

‎ui/components/app/wallet-overview/coin-buttons.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -645,7 +645,7 @@ const CoinButtons = ({
645645
key={testId}
646646
variant={ButtonVariant.Secondary}
647647
size={ButtonSize.Lg}
648-
className="w-auto shrink-0"
648+
className="w-auto shrink-0 p-7"
649649
startIconName={iconName}
650650
startIconProps={{ className: iconClassName }}
651651
isDisabled={isDisabled}

‎ui/components/multichain/network-manager/hooks/useNetworkChangeHandlers.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,16 @@ import { useNetworkChangeHandlers } from './useNetworkChangeHandlers';
99

1010
const mockDispatch = jest.fn();
1111
const mockTrackEvent = jest.fn();
12+
const trackedProperties: Record<string, unknown>[] = [];
1213
const mockCreateEventBuilder = jest.fn(() => ({
1314
addCategory: jest.fn().mockReturnThis(),
14-
addProperties: jest.fn().mockReturnThis(),
15+
addProperties: jest.fn(function addProperties(
16+
this: unknown,
17+
properties: Record<string, unknown>,
18+
) {
19+
trackedProperties.push(properties);
20+
return this;
21+
}),
1522
build: jest.fn().mockReturnValue({ event: 'NavNetworkSwitched' }),
1623
}));
1724

@@ -115,6 +122,7 @@ jest.mock('../../../../../shared/lib/network.utils', () => ({
115122
describe('useNetworkChangeHandlers', () => {
116123
beforeEach(() => {
117124
jest.clearAllMocks();
125+
trackedProperties.length = 0;
118126
jest.useFakeTimers();
119127
});
120128

@@ -139,6 +147,27 @@ describe('useNetworkChangeHandlers', () => {
139147
setActiveNetwork('linea-mainnet'),
140148
);
141149
expect(mockTrackEvent).toHaveBeenCalled();
150+
expect(trackedProperties).toMatchObject([
151+
{
152+
location: 'Network Menu',
153+
// eslint-disable-next-line @typescript-eslint/naming-convention
154+
chain_id: CHAIN_IDS.MAINNET,
155+
// eslint-disable-next-line @typescript-eslint/naming-convention
156+
from_network: CHAIN_IDS.MAINNET,
157+
// eslint-disable-next-line @typescript-eslint/naming-convention
158+
to_network: CHAIN_IDS.LINEA_MAINNET,
159+
},
160+
]);
161+
});
162+
163+
it('tracks the switch with the location it was given', async () => {
164+
const { result } = renderHook(() => useNetworkChangeHandlers());
165+
166+
await act(async () => {
167+
await result.current.handleNetworkChange(mockLineaCaip, 'Network Pill');
168+
});
169+
170+
expect(trackedProperties).toMatchObject([{ location: 'Network Pill' }]);
142171
});
143172

144173
it('exposes isPending and startTransition for callers', () => {

‎ui/components/multichain/network-manager/hooks/useNetworkChangeHandlers.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ export const useNetworkChangeHandlers = () => {
154154
);
155155

156156
const handleNetworkChange = useCallback(
157-
async (chainId: CaipChainId) => {
157+
async (chainId: CaipChainId, location = 'Network Menu') => {
158158
if (isPending) {
159159
return;
160160
}
@@ -202,7 +202,7 @@ export const useNetworkChangeHandlers = () => {
202202
createEventBuilder(MetaMetricsEventName.NavNetworkSwitched)
203203
.addCategory(MetaMetricsEventCategory.Network)
204204
.addProperties({
205-
location: 'Network Menu',
205+
location,
206206
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31860
207207
// eslint-disable-next-line @typescript-eslint/naming-convention
208208
chain_id: currentChainIdToTrack,
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { getHiddenPillCount } from './get-hidden-pill-count';
2+
3+
describe('getHiddenPillCount', () => {
4+
it('returns 0 when there are no pills', () => {
5+
expect(getHiddenPillCount([], 250, 8, 40)).toBe(0);
6+
});
7+
8+
it('returns 0 when every pill fits on the row', () => {
9+
expect(getHiddenPillCount([100, 100, 100], 316, 8, 40)).toBe(0);
10+
});
11+
12+
it('hides the trailing pill when the toggle still fits beside the rest', () => {
13+
expect(getHiddenPillCount([100, 100, 100], 250, 0, 40)).toBe(1);
14+
});
15+
16+
it('hides another pill when the toggle needs the room', () => {
17+
expect(getHiddenPillCount([100, 100, 100], 250, 0, 80)).toBe(2);
18+
});
19+
20+
it('hides the pills that overflow before the toggle has been measured', () => {
21+
expect(getHiddenPillCount([100, 100, 100], 250, 0, 0)).toBe(1);
22+
});
23+
24+
it('counts the gap between pills and before the toggle', () => {
25+
expect(getHiddenPillCount([100, 100], 148, 8, 40)).toBe(1);
26+
expect(getHiddenPillCount([100, 100], 147, 8, 40)).toBe(2);
27+
});
28+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* How many trailing pills to hide so the rest fit on one row with the toggle.
3+
* Returns 0 when every pill fits without a toggle.
4+
*
5+
* @param widths - Width of each pill, in display order.
6+
* @param available - Width of the row.
7+
* @param gap - Gap between items.
8+
* @param toggleWidth - Width of the toggle, or 0 before it has been rendered.
9+
* @returns The number of trailing pills that do not fit.
10+
*/
11+
export const getHiddenPillCount = (
12+
widths: number[],
13+
available: number,
14+
gap: number,
15+
toggleWidth: number,
16+
): number => {
17+
if (widths.length === 0) {
18+
return 0;
19+
}
20+
21+
const rowWidth = (count: number) =>
22+
widths.slice(0, count).reduce((sum, width) => sum + width, 0) +
23+
gap * Math.max(count - 1, 0);
24+
25+
if (rowWidth(widths.length) <= available) {
26+
return 0;
27+
}
28+
29+
const reserve = toggleWidth > 0 ? toggleWidth + gap : 0;
30+
let visible = 0;
31+
for (let count = 1; count <= widths.length; count++) {
32+
if (rowWidth(count) + reserve > available) {
33+
break;
34+
}
35+
visible = count;
36+
}
37+
return Math.max(widths.length - visible, 1);
38+
};

‎ui/components/multichain/network-pill-selector/network-pill-selector.stories.tsx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,18 @@ const withStore =
7979
</Provider>
8080
);
8181

82+
// The story canvas is wider than the home row, so every pill fits and the
83+
// toggle never renders. Constrain it to the width where the row wraps.
84+
const withWrappedRow: Decorator = (Story) => (
85+
<div style={{ maxWidth: 720 }}>
86+
<Story />
87+
</div>
88+
);
89+
8290
const meta: Meta<typeof NetworkPillSelector> = {
8391
title: 'Components/Multichain/NetworkPillSelector',
8492
component: NetworkPillSelector,
93+
decorators: [withWrappedRow],
8594
parameters: {
8695
docs: {
8796
description: {

‎ui/components/multichain/network-pill-selector/network-pill-selector.test.tsx‎

Lines changed: 102 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React from 'react';
2-
import { fireEvent, screen } from '@testing-library/react';
2+
import { act, fireEvent, screen } from '@testing-library/react';
33
import type { MultichainNetworkConfiguration } from '@metamask/multichain-network-controller';
44
import { renderWithProvider } from '../../../../test/lib/render-helpers-navigate';
55
import configureStore from '../../../store/store';
@@ -99,7 +99,10 @@ describe('NetworkPillSelector', () => {
9999
renderSelector();
100100

101101
fireEvent.click(screen.getByTestId('network-pill-0xa'));
102-
expect(mockHandleSelectNetwork).toHaveBeenCalledWith('eip155:10');
102+
expect(mockHandleSelectNetwork).toHaveBeenCalledWith(
103+
'eip155:10',
104+
'Network Pill',
105+
);
103106

104107
fireEvent.click(screen.getByTestId('network-pill-all-default'));
105108
expect(mockHandleSelectAll).toHaveBeenCalledTimes(1);
@@ -138,23 +141,113 @@ describe('NetworkPillSelector', () => {
138141
});
139142

140143
describe('when pills wrap onto more than one line', () => {
144+
afterEach(() => {
145+
jest.restoreAllMocks();
146+
});
147+
141148
it('toggles between the collapsed and expanded view', () => {
142-
// The Optimism pill sits on a second line
149+
// Three 100px pills in a 250px row, so the last one wraps. The toggle
150+
// is 40px and still fits beside the first two.
143151
jest
144-
.spyOn(HTMLElement.prototype, 'offsetTop', 'get')
152+
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
153+
.mockReturnValue(250);
154+
jest
155+
.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
145156
.mockImplementation(function mock(this: HTMLElement) {
146-
return this.dataset.testid === 'network-pill-0xa' ? 56 : 0;
157+
if (this.dataset.testid === 'network-pill-toggle') {
158+
return 40;
159+
}
160+
if (this.dataset.testid?.startsWith('network-pill')) {
161+
return 100;
162+
}
163+
return 0;
147164
});
148165

149166
renderSelector();
150167
const toggle = screen.getByTestId('network-pill-toggle');
151-
expect(toggle).toHaveTextContent('Show 1 more networks');
168+
const pills = screen.getByTestId(
169+
'network-pill-selector',
170+
).firstElementChild;
171+
expect(toggle).toHaveTextContent('Show all (3)');
152172

153173
fireEvent.click(toggle);
154-
expect(toggle).toHaveTextContent('Show fewer networks');
174+
const expandedToggle = screen.getByTestId('network-pill-toggle');
175+
expect(expandedToggle).toHaveTextContent('Show fewer');
155176

156-
fireEvent.click(toggle);
157-
expect(toggle).toHaveTextContent('Show 1 more networks');
177+
fireEvent.click(expandedToggle);
178+
const collapsedToggle = screen.getByTestId('network-pill-toggle');
179+
expect(collapsedToggle).toHaveTextContent('Show all (3)');
180+
});
181+
182+
it('remeasures when a pill changes width', () => {
183+
let notify: ResizeObserverCallback | undefined;
184+
const observed: Element[] = [];
185+
const originalResizeObserver = window.ResizeObserver;
186+
window.ResizeObserver = class {
187+
constructor(callback: ResizeObserverCallback) {
188+
notify = callback;
189+
}
190+
191+
observe(target: Element) {
192+
observed.push(target);
193+
}
194+
195+
unobserve() {
196+
// no-op
197+
}
198+
199+
disconnect() {
200+
// no-op
201+
}
202+
} as typeof ResizeObserver;
203+
204+
jest
205+
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
206+
.mockReturnValue(400);
207+
const offsetWidth = jest
208+
.spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
209+
.mockImplementation(function mock(this: HTMLElement) {
210+
if (this.dataset.testid === 'network-pill-toggle') {
211+
return 40;
212+
}
213+
if (this.dataset.testid?.startsWith('network-pill')) {
214+
return 100;
215+
}
216+
return 0;
217+
});
218+
219+
try {
220+
renderSelector();
221+
expect(
222+
screen.queryByTestId('network-pill-toggle'),
223+
).not.toBeInTheDocument();
224+
expect(
225+
observed.some(
226+
(element) =>
227+
element.getAttribute('data-testid') === 'network-pill-0x1',
228+
),
229+
).toBe(true);
230+
231+
offsetWidth.mockImplementation(function mock(this: HTMLElement) {
232+
if (this.dataset.testid === 'network-pill-toggle') {
233+
return 40;
234+
}
235+
if (this.dataset.testid?.startsWith('network-pill')) {
236+
return 200;
237+
}
238+
return 0;
239+
});
240+
act(() => {
241+
notify?.([], {} as ResizeObserver);
242+
});
243+
244+
expect(screen.getByTestId('network-pill-toggle')).toHaveTextContent(
245+
'Show all (3)',
246+
);
247+
expect(screen.getByTestId('network-pill-0xa')).toHaveAttribute('inert');
248+
} finally {
249+
window.ResizeObserver = originalResizeObserver;
250+
}
158251
});
159252
});
160253

0 commit comments

Comments
 (0)