Skip to content

feat: open prevent page leave modal on browser back button navigation #12061

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
88 changes: 85 additions & 3 deletions packages/ui/src/elements/LeaveWithoutSaving/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use client'
import React, { useCallback } from 'react'
import React, { useCallback, useEffect } from 'react'

import type { OnCancel } from '../ConfirmationModal/index.js'

Expand All @@ -12,34 +12,116 @@ import { usePreventLeave } from './usePreventLeave.js'

const modalSlug = 'leave-without-saving'

// Workaround to show the prevent leave page modal
// when clicking the browser navigation button.
// Note that this hook assumes only back button being used
// and not forward button. Which is the case for most of the time.
const useOnBrowserHistoryChange = ({
hasAcceptedLeave,
hasCancelledLeave,
onLeave,
onPrevent,
onStay,
shouldPreventLeave,
skip,
}: {
hasAcceptedLeave: boolean
hasCancelledLeave: boolean
onLeave: () => void
onPrevent: () => void
onStay: () => void
shouldPreventLeave: boolean
skip: boolean
}) => {
// Push a duplicated history entry to the stack
// so that when the popstate event is triggered
// it doesn't immediately navigate away.
// This creates a fake visual and we can show the
// prevent leave page modal in the meantime
useEffect(() => {
window.history.pushState(null, '', window.location.href)
}, [])

const handlePopState = useCallback(() => {
if (!skip) {
if (shouldPreventLeave) {
onPrevent()
} else {
window.history.go(-2) // -2 because we pushed a duplicate entry
}
}
}, [onPrevent, shouldPreventLeave, skip])

useEffect(() => {
window.addEventListener('popstate', handlePopState)

return () => {
window.removeEventListener('popstate', handlePopState)
}
}, [handlePopState])

useEffect(() => {
if (!skip) {
if (hasAcceptedLeave) {
onLeave()
window.history.go(-2)
} else if (hasCancelledLeave) {
onStay()
window.history.pushState(null, '', window.location.href) // Push a duplicate entry to the stack
}
}
}, [hasAcceptedLeave, hasCancelledLeave, onLeave, onStay, skip])
}

export const LeaveWithoutSaving: React.FC = () => {
const { closeModal, openModal } = useModal()
const modified = useFormModified()
const { isValid } = useForm()
const { user } = useAuth()
const [hasAccepted, setHasAccepted] = React.useState(false)
const [hasCancelled, setHasCancelled] = React.useState(false)
const { t } = useTranslation()

const prevent = Boolean((modified || !isValid) && user)

const onPrevent = useCallback(() => {
openModal(modalSlug)
// Reset the modal confirm and cancel state
setHasAccepted(false)
setHasCancelled(false)
}, [openModal])

const handleAccept = useCallback(() => {
closeModal(modalSlug)
setHasAccepted(true)
}, [closeModal])

usePreventLeave({ hasAccepted, onAccept: handleAccept, onPrevent, prevent })

const onCancel: OnCancel = useCallback(() => {
closeModal(modalSlug)
setHasCancelled(true)
}, [closeModal])

const onConfirm = useCallback(() => {
setHasAccepted(true)
}, [])

const { preventTriggered } = usePreventLeave({
hasAccepted,
onAccept: handleAccept,
onPrevent,
prevent,
})

useOnBrowserHistoryChange({
hasAcceptedLeave: hasAccepted,
hasCancelledLeave: hasCancelled,
onLeave: handleAccept,
onPrevent,
onStay: onCancel,
shouldPreventLeave: prevent,
skip: preventTriggered,
})

return (
<ConfirmationModal
body={t('general:changesNotSaved')}
Expand Down
12 changes: 11 additions & 1 deletion packages/ui/src/elements/LeaveWithoutSaving/usePreventLeave.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// Credit: `react-use` maintainers
// - Source: https://github.com/streamich/react-use/blob/ade8d3905f544305515d010737b4ae604cc51024/src/useBeforeUnload.ts#L2
import { useRouter } from 'next/navigation.js'
import { useCallback, useEffect, useRef } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'

import { useRouteTransition } from '../../providers/RouteTransition/index.js'

Expand Down Expand Up @@ -79,6 +79,11 @@ export const usePreventLeave = ({
const router = useRouter()
const cancelledURL = useRef<string>('')

// This state is added to accomodate the workaround for useOnBrowserHistoryChange.
// This is to prevent useOnBrowserHistoryChange fires the prevent modal too
// when there's an in app navigation.
const [preventTriggered, setPreventTriggered] = useState(false)

// check when page is about to be changed
useEffect(() => {
function isAnchorOfCurrentUrl(currentUrl: string, newUrl: string) {
Expand Down Expand Up @@ -130,6 +135,7 @@ export const usePreventLeave = ({
event.stopPropagation()

if (typeof onPrevent === 'function') {
setPreventTriggered(true)
onPrevent()
}
}
Expand Down Expand Up @@ -157,4 +163,8 @@ export const usePreventLeave = ({
startRouteTransition(() => router.push(cancelledURL.current))
}
}, [hasAccepted, onAccept, router, startRouteTransition])

return {
preventTriggered,
}
}