Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(studio): guard unsaved pipeline creation navigation (#51823)

Danny White69f46a4ab562
diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.tsx
index f58c876e7c3..700b7afd61a 100644
--- a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.tsx
@@ -23,10 +23,10 @@ import { PipelineReviewCosts } from './PipelineReviewCosts'
import { PipelineValidationAdmonition } from './PipelineValidationAdmonition'
import { usePipelineConnectionValidation } from './usePipelineConnectionValidation'
import { usePipelineDataValidation } from './usePipelineDataValidation'
+import { usePipelineNavigationGuard } from './usePipelineNavigationGuard'
import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
import { SteppedFlow, SteppedFlowHeader } from '@/components/ui/SteppedFlow/SteppedFlow'
import { useReplicationSourceId } from '@/data/replication/sources-query'
-import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
type FlowDestination = 'BigQuery' | 'DuckLake' | 'Snowflake' | 'ClickHouse'
const steps = [
@@ -57,23 +57,12 @@ export const PipelineCreationFlow = ({
defaultValues: generateDefaultValues({ catalogToken: '', editMode: false }),
shouldUnregister: false,
})
- const canLeaveRef = useRef(false)
- const pendingHrefRef = useRef<string | undefined>(undefined)
const initialTypeRef = useRef(type)
const { isDirty } = form.formState
- const hasUnsavedChanges = isDirty || type !== initialTypeRef.current
- const { confirmOnClose, modalProps } = useConfirmOnClose({
- checkIsDirty: () => hasUnsavedChanges,
- onClose: () => {
- canLeaveRef.current = true
- if (pendingHrefRef.current) window.location.assign(pendingHrefRef.current)
- else onClose()
- },
- })
- const handleClose = () => {
- pendingHrefRef.current = undefined
- confirmOnClose()
- }
+ const { requestNavigation, modalProps } = usePipelineNavigationGuard(
+ isDirty || type !== initialTypeRef.current
+ )
+ const handleClose = () => requestNavigation(onClose)
const { ref: projectRef } = useParams()
const { validateConnection, resetValidation, isValidating, isConnectionVerified, failures } =
usePipelineConnectionValidation({ projectRef, type, form })
@@ -104,24 +93,12 @@ export const PipelineCreationFlow = ({
if (step !== accessibleStep) void setStep(accessibleStep, { history: 'replace' })
}, [step, accessibleStep, setStep])
- useEffect(() => {
- if (!hasUnsavedChanges) return
- const handleBeforeUnload = (event: BeforeUnloadEvent) => {
- if (canLeaveRef.current) return
- event.preventDefault()
- event.returnValue = ''
- }
- window.addEventListener('beforeunload', handleBeforeUnload)
- return () => window.removeEventListener('beforeunload', handleBeforeUnload)
- }, [hasUnsavedChanges])
-
return (
<div className="flex min-h-screen flex-col bg-dash-sidebar">
<PipelineCreationHeader
onClose={handleClose}
onNavigate={(href) => {
- pendingHrefRef.current = href
- confirmOnClose()
+ requestNavigation(() => window.location.assign(href))
}}
/>
<main className="flex-1">
diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/usePipelineNavigationGuard.test.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/usePipelineNavigationGuard.test.tsx
new file mode 100644
index 00000000000..3fc70718798
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/usePipelineNavigationGuard.test.tsx
@@ -0,0 +1,95 @@
+import {
+ createBrowserHistory,
+ createRootRoute,
+ createRouter,
+ RouterContextProvider,
+} from '@tanstack/react-router'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { type ReactNode } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+
+import { usePipelineNavigationGuard } from './usePipelineNavigationGuard'
+
+const wizard = '/dashboard/project/test/database/pipelines/new'
+const list = '/dashboard/project/test/database/pipelines'
+
+const unload = () => {
+ const event = new Event('beforeunload', { cancelable: true })
+ window.dispatchEvent(event)
+ return event.defaultPrevented
+}
+
+describe('usePipelineNavigationGuard', () => {
+ it('reuses confirmation for explicit exits and bypasses unload only after discard', () => {
+ const exit = vi.fn()
+ const { result, rerender } = renderHook(({ dirty }) => usePipelineNavigationGuard(dirty), {
+ initialProps: { dirty: true },
+ })
+ act(() => result.current.requestNavigation(exit))
+ expect(result.current.modalProps.visible).toBe(true)
+ expect(unload()).toBe(true)
+ act(() => result.current.modalProps.onCancel())
+ expect(exit).not.toHaveBeenCalled()
+ expect(unload()).toBe(true)
+ act(() => result.current.requestNavigation(exit))
+ act(() => result.current.modalProps.onClose())
+ expect(exit).toHaveBeenCalledOnce()
+ expect(unload()).toBe(false)
+ rerender({ dirty: false })
+ expect(unload()).toBe(false)
+ })
+
+ it('leaves immediately without changes', () => {
+ const exit = vi.fn()
+ const { result } = renderHook(() => usePipelineNavigationGuard(false))
+ expect(unload()).toBe(false)
+ act(() => result.current.requestNavigation(exit))
+ expect(exit).toHaveBeenCalledOnce()
+ expect(result.current.modalProps.visible).toBe(false)
+ })
+
+ it('uses native TanStack history blocking for links and traversal, allowing step changes', async () => {
+ window.history.replaceState({}, '', list)
+ const history = createBrowserHistory()
+ history.push(wizard)
+ const router = createRouter({ routeTree: createRootRoute(), history })
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RouterContextProvider router={router}>{children}</RouterContextProvider>
+ )
+ const { result, unmount } = renderHook(() => usePipelineNavigationGuard(true), { wrapper })
+ try {
+ await act(async () => {
+ history.push(`${wizard}?step=connection`)
+ })
+ expect(history.location.search).toBe('?step=connection')
+ await act(async () => {
+ history.back()
+ })
+ await waitFor(() => expect(history.location.search).toBe(''))
+ expect(result.current.modalProps.visible).toBe(false)
+ await act(async () => {
+ history.back()
+ })
+ await waitFor(() => expect(result.current.modalProps.visible).toBe(true))
+ await act(async () => {
+ history.push('/another-page')
+ })
+ act(() => result.current.modalProps.onCancel())
+ await waitFor(() => expect(history.location.pathname).toBe(wizard))
+ await act(async () => {
+ history.forward()
+ })
+ await waitFor(() => expect(history.location.search).toBe('?step=connection'))
+ expect(result.current.modalProps.visible).toBe(false)
+ await act(async () => {
+ history.go(-2)
+ })
+ await waitFor(() => expect(result.current.modalProps.visible).toBe(true))
+ await act(async () => result.current.modalProps.onClose())
+ await waitFor(() => expect(history.location.pathname).toBe(list))
+ } finally {
+ unmount()
+ history.destroy()
+ }
+ })
+})
diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/usePipelineNavigationGuard.ts b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/usePipelineNavigationGuard.ts
new file mode 100644
index 00000000000..da5d7966ebc
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/usePipelineNavigationGuard.ts
@@ -0,0 +1,74 @@
+import { useRouter as useTanStackRouter } from '@tanstack/react-router'
+import { useEffect, useRef } from 'react'
+
+import { useLatest } from '@/hooks/misc/useLatest'
+import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
+
+export const usePipelineNavigationGuard = (hasChanges: boolean) => {
+ const router = useTanStackRouter({ warn: false })
+ const canLeave = useRef(false)
+ const pending = useRef<(() => void) | undefined>(undefined)
+ const cancelPending = useRef<(() => void) | undefined>(undefined)
+ const { confirmOnClose, modalProps } = useConfirmOnClose({
+ checkIsDirty: () => hasChanges,
+ onClose: () => {
+ canLeave.current = true
+ pending.current?.()
+ },
+ })
+ const requestNavigation = (proceed: () => void, cancel?: () => void) => {
+ // Keep the first requested destination while its confirmation is open.
+ if (pending.current) {
+ cancel?.()
+ return
+ }
+ pending.current = proceed
+ cancelPending.current = cancel
+ confirmOnClose()
+ }
+ const latest = useLatest({ hasChanges, requestNavigation })
+
+ useEffect(() => {
+ const handleBeforeUnload = (event: BeforeUnloadEvent) => {
+ if (!latest.current.hasChanges || canLeave.current) return
+ event.preventDefault()
+ event.returnValue = ''
+ }
+ window.addEventListener('beforeunload', handleBeforeUnload)
+ return () => window.removeEventListener('beforeunload', handleBeforeUnload)
+ }, [latest])
+
+ useEffect(() => {
+ if (!router) return
+ return router.history.block({
+ enableBeforeUnload: false,
+ blockerFn: ({ currentLocation, nextLocation }) => {
+ if (
+ !latest.current.hasChanges ||
+ canLeave.current ||
+ currentLocation.pathname === nextLocation.pathname
+ )
+ return false
+ return new Promise<boolean>((resolve) => {
+ latest.current.requestNavigation(
+ () => resolve(false),
+ () => resolve(true)
+ )
+ })
+ },
+ })
+ }, [router, latest])
+
+ return {
+ requestNavigation,
+ modalProps: {
+ ...modalProps,
+ onCancel: () => {
+ cancelPending.current?.()
+ pending.current = undefined
+ cancelPending.current = undefined
+ modalProps.onCancel()
+ },
+ },
+ }
+}