Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix(Tx flow): prevent navigation when tx modal is open #4909

Draft
wants to merge 2 commits into
base: dev
Choose a base branch
from
Draft
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
27 changes: 6 additions & 21 deletions apps/web/src/components/tx-flow/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { createContext, type ReactElement, type ReactNode, useState, useEffect, useCallback, useRef } from 'react'
import { usePathname } from 'next/navigation'
import { createContext, type ReactElement, type ReactNode, useState, useCallback, useRef } from 'react'
import TxModalDialog from '@/components/common/TxModalDialog'
import { SuccessScreenFlow, NestedTxSuccessScreenFlow } from './flows'
import useSafeAddress from '@/hooks/useSafeAddress'
import useChainId from '@/hooks/useChainId'
import { useWalletContext } from '@/hooks/wallets/useWallet'
import { usePreventNavigation } from '@/hooks/usePreventNavigation'

const noop = () => {}

Expand All @@ -20,7 +18,6 @@ export const TxModalContext = createContext<TxModalContextType>({
setFullWidth: noop,
})

// TODO: Rename TxModalProvider, setTxFlow, TxModalDialog to not contain Tx since it can be used for any type of modal as a global provider
const confirmClose = () => {
return confirm('Closing this window will discard your current progress.')
}
Expand All @@ -30,21 +27,19 @@ export const TxModalProvider = ({ children }: { children: ReactNode }): ReactEle
const [fullWidth, setFullWidth] = useState<boolean>(false)
const shouldWarn = useRef<boolean>(true)
const onClose = useRef<() => void>(noop)
const safeId = useChainId() + useSafeAddress()
const prevSafeId = useRef<string>(safeId ?? '')
const pathname = usePathname()
const prevPathname = useRef<string | null>(pathname)
const { setSignerAddress } = useWalletContext() ?? {}

const handleModalClose = useCallback(() => {
if (shouldWarn.current && !confirmClose()) {
return
return false
}
onClose.current()
onClose.current = noop
setFlow(undefined)

setSignerAddress?.(undefined)

return true
}, [setSignerAddress])

// Open a new tx flow, close the previous one if any
Expand All @@ -70,17 +65,7 @@ export const TxModalProvider = ({ children }: { children: ReactNode }): ReactEle
[],
)

// Close the modal when the user navigates to a different Safe or route
useEffect(() => {
if (safeId === prevSafeId.current && pathname === prevPathname.current) return

prevSafeId.current = safeId
prevPathname.current = pathname

if (txFlow) {
handleModalClose()
}
}, [txFlow, safeId, pathname, handleModalClose])
usePreventNavigation(txFlow ? handleModalClose : undefined)

return (
<TxModalContext.Provider value={{ txFlow, setTxFlow, setFullWidth }}>
Expand Down
48 changes: 48 additions & 0 deletions apps/web/src/hooks/usePreventNavigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { useRef, useEffect } from 'react'
import { useRouter } from 'next/router'

export function usePreventNavigation(onNavigate?: () => boolean): void {
const router = useRouter()
const previousPath = useRef(router.asPath)
const isRedirecting = useRef(false)
const { asPath, replace } = router

useEffect(() => {
const previousRoute = previousPath.current
if (asPath === previousRoute) return
previousPath.current = asPath

if (isRedirecting.current) {
isRedirecting.current = false
return
}

if (!onNavigate) return
const allowNavigation = onNavigate()

if (!allowNavigation) {
isRedirecting.current = true
replace(previousRoute, undefined, { shallow: true })
}
}, [replace, asPath, onNavigate])

useEffect(() => {
if (!onNavigate) return

const onLinkClick = (e: MouseEvent) => {
const target = e.target as HTMLElement
const link = target.closest('a')
if (!link || !link.getAttribute('href')) return
if (onNavigate()) return
e.preventDefault()
e.stopImmediatePropagation()
e.stopPropagation()
}

document.addEventListener('mousedown', onLinkClick)

return () => {
document.removeEventListener('mousedown', onLinkClick)
}
}, [onNavigate])
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import * as messages from '@/utils/safe-messages'
import { faker } from '@faker-js/faker'
import { Interface } from 'ethers'
import { getCreateCallDeployment } from '@safe-global/safe-deployments'
import { useCurrentChain } from '@/hooks/useChains'
import * as chainHooks from '@/hooks/useChains'
import { chainBuilder } from '@/tests/builders/chains'

const appInfo = {
Expand All @@ -33,21 +33,13 @@ jest.mock('./notifications', () => {
}
})

jest.mock('@/hooks/useChains', () => ({
__esModule: true,
...jest.requireActual('@/hooks/useChains'),
useCurrentChain: jest.fn(),
}))

describe('useSafeWalletProvider', () => {
const mockUseCurrentChain = useCurrentChain as jest.MockedFunction<typeof useCurrentChain>

beforeEach(() => {
jest.clearAllMocks()

mockUseCurrentChain.mockReturnValue(
chainBuilder().with({ chainId: '1', recommendedMasterCopyVersion: '1.4.1' }).build(),
)
jest.spyOn(chainHooks, 'useCurrentChain').mockImplementation(() => {
return chainBuilder().with({ chainId: '1', recommendedMasterCopyVersion: '1.4.1' }).build()
})
})

describe('useSafeWalletProvider', () => {
Expand Down
Loading