Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 40 additions & 11 deletions ui/contexts/metametrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
useContext,
} from 'react';
import PropTypes from 'prop-types';
import { matchPath, useLocation } from 'react-router-dom';
// NOTE: Mixed v5/v5-compat imports during router migration
// - useLocation from v5: Works with the v5 HashRouter to detect navigation changes
// - matchPath from v5-compat: Provides v6 API (reversed args, pattern.path structure)
// When v6 migration is complete, change both imports to: import { useLocation, matchPath } from 'react-router-dom';
import { useLocation } from 'react-router-dom';
import { matchPath } from 'react-router-dom-v5-compat';
import { useSelector } from 'react-redux';

import { omit } from 'lodash';
Expand Down Expand Up @@ -148,6 +153,7 @@

// Used to prevent double tracking page calls
const previousMatch = useRef();
const previousPathname = useRef();

/**
* Anytime the location changes, track a page change with segment.
Expand All @@ -156,12 +162,33 @@
* which page the user is on and their navigation path.
*/
useEffect(() => {
// Only run if pathname actually changed
if (previousPathname.current === location.pathname) {
return;
}
previousPathname.current = location.pathname;

const environmentType = getEnvironmentType();
const match = matchPath(location.pathname, {
path: getPaths(),
exact: true,
strict: true,
});
// v6 matchPath doesn't support array of paths, so we loop to find first match
const paths = getPaths();
let match = null;
for (const path of paths) {
// Skip empty string paths - they don't work correctly with v6 matchPath
if (path === '') {
continue;
}
match = matchPath(
{
path,
end: true,
caseSensitive: true,
},
location.pathname,
);
if (match) {
break;
}
}
// Start by checking for a missing match route. If this falls through to
// the else if, then we know we have a matched route for tracking.
if (!match) {
Expand All @@ -172,10 +199,10 @@
},
});
} else if (
previousMatch.current !== match.path &&
previousMatch.current !== match.pattern.path &&
!(
environmentType === 'notification' &&
match.path === '/' &&
match.pattern.path === '/' &&
previousMatch.current === undefined
)
) {
Expand All @@ -184,7 +211,8 @@
// this we keep track of the previousMatch, and we skip the event track
// in the event that we are dealing with the initial load of the
// homepage
const { path, params } = match;
const { pattern, params } = match;
const path = pattern.path;

Check failure on line 215 in ui/contexts/metametrics.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Use object destructuring
const name = PATH_NAME_MAP.get(path);
trackMetaMetricsPage(
{
Expand All @@ -201,8 +229,9 @@
},
);
}
previousMatch.current = match?.path;
}, [location, context]);
previousMatch.current = match?.pattern?.path;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.pathname, location.search, location.hash]);

// For backwards compatibility, attach the new methods as properties to trackEvent
const trackEventWithMethods = trackEvent;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from 'react';
import { useSelector } from 'react-redux';
import { Navigate } from 'react-router-dom-v5-compat';
import { ONBOARDING_ROUTE } from '../../constants/routes';

type InitializedV5CompatProps = {
children: React.ReactNode;
};

/**
* InitializedV5Compat - A wrapper component for v5-compat routes that require initialization
*
* This component checks if the user has completed onboarding.
* If not, it redirects to the onboarding route using v5-compat Navigate.
*
* Unlike the v5 Initialized HOC, this returns the element directly (not wrapped in Route)
* because v5-compat Routes handle their children differently.
*
* @param props - Component props
* @param props.children - Child components to render when initialized
* @returns Navigate component or children
*/
const InitializedV5Compat = ({ children }: InitializedV5CompatProps) => {
const completedOnboarding = useSelector(
(state: { metamask: { completedOnboarding: boolean } }) =>
state.metamask.completedOnboarding,
);

if (!completedOnboarding) {
return <Navigate to={ONBOARDING_ROUTE} replace />;
}

return <>{children}</>;
};

export default InitializedV5Compat;
9 changes: 6 additions & 3 deletions ui/pages/deep-link/deep-link.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import type { Location as RouterLocation } from 'react-router-dom-v5-compat';
import log from 'loglevel';
import { useDispatch, useSelector } from 'react-redux';
import {
Expand Down Expand Up @@ -154,8 +154,11 @@ async function updateStateFromUrl(
}
}

export const DeepLink = () => {
const location = useLocation();
type DeepLinkProps = {
location: RouterLocation;
};

export const DeepLink = ({ location }: DeepLinkProps) => {
const t = useI18nContext() as TranslateFunction;
const dispatch = useDispatch();
// it's technically not possible for a natural flow to reach this page
Expand Down
2 changes: 1 addition & 1 deletion ui/pages/defi/components/defi-details-list.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jest.mock('react-router-dom-v5-compat', () => {
describe('DeFiDetailsPage', () => {
const store = configureMockStore([thunk])(mockState);

beforeAll(() => {
beforeEach(() => {
jest.clearAllMocks();
});

Expand Down
21 changes: 9 additions & 12 deletions ui/pages/defi/components/defi-details-page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,7 @@ import { renderWithProvider } from '../../../../test/lib/render-helpers-navigate
import mockState from '../../../../test/data/mock-state.json';
import DeFiPage from './defi-details-page';

const mockUseParams = jest
.fn()
.mockReturnValue({ chainId: CHAIN_IDS.MAINNET, protocolId: 'aave' });

jest.mock('react-router-dom', () => {
return {
...jest.requireActual('react-router-dom'),
useParams: () => mockUseParams(),
};
});
const mockNavigate = jest.fn();

describe('DeFiDetailsPage', () => {
const mockStore = {
Expand Down Expand Up @@ -79,7 +70,7 @@ describe('DeFiDetailsPage', () => {

const store = configureMockStore([thunk])(mockStore);

beforeAll(() => {
beforeEach(() => {
jest.clearAllMocks();
});

Expand All @@ -89,7 +80,13 @@ describe('DeFiDetailsPage', () => {
});

it('renders defi asset page', () => {
const { container } = renderWithProvider(<DeFiPage />, store);
const { container } = renderWithProvider(
<DeFiPage
navigate={mockNavigate}
params={{ chainId: CHAIN_IDS.MAINNET, protocolId: 'aave' }}
/>,
store,
);

expect(container).toMatchSnapshot();
});
Expand Down
25 changes: 14 additions & 11 deletions ui/pages/defi/components/defi-details-page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useMemo } from 'react';
import { useHistory, useParams, Redirect } from 'react-router-dom';
import { Navigate } from 'react-router-dom-v5-compat';
import { useSelector } from 'react-redux';
import {
Display,
Expand Down Expand Up @@ -45,22 +45,25 @@
);
}, [positions]);

const DeFiPage = () => {
const { chainId, protocolId } = useParams<{
chainId: '0x' & string;
protocolId: string;
}>() as { chainId: '0x' & string; protocolId: string };
type DeFiPageProps = {
navigate: (to: string | number) => void;
params: { chainId: string; protocolId: string };
};

const DeFiPage = ({ navigate, params }: DeFiPageProps) => {
const { formatCurrencyWithMinThreshold } = useFormatters();
const { chainId, protocolId } = params;
const defiPositions = useSelector(getDefiPositions);
const selectedAccount = useSelector(getSelectedAccount);

const history = useHistory();
const t = useI18nContext();
const { privacyMode } = useSelector(getPreferences);

// TODO: Get value in user's preferred currency
const protocolPosition =
defiPositions[selectedAccount.address]?.[chainId]?.protocols[protocolId];
defiPositions[selectedAccount.address]?.[
chainId as keyof typeof defiPositions[string]

Check failure on line 65 in ui/pages/defi/components/defi-details-page.tsx

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Replace `typeof·defiPositions` with `(typeof·defiPositions)`
]?.protocols[protocolId];

const extractedTokens = useMemo(() => {
return Object.keys(protocolPosition?.positionTypes || {}).reduce(
Expand All @@ -82,7 +85,7 @@
};

if (!protocolPosition) {
return <Redirect to={{ pathname: DEFAULT_ROUTE }} />;
return <Navigate to={DEFAULT_ROUTE} replace />;
}

return (
Expand All @@ -100,7 +103,7 @@
size={ButtonIconSize.Sm}
ariaLabel={t('back')}
iconName={IconName.ArrowLeft}
onClick={() => history.push(DEFAULT_ROUTE)}
onClick={() => navigate(DEFAULT_ROUTE)}
/>
</Box>

Expand All @@ -119,7 +122,7 @@
{protocolPosition.protocolDetails.name}
</Text>
<AssetCellBadge
chainId={chainId}
chainId={chainId as (typeof CHAIN_IDS)[keyof typeof CHAIN_IDS]}
tokenImage={protocolPosition.protocolDetails.iconUrl}
symbol={protocolPosition.protocolDetails.name}
data-testid="defi-details-page-protocol-badge"
Expand Down
17 changes: 11 additions & 6 deletions ui/pages/keychains/reveal-seed.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import qrCode from 'qrcode-generator';
import React, { useContext, useEffect, useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useParams } from 'react-router-dom';
import { getErrorMessage } from '../../../shared/modules/error';
import {
MetaMetricsEventCategory,
Expand Down Expand Up @@ -44,9 +44,7 @@ import { endTrace, trace, TraceName } from '../../../shared/lib/trace';
const PASSWORD_PROMPT_SCREEN = 'PASSWORD_PROMPT_SCREEN';
const REVEAL_SEED_SCREEN = 'REVEAL_SEED_SCREEN';

export default function RevealSeedPage() {
const history = useHistory();
const { keyringId } = useParams();
function RevealSeedPage({ navigate, keyringId }) {
const dispatch = useDispatch();
const t = useI18nContext();
const trackEvent = useContext(MetaMetricsContext);
Expand Down Expand Up @@ -267,7 +265,7 @@ export default function RevealSeedPage() {
hd_entropy_index: hdEntropyIndex,
},
});
history.goBack();
navigate(-1);
}}
>
{t('cancel')}
Expand Down Expand Up @@ -316,7 +314,7 @@ export default function RevealSeedPage() {
key_type: MetaMetricsEventKeyType.Srp,
},
});
history.goBack();
navigate(-1);
}}
>
{t('close')}
Expand Down Expand Up @@ -409,3 +407,10 @@ export default function RevealSeedPage() {
</Box>
);
}

RevealSeedPage.propTypes = {
navigate: PropTypes.func.isRequired,
keyringId: PropTypes.string,
};

export default RevealSeedPage;
Loading
Loading