Skip to content

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

fix(studio): resolve dirty notebook save conflicts (#49540)

Chariseabb87564b65
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index b62220e86b7..d4125fe3b2b 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -12,6 +12,7 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { acceptUntrustedSql } from '@supabase/pg-meta'
+import { useQueryClient } from '@tanstack/react-query'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import {
Check,
@@ -59,7 +60,10 @@ import { type QueryEditorHandle } from './QueryEditor'
import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useContentDeleteMutation } from '@/data/content/content-delete-mutation'
-import { hasDiscardableChanges } from '@/data/content/notebooks/notebook-cache'
+import {
+ evictNotebookFromCaches,
+ hasDiscardableChanges,
+} from '@/data/content/notebooks/notebook-cache'
import {
isQueryCell,
WritableCell,
@@ -80,6 +84,7 @@ export const ExplorerNotebookTab = () => {
const { id, ref } = useParams()
const tabs = useTabsStateSnapshot()
const snap = useNotebooksStateSnapshot()
+ const queryClient = useQueryClient()
const { createChat, isCreating } = useCreateChat()
const [isIntellisenseEnabled, setIsIntellisenseEnabled] = useLocalStorageQuery(
@@ -96,6 +101,7 @@ export const ExplorerNotebookTab = () => {
const [isRunningNotebook, setIsRunningNotebook] = useState(false)
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
const [isSaveBeforeAnalyzeOpen, setIsSaveBeforeAnalyzeOpen] = useState(false)
+ const [isSaveConflictOpen, setIsSaveConflictOpen] = useState(false)
const [pendingMutationCells, setPendingMutationCells] = useState<
{ id: string; title: string }[] | null
>(null)
@@ -199,7 +205,7 @@ export const ExplorerNotebookTab = () => {
runNotebook({ cellIdsToRun, force: true })
}
- const handleSaveNotebook = () => {
+ const persistNotebook = () => {
const notebookId = currentNotebook?.notebook.id
if (!ref || !notebookId || !name || !content) return
@@ -231,6 +237,10 @@ export const ExplorerNotebookTab = () => {
}),
}
+ if (snap.serverDivergedWhileDirty.get(notebookId) === 'deleted') {
+ writableContent.cells = writableContent.cells.map(({ _id: _, ...cell }) => cell)
+ }
+
// [Joshen] For tracking if a notebook is updated while being saved, so that we do not
// incorrectly show the saved toast if it's subsequently then saved once again while
// the initial save is midflight
@@ -245,6 +255,32 @@ export const ExplorerNotebookTab = () => {
})
}
+ const handleSaveNotebook = () => {
+ const notebookId = currentNotebook?.notebook.id
+ if (notebookId && snap.serverDivergedWhileDirty.get(notebookId)) {
+ setIsSaveConflictOpen(true)
+ return
+ }
+
+ persistNotebook()
+ }
+
+ const handleSaveAnyway = () => {
+ setIsSaveConflictOpen(false)
+ persistNotebook()
+ }
+
+ const handleDiscardNotebookChanges = async () => {
+ if (!ref || !id) return
+
+ const wasDeletedOnServer = snap.serverDivergedWhileDirty.get(id) === 'deleted'
+ setIsSaveConflictOpen(false)
+ const evicted = await evictNotebookFromCaches({ queryClient, projectRef: ref, id })
+ if (wasDeletedOnServer && evicted) {
+ tabs.removeTab(createTabId('notebook', { id }))
+ }
+ }
+
const handleAnalyze = () => {
createChat({
name: `Analyze ${name} notebook`,
@@ -463,6 +499,25 @@ export const ExplorerNotebookTab = () => {
</p>
</ConfirmationModal>
+ <ConfirmationModal
+ size="small"
+ visible={isSaveConflictOpen}
+ title="Assistant changes detected"
+ additionalActionLabel="Discard changes"
+ confirmLabel={
+ id && snap.serverDivergedWhileDirty.get(id) === 'deleted' ? 'Recreate' : 'Save anyway'
+ }
+ onAdditionalAction={handleDiscardNotebookChanges}
+ onCancel={() => setIsSaveConflictOpen(false)}
+ onConfirm={handleSaveAnyway}
+ >
+ <p className="text-sm">
+ {id && snap.serverDivergedWhileDirty.get(id) === 'deleted'
+ ? 'An assistant deleted this notebook after your local changes. Saving will recreate it.'
+ : "An assistant updated this notebook after your local changes. Saving will overwrite the assistant's update."}
+ </p>
+ </ConfirmationModal>
+
<ConfirmationModal
size="small"
visible={pendingMutationCells !== null}
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx
index 497d111046f..c12a5f123d3 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx
@@ -1,7 +1,8 @@
import { QueryClient } from '@tanstack/react-query'
-import { screen } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { HttpResponse } from 'msw'
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { ExplorerNotebookTab } from '../ExplorerNotebookTab'
import type { components } from '@/data/api'
@@ -16,7 +17,7 @@ import {
} from '@/lib/ai/test-fixtures'
import { notebooksState } from '@/state/notebooks/notebooks-state'
import type { Notebook } from '@/state/notebooks/types'
-import { createTabsState, TabsStateContext } from '@/state/tabs'
+import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
@@ -62,14 +63,18 @@ const seedNotebook = () => {
notebooksState.setNotebook({ projectRef: PROJECT_REF, notebook })
}
-const renderNotebookTab = (queryClient: QueryClient) =>
+const renderNotebookTab = (queryClient: QueryClient, tabsState = createTabsState(PROJECT_REF)) =>
customRender(
- <TabsStateContext.Provider value={createTabsState(PROJECT_REF)}>
+ <TabsStateContext.Provider value={tabsState}>
<ExplorerNotebookTab />
</TabsStateContext.Provider>,
{ queryClient }
)
+afterEach(() => {
+ notebooksState.serverDivergedWhileDirty.clear()
+})
+
describe('ExplorerNotebookTab — assistant cache invalidation', () => {
it('refetches and renders the updated cells after an assistant update_notebook tool call completes', async () => {
setupSqlEditorMocks()
@@ -205,4 +210,235 @@ describe('ExplorerNotebookTab — assistant cache invalidation', () => {
expect(await screen.findByText('Notebook not found')).toBeInTheDocument()
expect(screen.queryByText('Original content')).not.toBeInTheDocument()
})
+
+ it('saves normally without a conflict dialog when the notebook has not diverged', async () => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ const queryClient = new QueryClient()
+ let mutationCount = 0
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => {
+ mutationCount += 1
+ return HttpResponse.json({ id: NOTEBOOK_ID })
+ },
+ })
+
+ renderNotebookTab(queryClient)
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+
+ await waitFor(() => expect(mutationCount).toBe(1))
+ expect(
+ screen.queryByRole('dialog', { name: 'Assistant changes detected' })
+ ).not.toBeInTheDocument()
+ })
+
+ it.each([
+ {
+ type: 'updated' as const,
+ description:
+ "An assistant updated this notebook after your local changes. Saving will overwrite the assistant's update.",
+ saveLabel: 'Save anyway',
+ },
+ {
+ type: 'deleted' as const,
+ description:
+ 'An assistant deleted this notebook after your local changes. Saving will recreate it.',
+ saveLabel: 'Recreate',
+ },
+ ])('shows the $type conflict copy before saving', async ({ type, description, saveLabel }) => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type })
+
+ renderNotebookTab(new QueryClient())
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+
+ const dialog = await screen.findByRole('dialog', { name: 'Assistant changes detected' })
+ expect(dialog).toHaveTextContent(description)
+ expect(dialog).toHaveTextContent(saveLabel)
+ expect(dialog).toHaveTextContent('Discard changes')
+ })
+
+ it('saves exactly once and clears the conflict only after a successful save', async () => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })
+ const queryClient = new QueryClient()
+ let mutationCount = 0
+ let resolveSave: (() => void) | undefined
+ const savePromise = new Promise<void>((resolve) => {
+ resolveSave = resolve
+ })
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: async () => {
+ mutationCount += 1
+ await savePromise
+ return HttpResponse.json({ id: NOTEBOOK_ID })
+ },
+ })
+
+ renderNotebookTab(queryClient)
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')
+ await userEvent.click(await screen.findByRole('button', { name: 'Save anyway' }))
+
+ await waitFor(() => expect(mutationCount).toBe(1))
+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')
+ resolveSave?.()
+ await waitFor(() =>
+ expect(notebooksState.serverDivergedWhileDirty.has(NOTEBOOK_ID)).toBe(false)
+ )
+ })
+
+ it('keeps the conflict marker when saving anyway fails', async () => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })
+ let mutationCount = 0
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => {
+ mutationCount += 1
+ return HttpResponse.json({ message: 'Save failed' }, { status: 500 })
+ },
+ })
+
+ renderNotebookTab(new QueryClient())
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Save anyway' }))
+
+ await waitFor(() => expect(mutationCount).toBe(1))
+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')
+ })
+
+ it('omits existing cell IDs when saving anyway recreates an assistant-deleted notebook', async () => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'deleted' })
+ let sentBody: Record<string, unknown> | undefined
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: async ({ request }) => {
+ sentBody = (await request.json()) as Record<string, unknown>
+ return HttpResponse.json({ id: NOTEBOOK_ID })
+ },
+ })
+
+ renderNotebookTab(new QueryClient())
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Recreate' }))
+
+ await waitFor(() => expect(sentBody).toBeDefined())
+ const content = sentBody?.content as { cells: Array<Record<string, unknown>> }
+ content.cells.forEach((cell) => expect(cell).not.toHaveProperty('_id'))
+ })
+
+ it('discards local changes without mutating and evicts the conflicted notebook', async () => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })
+ let mutationCount = 0
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => {
+ mutationCount += 1
+ return HttpResponse.json({ id: NOTEBOOK_ID })
+ },
+ })
+
+ renderNotebookTab(queryClient)
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Discard changes' }))
+
+ await waitFor(() => expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined())
+ expect(notebooksState.serverDivergedWhileDirty.has(NOTEBOOK_ID)).toBe(false)
+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()
+ expect(mutationCount).toBe(0)
+ })
+
+ it('closes the notebook tab when discarding edits after an assistant deletion', async () => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'deleted' })
+ const tabsState = createTabsState(PROJECT_REF)
+ const tabId = createTabId('notebook', { id: NOTEBOOK_ID })
+ tabsState.addTab({ id: tabId, type: 'notebook', metadata: { notebookId: NOTEBOOK_ID } })
+
+ renderNotebookTab(new QueryClient(), tabsState)
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Discard changes' }))
+
+ await waitFor(() => expect(tabsState.tabsMap[tabId]).toBeUndefined())
+ })
+
+ it.each(['the close button', 'the backdrop'])(
+ 'dismisses the conflict with %s without changing notebook state',
+ async (dismissal) => {
+ setupSqlEditorMocks()
+ seedNotebook()
+ notebooksState.updateCells({
+ id: NOTEBOOK_ID,
+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,
+ })
+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })
+
+ renderNotebookTab(new QueryClient())
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
+ const dialog = await screen.findByRole('dialog', { name: 'Assistant changes detected' })
+ if (dismissal === 'the close button') {
+ await userEvent.click(screen.getByRole('button', { name: 'Close' }))
+ } else {
+ fireEvent.pointerDown(dialog.parentElement!, { button: 0, ctrlKey: false })
+ }
+
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'Assistant changes detected' })
+ ).not.toBeInTheDocument()
+ )
+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeDefined()
+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')
+ }
+ )
})
diff --git a/apps/studio/data/content/notebooks/notebook-cache.test.ts b/apps/studio/data/content/notebooks/notebook-cache.test.ts
index 875f5c23103..1fe4f86de62 100644
--- a/apps/studio/data/content/notebooks/notebook-cache.test.ts
+++ b/apps/studio/data/content/notebooks/notebook-cache.test.ts
@@ -54,7 +54,7 @@ describe('evictNotebookFromCaches', () => {
expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()
})
- it('leaves an unsaved notebook and its cache entry untouched', async () => {
+ it('removes an unsaved notebook and its cache entry after its caller confirms discard', async () => {
seedNotebook('new')
const queryClient = new QueryClient()
seedQueryData(queryClient)
@@ -65,14 +65,12 @@ describe('evictNotebookFromCaches', () => {
id: NOTEBOOK_ID,
})
- expect(evicted).toBe(false)
- expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeDefined()
- expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toEqual({
- id: NOTEBOOK_ID,
- })
+ expect(evicted).toBe(true)
+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()
+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()
})
- it('no-ops for an id not present in the store', async () => {
+ it('drops a stale cache entry when the notebook is not present in the store', async () => {
const queryClient = new QueryClient()
seedQueryData(queryClient)
@@ -82,9 +80,7 @@ describe('evictNotebookFromCaches', () => {
id: NOTEBOOK_ID,
})
- expect(evicted).toBe(false)
- expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toEqual({
- id: NOTEBOOK_ID,
- })
+ expect(evicted).toBe(true)
+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()
})
})
diff --git a/apps/studio/data/content/notebooks/notebook-cache.ts b/apps/studio/data/content/notebooks/notebook-cache.ts
index be8db93ff53..10ce4711450 100644
--- a/apps/studio/data/content/notebooks/notebook-cache.ts
+++ b/apps/studio/data/content/notebooks/notebook-cache.ts
@@ -23,8 +23,7 @@ export function hasDiscardableChanges(
/**
* Evicts a notebook from the React Query cache and the Valtio store together.
- * Applies to a persisted notebook (always safe to refetch) and to a dirty
- * unsaved notebook (safe once the caller has confirmed discarding it).
+ * Callers are responsible for confirming before discarding unsaved edits.
*
* Removes the query entry outright rather than invalidating it: a mounted
* `useNotebookQuery` observer would otherwise read the stale cached value
@@ -32,10 +31,8 @@ export function hasDiscardableChanges(
* merge guard would treat that stale merge as already-loaded and drop the
* real update.
*
- * @returns A boolean indicating whether the notebook was successfully evicted
- * from the cache.
*/
-export async function evictNotebookFromCaches({
+export function evictNotebookFromCaches({
queryClient,
projectRef,
id,
@@ -43,11 +40,7 @@ export async function evictNotebookFromCaches({
queryClient: QueryClient
projectRef: string
id: string
-}): Promise<boolean> {
- const stateNotebook = notebooksState.notebooks[id]
- const canEvict = stateNotebook?.status === 'saved' || hasDiscardableChanges(stateNotebook)
- if (!canEvict) return false
-
+}): boolean {
notebooksState.removeNotebook({ id })
queryClient.removeQueries({ queryKey: contentKeys.resource(projectRef, id) })
diff --git a/packages/ui-patterns/src/Dialogs/ConfirmationModal.test.tsx b/packages/ui-patterns/src/Dialogs/ConfirmationModal.test.tsx
new file mode 100644
index 00000000000..cf87dba142a
--- /dev/null
+++ b/packages/ui-patterns/src/Dialogs/ConfirmationModal.test.tsx
@@ -0,0 +1,48 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+
+import { ConfirmationModal } from './ConfirmationModal'
+
+describe('ConfirmationModal', () => {
+ it('keeps an additional footer action separate from dismissal', async () => {
+ const onCancel = vi.fn()
+ const onAdditionalAction = vi.fn()
+
+ render(
+ <ConfirmationModal
+ visible
+ title="Assistant changes detected"
+ additionalActionLabel="Discard changes"
+ onCancel={onCancel}
+ onAdditionalAction={onAdditionalAction}
+ onConfirm={vi.fn()}
+ />
+ )
+
+ await userEvent.click(screen.getByRole('button', { name: 'Discard changes' }))
+
+ expect(onAdditionalAction).toHaveBeenCalledOnce()
+ expect(onCancel).not.toHaveBeenCalled()
+ })
+
+ it('does not dismiss while loading', async () => {
+ const onCancel = vi.fn()
+
+ render(
+ <ConfirmationModal
+ visible
+ loading
+ title="Saving notebook"
+ onCancel={onCancel}
+ onConfirm={vi.fn()}
+ />
+ )
+
+ const dialog = screen.getByRole('dialog', { name: 'Saving notebook' })
+ await userEvent.click(screen.getByRole('button', { name: 'Close' }))
+ fireEvent.pointerDown(dialog.parentElement!, { button: 0, ctrlKey: false })
+
+ expect(onCancel).not.toHaveBeenCalled()
+ })
+})
diff --git a/packages/ui-patterns/src/Dialogs/ConfirmationModal.tsx b/packages/ui-patterns/src/Dialogs/ConfirmationModal.tsx
index 5b70b94d8c0..89460076fbd 100644
--- a/packages/ui-patterns/src/Dialogs/ConfirmationModal.tsx
+++ b/packages/ui-patterns/src/Dialogs/ConfirmationModal.tsx
@@ -27,8 +27,12 @@ export interface ConfirmationModalProps {
confirmLabel?: string
confirmLabelLoading?: string
cancelLabel?: string
+ /** Overrides the first footer action label when `onAdditionalAction` is provided. */
+ additionalActionLabel?: string
onConfirm: () => void
onCancel: () => void
+ /** Overrides the first footer action while `onCancel` continues to handle dismissal. */
+ onAdditionalAction?: () => void
disabled?: boolean
variant?: React.ComponentProps<typeof Alert>['variant']
alert?: {
@@ -51,8 +55,10 @@ export const ConfirmationModal = forwardRef<
visible,
onCancel,
onConfirm,
+ onAdditionalAction,
loading: loading_,
cancelLabel = 'Cancel',
+ additionalActionLabel,
confirmLabel = 'Submit',
confirmLabelLoading,
alert = undefined,
@@ -75,6 +81,10 @@ export const ConfirmationModal = forwardRef<
if (loading_ === undefined) setLoading(true)
}
+ const preventDismissWhileLoading = (event: Event) => {
+ if (loading) event.preventDefault()
+ }
+
useEffect(() => {
if (visible && loading_ === undefined) {
setLoading(false)
@@ -92,10 +102,8 @@ export const ConfirmationModal = forwardRef<
<Dialog
open={visible}
{...props}
- onOpenChange={() => {
- if (visible) {
- onCancel()
- }
+ onOpenChange={(open) => {
+ if (!open && visible && !loading) onCancel()
}}
>
<DialogContent
@@ -103,6 +111,8 @@ export const ConfirmationModal = forwardRef<
ref={ref}
className="p-0 gap-0 pb-5 block!"
size={size}
+ onPointerDownOutside={preventDismissWhileLoading}
+ onEscapeKeyDown={preventDismissWhileLoading}
>
<DialogHeader className={cn('border-b')} padding={'small'}>
<DialogTitle>{title}</DialogTitle>
@@ -131,9 +141,9 @@ export const ConfirmationModal = forwardRef<
block
variant="default"
disabled={loading}
- onClick={() => onCancel()}
+ onClick={() => (onAdditionalAction ?? onCancel)()}
>
- {cancelLabel}
+ {additionalActionLabel ?? cancelLabel}
</Button>
<Button