Skip to content

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

feat(studio): add setting to skip the SQL editor unsaved-changes prompt (#52029)

Drew McLellan6957daa3b700
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index 94e26d801d6..80e9541673a 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -2,17 +2,18 @@ import { Hotkey } from '@tanstack/react-hotkeys'
import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'
import {
AlignLeftIcon,
- CheckIcon,
ChevronDownIcon,
HeartIcon,
KeyboardIcon,
MoreVerticalIcon,
+ TriangleAlertIcon,
} from 'lucide-react'
import { toast } from 'sonner'
import {
Button,
cn,
DropdownMenu,
+ DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuRadioGroup,
@@ -45,6 +46,11 @@ import { useSqlEditorSaveCoordinator } from '@/state/sql-editor/sql-editor-save-
import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
+// DropdownMenuCheckboxItem puts its check indicator on the left. These menus show
+// it on the right, matching the other toggle items, so move the indicator over.
+const CHECKBOX_ITEM_CHECK_ON_RIGHT =
+ 'gap-x-2 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2 [&>span:first-child_svg]:text-primary'
+
export type UtilityActionsProps = {
id: string
runSource: QuerySourceBinding
@@ -85,6 +91,10 @@ export const UtilityActions = ({
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
true
)
+ const [confirmUnsavedChanges, setConfirmUnsavedChanges] = useLocalStorageQuery(
+ LOCAL_STORAGE_KEYS.SQL_EDITOR_CONFIRM_UNSAVED_CHANGES,
+ true
+ )
const [lastSelectedDb, setLastSelectedDb] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_LAST_SELECTED_DB(ref as string),
''
@@ -123,21 +133,32 @@ export const UtilityActions = ({
<Button
aria-label="More actions"
data-testid="sql-editor-utility-actions"
- className={cn('px-1', isAiOpen ? 'block 2xl:hidden' : 'hidden')}
+ className={cn('px-1', isAiOpen ? 'flex 2xl:hidden' : 'hidden')}
icon={<MoreVerticalIcon className="text-foreground-light" />}
/>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom">More actions</TooltipContent>
</Tooltip>
- <DropdownMenuContent className="w-48">
- <DropdownMenuItem className="justify-between" onClick={toggleIntellisense}>
- <span className="flex items-center gap-x-2">
- <KeyboardIcon size={14} className="text-foreground-light" />
- Intellisense enabled
- </span>
- {intellisenseEnabled && <CheckIcon className="text-primary" size={16} />}
- </DropdownMenuItem>
+ <DropdownMenuContent className="w-56">
+ <DropdownMenuCheckboxItem
+ className={CHECKBOX_ITEM_CHECK_ON_RIGHT}
+ checked={intellisenseEnabled}
+ onCheckedChange={toggleIntellisense}
+ >
+ <KeyboardIcon size={14} className="text-foreground-light" />
+ Intellisense enabled
+ </DropdownMenuCheckboxItem>
+ {isManualSaveEnabled && (
+ <DropdownMenuCheckboxItem
+ className={CHECKBOX_ITEM_CHECK_ON_RIGHT}
+ checked={confirmUnsavedChanges}
+ onCheckedChange={setConfirmUnsavedChanges}
+ >
+ <TriangleAlertIcon size={14} className="text-foreground-light" />
+ Confirm on discard
+ </DropdownMenuCheckboxItem>
+ )}
{IS_PLATFORM && (
<>
<DropdownMenuSeparator />
@@ -183,18 +204,32 @@ export const UtilityActions = ({
<Button
variant="text"
className="px-1"
- icon={<KeyboardIcon className="text-foreground-light" />}
- aria-label="Enable Intellisense"
+ icon={<MoreVerticalIcon className="text-foreground-light" />}
+ aria-label="More actions"
/>
</DropdownMenuTrigger>
</TooltipTrigger>
- <TooltipContent side="bottom">Enable Intellisense</TooltipContent>
+ <TooltipContent side="bottom">More actions</TooltipContent>
</Tooltip>
- <DropdownMenuContent className="w-48">
- <DropdownMenuItem className="justify-between" onClick={toggleIntellisense}>
+ <DropdownMenuContent className="w-56">
+ <DropdownMenuCheckboxItem
+ className={CHECKBOX_ITEM_CHECK_ON_RIGHT}
+ checked={intellisenseEnabled}
+ onCheckedChange={toggleIntellisense}
+ >
+ <KeyboardIcon size={14} className="text-foreground-light" />
Intellisense enabled
- {intellisenseEnabled && <CheckIcon className="text-primary" size={16} />}
- </DropdownMenuItem>
+ </DropdownMenuCheckboxItem>
+ {isManualSaveEnabled && (
+ <DropdownMenuCheckboxItem
+ className={CHECKBOX_ITEM_CHECK_ON_RIGHT}
+ checked={confirmUnsavedChanges}
+ onCheckedChange={setConfirmUnsavedChanges}
+ >
+ <TriangleAlertIcon size={14} className="text-foreground-light" />
+ Confirm on discard
+ </DropdownMenuCheckboxItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
diff --git a/apps/studio/components/layouts/Tabs/Tabs.tsx b/apps/studio/components/layouts/Tabs/Tabs.tsx
index e1d44fd3c8b..11d56b44892 100644
--- a/apps/studio/components/layouts/Tabs/Tabs.tsx
+++ b/apps/studio/components/layouts/Tabs/Tabs.tsx
@@ -13,6 +13,7 @@ import { AnimatePresence, motion } from 'motion/react'
import { useRouter } from 'next/router'
import { ReactNode, useState } from 'react'
import {
+ Checkbox,
cn,
ContextMenu,
ContextMenuContent,
@@ -22,6 +23,7 @@ import {
TabsList,
TabsTrigger,
} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { useEditorType } from '../editors/EditorsLayout.hooks'
import { CollapseButton } from './CollapseButton'
@@ -61,6 +63,7 @@ export const EditorTabs = ({
const tabs = useTabsStateSnapshot()
const [pendingClose, setPendingClose] = useState<(() => void) | null>(null)
const [pendingConfirmation, setPendingConfirmation] = useState<TabCloseConfirmation | null>(null)
+ const [isOptOutChecked, setIsOptOutChecked] = useState(false)
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
@@ -119,6 +122,12 @@ export const EditorTabs = ({
}
}
+ const resetPendingClose = () => {
+ setPendingClose(null)
+ setPendingConfirmation(null)
+ setIsOptOutChecked(false)
+ }
+
const handleClose = (tabId: string) => {
closeWithConfirmation([tabId], () => {
tabs.handleTabClose({ id: tabId, router, editor, onClearDashboardHistory })
@@ -319,17 +328,30 @@ export const EditorTabs = ({
<DiscardChangesConfirmationDialog
visible={pendingClose !== null}
onClose={() => {
+ if (isOptOutChecked) pendingConfirmation?.optOut?.onOptOut()
pendingClose?.()
- setPendingClose(null)
- setPendingConfirmation(null)
- }}
- onCancel={() => {
- setPendingClose(null)
- setPendingConfirmation(null)
+ resetPendingClose()
}}
+ onCancel={resetPendingClose}
title={pendingConfirmation?.title ?? 'Unsaved changes'}
description={pendingConfirmation?.description}
- />
+ >
+ {pendingConfirmation?.optOut && (
+ <FormItemLayout
+ isReactForm={false}
+ layout="flex"
+ name="optOutOfCloseConfirmation"
+ label={pendingConfirmation.optOut.label}
+ className="[&>div:first-child>button]:translate-y-0.5"
+ >
+ <Checkbox
+ id="optOutOfCloseConfirmation"
+ checked={isOptOutChecked}
+ onCheckedChange={(value) => setIsOptOutChecked(!!value)}
+ />
+ </FormItemLayout>
+ )}
+ </DiscardChangesConfirmationDialog>
</>
)
}
diff --git a/apps/studio/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog.tsx b/apps/studio/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog.tsx
index 8944bb8aa47..75093e91840 100644
--- a/apps/studio/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog.tsx
+++ b/apps/studio/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog.tsx
@@ -20,6 +20,8 @@ export interface DiscardChangesConfirmationDialogProps extends ConfirmOnCloseMod
confirmLabel?: ReactNode
cancelLabel?: ReactNode
size?: React.ComponentProps<typeof AlertDialogContent>['size']
+ /** Extra content rendered between the description and the footer, e.g. an opt-out checkbox. */
+ children?: ReactNode
}
export const DiscardChangesConfirmationDialog = ({
@@ -31,6 +33,7 @@ export const DiscardChangesConfirmationDialog = ({
confirmLabel = 'Discard changes',
cancelLabel = 'Keep editing',
size = 'tiny',
+ children,
}: DiscardChangesConfirmationDialogProps) => {
const isConfirmingRef = useRef(false)
@@ -65,7 +68,12 @@ export const DiscardChangesConfirmationDialog = ({
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
{description !== undefined && description !== null && (
- <AlertDialogDescription>{description}</AlertDialogDescription>
+ <AlertDialogDescription asChild>
+ <div>
+ {description}
+ {children && <div className="mt-4">{children}</div>}
+ </div>
+ </AlertDialogDescription>
)}
</AlertDialogHeader>
<AlertDialogFooter>
diff --git a/apps/studio/state/sql-editor/sql-editor-save-coordinator.test.tsx b/apps/studio/state/sql-editor/sql-editor-save-coordinator.test.tsx
new file mode 100644
index 00000000000..e82b7c19f38
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-save-coordinator.test.tsx
@@ -0,0 +1,79 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, render, waitFor } from '@testing-library/react'
+import { LOCAL_STORAGE_KEYS } from 'common'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { SqlEditorSaveCoordinatorProvider } from './sql-editor-save-coordinator'
+import { sqlEditorState } from './sql-editor-state'
+import type { SnippetWithContent } from '@/data/content/sql-folders-query'
+import { createTabsState, TabsStateContext } from '@/state/tabs'
+
+vi.mock('@/components/interfaces/App/FeaturePreview/FeaturePreviewContext', () => ({
+ useIsSqlEditorManualSaveEnabled: () => true,
+}))
+
+const SNIPPET_ID = 'snippet-a'
+
+const renderCoordinator = () => {
+ const tabsStore = createTabsState('default')
+ tabsStore.addTab({
+ id: `sql-${SNIPPET_ID}`,
+ type: 'sql',
+ label: 'Snippet A',
+ isPreview: false,
+ metadata: { sqlId: SNIPPET_ID },
+ })
+
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <TabsStateContext.Provider value={tabsStore}>
+ <SqlEditorSaveCoordinatorProvider>{null}</SqlEditorSaveCoordinatorProvider>
+ </TabsStateContext.Provider>
+ </QueryClientProvider>
+ )
+
+ return tabsStore
+}
+
+describe('SqlEditorSaveCoordinatorProvider close confirmation', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ sqlEditorState.snippets[SNIPPET_ID] = {
+ projectRef: 'default',
+ snippet: { id: SNIPPET_ID, status: 'unsaved' } as SnippetWithContent,
+ } as (typeof sqlEditorState.snippets)[string]
+ })
+
+ it('asks to confirm closing a snippet with unsaved edits by default', async () => {
+ const tabsStore = renderCoordinator()
+
+ await waitFor(() =>
+ expect(tabsStore.getCloseConfirmation([`sql-${SNIPPET_ID}`])).toMatchObject({
+ title: 'Unsaved changes',
+ })
+ )
+ })
+
+ it('closes without asking once the user has opted out', async () => {
+ localStorage.setItem(LOCAL_STORAGE_KEYS.SQL_EDITOR_CONFIRM_UNSAVED_CHANGES, 'false')
+ const tabsStore = renderCoordinator()
+
+ // Passes only once the stored value loads: the default is to confirm.
+ await waitFor(() => expect(tabsStore.getCloseConfirmation([`sql-${SNIPPET_ID}`])).toBeNull())
+ })
+
+ it('turns the confirmation off when the opt-out is chosen', async () => {
+ const tabsStore = renderCoordinator()
+
+ await waitFor(() =>
+ expect(tabsStore.getCloseConfirmation([`sql-${SNIPPET_ID}`])?.optOut).toBeDefined()
+ )
+
+ act(() => tabsStore.getCloseConfirmation([`sql-${SNIPPET_ID}`])?.optOut?.onOptOut())
+
+ expect(localStorage.getItem(LOCAL_STORAGE_KEYS.SQL_EDITOR_CONFIRM_UNSAVED_CHANGES)).toBe(
+ 'false'
+ )
+ await waitFor(() => expect(tabsStore.getCloseConfirmation([`sql-${SNIPPET_ID}`])).toBeNull())
+ })
+})
diff --git a/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx b/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx
index 7a271da346d..279142c1422 100644
--- a/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx
+++ b/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx
@@ -1,4 +1,5 @@
import { useQueryClient } from '@tanstack/react-query'
+import { LOCAL_STORAGE_KEYS } from 'common'
import {
createContext,
useContext,
@@ -22,6 +23,7 @@ import { upsertContent } from '@/data/content/content-upsert-mutation'
import { contentKeys } from '@/data/content/keys'
import { createSQLSnippetFolder } from '@/data/content/sql-folder-create-mutation'
import { updateSQLSnippetFolder } from '@/data/content/sql-folder-update-mutation'
+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { TabsStateContext, type Tab } from '@/state/tabs'
type SaveCoordinator = Pick<SaveScheduler, 'requestSave'> & {
@@ -48,6 +50,16 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren
saveModeRef.current = isManualSaveEnabled ? 'manual' : 'auto'
}, [isManualSaveEnabled])
+ // Read from the tab handler below, which runs outside React's render cycle.
+ const [confirmUnsavedChanges, setConfirmUnsavedChanges] = useLocalStorageQuery(
+ LOCAL_STORAGE_KEYS.SQL_EDITOR_CONFIRM_UNSAVED_CHANGES,
+ true
+ )
+ const confirmUnsavedChangesRef = useRef(confirmUnsavedChanges)
+ useEffect(() => {
+ confirmUnsavedChangesRef.current = confirmUnsavedChanges
+ }, [confirmUnsavedChanges])
+
const coordinator = useMemo(() => {
const mechanism = createSaveMechanism({
state: sqlEditorState,
@@ -98,8 +110,9 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren
// snippet's store content or cache — nulling a still-mounted editor's content
// crashes Monaco on dispose, and a snippet left with `content: undefined`
// silently drops the next edit (breaking autosave). Only when there are edits
- // to discard do we confirm first, then clear the local content and evict the
- // cached server copy so the snippet re-fetches clean when reopened.
+ // to discard do we confirm first (unless the user turned the prompt off), then
+ // clear the local content and evict the cached server copy so the snippet
+ // re-fetches clean when reopened.
const tabsStore = useContext(TabsStateContext)
useEffect(() => {
// A snippet has unsaved edits worth discarding only in manual mode.
@@ -118,6 +131,8 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren
queryClient.removeQueries({ queryKey: contentKeys.resource(projectRef, snippetId) })
},
confirmClose: (tabs) => {
+ // The user opted out of the prompt; closing still discards the edits.
+ if (!confirmUnsavedChangesRef.current) return null
const dirtyCount = tabs.filter(snippetHasUnsavedEdits).length
if (dirtyCount === 0) return null
return {
@@ -126,10 +141,14 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren
dirtyCount === 1
? 'You have unsaved changes in this SQL snippet. Closing it will discard them.'
: `You have unsaved changes in ${dirtyCount} SQL snippets. Closing them will discard those changes.`,
+ optOut: {
+ label: "Don't ask again",
+ onOptOut: () => setConfirmUnsavedChanges(false),
+ },
}
},
})
- }, [tabsStore, queryClient])
+ }, [tabsStore, queryClient, setConfirmUnsavedChanges])
// Warn before the tab is closed/reloaded while any snippet still has unsaved
// work (a failed save, a save in flight, or a never-saved snippet). In-app
diff --git a/apps/studio/state/tabs.tsx b/apps/studio/state/tabs.tsx
index bc1a2cbfcb3..c118bfe1f25 100644
--- a/apps/studio/state/tabs.tsx
+++ b/apps/studio/state/tabs.tsx
@@ -90,6 +90,11 @@ export interface Tab {
export interface TabCloseConfirmation {
title: string
description: string
+ /**
+ * Offers a "don't ask again" checkbox. `onOptOut` runs when the user ticks it
+ * and confirms the close.
+ */
+ optOut?: { label: string; onOptOut: () => void }
}
/**
diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.ts
index cfcfa5eef85..0a03db84562 100644
--- a/packages/common/constants/local-storage.ts
+++ b/packages/common/constants/local-storage.ts
@@ -56,6 +56,7 @@ export const LOCAL_STORAGE_KEYS = {
SQL_EDITOR_SECTION_STATE: (ref: string) => `sql-editor-section-state-${ref}`,
SQL_EDITOR_SORT: (ref: string) => `sql-editor-sort-${ref}`,
SQL_EDITOR_MANUAL_SAVE_NOTICE_DISMISSED: 'sql-editor-manual-save-notice-dismissed',
+ SQL_EDITOR_CONFIRM_UNSAVED_CHANGES: 'sql-editor-confirm-unsaved-changes',
EXPLORER_QUERY_DRAFTS: (ref: string) => `explorer-query-drafts-${ref}`,
NOTEBOOK_DRAFTS: (ref: string) => `notebook-drafts-${ref}`,