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 async handling to AlertDialog actions (#45960)

Danny White331278bfe4c8
diff --git a/apps/design-system/__registry__/index.tsx b/apps/design-system/__registry__/index.tsx
index 2e2cf76ea4b..772b0471f45 100644
--- a/apps/design-system/__registry__/index.tsx
+++ b/apps/design-system/__registry__/index.tsx
@@ -247,6 +247,28 @@ export const Index: Record<string, any> = {
subcategory: "undefined",
chunks: []
},
+ "alert-dialog-async": {
+ name: "alert-dialog-async",
+ type: "components:example",
+ registryDependencies: ["alert-dialog","button"],
+ component: React.lazy(() => import("@/registry/default/example/alert-dialog-async")),
+ source: "",
+ files: ["registry/default/example/alert-dialog-async.tsx"],
+ category: "undefined",
+ subcategory: "undefined",
+ chunks: []
+ },
+ "alert-dialog-async-error": {
+ name: "alert-dialog-async-error",
+ type: "components:example",
+ registryDependencies: ["alert-dialog","button","admonition"],
+ component: React.lazy(() => import("@/registry/default/example/alert-dialog-async-error")),
+ source: "",
+ files: ["registry/default/example/alert-dialog-async-error.tsx"],
+ category: "undefined",
+ subcategory: "undefined",
+ chunks: []
+ },
"alert-dialog-destructive": {
name: "alert-dialog-destructive",
type: "components:example",
diff --git a/apps/design-system/content/docs/components/alert-dialog.mdx b/apps/design-system/content/docs/components/alert-dialog.mdx
index 7c35e586b3c..fe0508be5a4 100644
--- a/apps/design-system/content/docs/components/alert-dialog.mdx
+++ b/apps/design-system/content/docs/components/alert-dialog.mdx
@@ -60,6 +60,7 @@ npm install @radix-ui/react-alert-dialog
import {
AlertDialog,
AlertDialogAction,
+ AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
@@ -95,18 +96,38 @@ Unlike a generic [Dialog](../components/dialog), an Alert Dialog cannot be dismi
This enforced decision helps prevent accidental dismissal of critical warnings or destructive actions.
+Supabase’s Alert Dialog extends the Radix/Shadcn version with async action handling. When an
+`AlertDialogAction` returns a Promise, the dialog keeps focus trapped, blocks dismissal, and shows
+loading until the Promise resolves. Rejected Promises keep the dialog open so consumers can render
+inline error feedback.
+
## Guidelines
- **Keep content concise:** AlertDialogDescription renders as a single paragraph and must not contain block-level elements such as lists, multiple paragraphs, or complex layouts.
- **Use for critical decisions only:** Reserve Alert Dialog for destructive or irreversible actions, or for warnings that require explicit acknowledgement.
- **Use for dirty-form discard confirmation:** A short discard-confirmation step after a dirty form dismissal attempt (backdrop, Escape, or `Cancel`) is a valid Alert Dialog pattern. In Studio, prefer `DiscardChangesConfirmationDialog` for this flow.
- **Always provide a cancel action:** Include AlertDialogCancel so users can safely back out, in addition to supporting the Escape key.
+- **Use AlertDialogBody for inline feedback:** If async actions can fail, render inline feedback such as an Admonition inside AlertDialogBody so spacing stays consistent.
- **Avoid rich content:** If the dialog requires detailed explanations, callouts, or form inputs, use [Confirmation Modal](../fragments/confirmation-modal) or [Dialog](../components/dialog) instead.
See [Modality](../ui-patterns/modality) for guidance on choosing the appropriate dialog pattern.
## Examples
+### Async action
+
+When an action returns a Promise, Alert Dialog keeps the dialog open, shows a loading state on the
+action button, and disables dismissal until the Promise resolves.
+
+<ComponentPreview name="alert-dialog-async" peekCode wide />
+
+### Async action error
+
+Catch errors to show inline feedback, then rethrow so Alert Dialog can reset the loading state and
+keep the dialog open.
+
+<ComponentPreview name="alert-dialog-async-error" peekCode wide />
+
### Close only
<ComponentPreview name="alert-dialog-close-only" />
diff --git a/apps/design-system/registry/default/example/alert-dialog-async-error.tsx b/apps/design-system/registry/default/example/alert-dialog-async-error.tsx
new file mode 100644
index 00000000000..21cd9c9d7c1
--- /dev/null
+++ b/apps/design-system/registry/default/example/alert-dialog-async-error.tsx
@@ -0,0 +1,63 @@
+import { useState } from 'react'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogBody,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+ Button,
+} from 'ui'
+import { Admonition } from 'ui-patterns/admonition'
+
+const resetTemplate = async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1200))
+ throw new Error('Template reset failed')
+}
+
+export default function AlertDialogAsyncError() {
+ const [error, setError] = useState<string | null>(null)
+
+ const handleResetTemplate = async () => {
+ setError(null)
+
+ try {
+ await resetTemplate()
+ } catch (error) {
+ setError('Check the template configuration and try again.')
+ throw error
+ }
+ }
+
+ return (
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button type="outline">Show Alert Dialog</Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Reset email template?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will replace the current email template with the default version. Any unsaved
+ changes will be lost.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {error && (
+ <AlertDialogBody>
+ <Admonition type="destructive" title="Failed to reset template" description={error} />
+ </AlertDialogBody>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="warning" onClick={handleResetTemplate}>
+ Reset template
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/apps/design-system/registry/default/example/alert-dialog-async.tsx b/apps/design-system/registry/default/example/alert-dialog-async.tsx
new file mode 100644
index 00000000000..a34c37fb463
--- /dev/null
+++ b/apps/design-system/registry/default/example/alert-dialog-async.tsx
@@ -0,0 +1,40 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+ Button,
+} from 'ui'
+
+const createApiKeys = async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1200))
+}
+
+export default function AlertDialogAsync() {
+ return (
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button type="outline">Show Alert Dialog</Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Create new API keys</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will create a default publishable key and a default secret key both named{' '}
+ <code className="text-code-inline">default</code>. These keys are required to connect
+ your application to your Supabase project.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={createApiKeys}>Create keys</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/apps/design-system/registry/examples.ts b/apps/design-system/registry/examples.ts
index 2798b46c8c2..aba1bc622a6 100644
--- a/apps/design-system/registry/examples.ts
+++ b/apps/design-system/registry/examples.ts
@@ -79,6 +79,18 @@ export const examples: Registry = [
registryDependencies: ['alert-dialog', 'button'],
files: ['example/alert-dialog-close-only.tsx'],
},
+ {
+ name: 'alert-dialog-async',
+ type: 'components:example',
+ registryDependencies: ['alert-dialog', 'button'],
+ files: ['example/alert-dialog-async.tsx'],
+ },
+ {
+ name: 'alert-dialog-async-error',
+ type: 'components:example',
+ registryDependencies: ['alert-dialog', 'button', 'admonition'],
+ files: ['example/alert-dialog-async-error.tsx'],
+ },
{
name: 'alert-dialog-destructive',
type: 'components:example',
diff --git a/apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx b/apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
index 1af8b69bc29..2e4e591c63c 100644
--- a/apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
+++ b/apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
@@ -4,6 +4,7 @@ import { toast } from 'sonner'
import {
AlertDialog,
AlertDialogAction,
+ AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
@@ -12,34 +13,47 @@ import {
AlertDialogTitle,
Button,
} from 'ui'
+import { Admonition } from 'ui-patterns/admonition'
import { useAPIKeyCreateMutation } from '@/data/api-keys/api-key-create-mutation'
export const CreateNewAPIKeysButton = () => {
const { ref: projectRef } = useParams()
- const [isCreatingKeys, setIsCreatingKeys] = useState(false)
const [createKeysDialogOpen, setCreateKeysDialogOpen] = useState(false)
+ const [error, setError] = useState<string | null>(null)
- const { mutateAsync: createAPIKey } = useAPIKeyCreateMutation()
+ const { mutateAsync: createAPIKey } = useAPIKeyCreateMutation({ onError: () => {} })
const handleCreateNewApiKeys = async () => {
if (!projectRef) return
- setIsCreatingKeys(true)
try {
+ setError(null)
+
// Create publishable key
- await createAPIKey({ projectRef, type: 'publishable', name: 'default' })
+ try {
+ await createAPIKey({ projectRef, type: 'publishable', name: 'default' })
+ } catch (error: any) {
+ setError(`Failed to create the default publishable key: ${error.message}`)
+ throw error
+ }
// Create secret key
- await createAPIKey({ projectRef, type: 'secret', name: 'default' })
+ try {
+ await createAPIKey({ projectRef, type: 'secret', name: 'default' })
+ } catch (error: any) {
+ setError(
+ `The default publishable key was created, but the default secret key failed: ${error.message}`
+ )
+ throw error
+ }
setCreateKeysDialogOpen(false)
toast.success('Successfully created a new set of API keys!')
} catch (error) {
console.error('Failed to create API keys:', error)
- } finally {
- setIsCreatingKeys(false)
+ throw error
}
}
@@ -55,11 +69,14 @@ export const CreateNewAPIKeysButton = () => {
to connect your application to your Supabase project.
</AlertDialogDescription>
</AlertDialogHeader>
+ {error && (
+ <AlertDialogBody>
+ <Admonition type="destructive" title="Unable to create API keys" description={error} />
+ </AlertDialogBody>
+ )}
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction onClick={handleCreateNewApiKeys} disabled={isCreatingKeys}>
- {isCreatingKeys ? 'Creating...' : 'Create keys'}
- </AlertDialogAction>
+ <AlertDialogAction onClick={handleCreateNewApiKeys}>Create keys</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
diff --git a/apps/studio/components/interfaces/Database/Replication/DisableExternalReplicationDialog.tsx b/apps/studio/components/interfaces/Database/Replication/DisableExternalReplicationDialog.tsx
index 18586c89ce3..90d235cf975 100644
--- a/apps/studio/components/interfaces/Database/Replication/DisableExternalReplicationDialog.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/DisableExternalReplicationDialog.tsx
@@ -1,16 +1,18 @@
import { useParams } from 'common'
+import { useState } from 'react'
import { toast } from 'sonner'
import {
AlertDialog,
AlertDialogAction,
+ AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
- Button,
} from 'ui'
+import { Admonition } from 'ui-patterns/admonition'
import { useDeleteReplicationTenantMutation } from '@/data/replication/delete-tenant-mutation'
@@ -24,6 +26,7 @@ export const DisableExternalReplicationDialog = ({
setOpen,
}: DisableExternalReplicationDialogProps) => {
const { ref: projectRef } = useParams()
+ const [error, setError] = useState<string | null>(null)
const { mutateAsync: deleteReplicationTenant, isPending: isSubmitting } =
useDeleteReplicationTenantMutation({
@@ -31,18 +34,26 @@ export const DisableExternalReplicationDialog = ({
toast.success('External replication has been disabled')
setOpen(false)
},
+ onError: () => {},
})
const onConfirm = async () => {
- if (!projectRef) return console.error('Project ref is required')
- await deleteReplicationTenant({ projectRef })
+ setError(null)
+
+ try {
+ if (!projectRef) throw new Error('Project ref is required')
+ await deleteReplicationTenant({ projectRef })
+ } catch (error: any) {
+ setError(error.message ?? 'An unknown error occurred')
+ throw error
+ }
}
return (
<AlertDialog open={open} onOpenChange={(open) => !isSubmitting && setOpen(open)}>
- <AlertDialogContent size="medium">
+ <AlertDialogContent size="small">
<AlertDialogHeader>
- <AlertDialogTitle>Confirm to disable external replication</AlertDialogTitle>
+ <AlertDialogTitle>Disable external replication</AlertDialogTitle>
<AlertDialogDescription className="space-y-2 text-sm">
<p>
This will remove the <code className="text-code-inline">etl</code> schema and all
@@ -52,20 +63,19 @@ export const DisableExternalReplicationDialog = ({
<p>Read replicas are not affected.</p>
</AlertDialogDescription>
</AlertDialogHeader>
+ {error && (
+ <AlertDialogBody>
+ <Admonition
+ type="destructive"
+ title="Unable to disable external replication"
+ description={error}
+ />
+ </AlertDialogBody>
+ )}
<AlertDialogFooter>
<AlertDialogCancel disabled={isSubmitting}>Cancel</AlertDialogCancel>
- <AlertDialogAction variant="danger" asChild>
- <Button
- type="danger"
- loading={isSubmitting}
- disabled={isSubmitting}
- onClick={(e) => {
- e.preventDefault()
- onConfirm()
- }}
- >
- Disable external replication
- </Button>
+ <AlertDialogAction variant="danger" loading={isSubmitting} onClick={onConfirm}>
+ Disable
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx
index 98c4dcdd41d..936e80a5ca1 100644
--- a/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx
@@ -86,12 +86,13 @@ export const EnableIndexAdvisorDialog = ({
setOpen(false)
} catch (error: any) {
toast.error(`Failed to enable Index Advisor: ${error.message}`)
+ throw error
}
}
return (
<AlertDialog open={open} onOpenChange={() => setOpen(!open)}>
- <AlertDialogContent size="medium">
+ <AlertDialogContent size="small">
<AlertDialogHeader>
<AlertDialogTitle>Enable Index Advisor</AlertDialogTitle>
<AlertDialogDescription className="flex flex-col gap-y-2">
@@ -100,21 +101,21 @@ export const EnableIndexAdvisorDialog = ({
on your actual query patterns.
</p>
<p>
- Enable this will install the <code className="text-code-inline">index_advisor</code>{' '}
- and <code className="text-code-inline">hypopg</code> Postgres extensions so Index
- Advisor can analyse queries and suggest performance-improving indexes.
+ This will install the{' '}
+ <code className="text-code-inline break-normal!">index_advisor</code> and{' '}
+ <code className="text-code-inline break-normal!">hypopg</code> Postgres extensions so
+ Index Advisor can analyse queries and suggest performance-improving indexes.
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
- onClick={(e) => {
- e.preventDefault()
- onEnableIndexAdvisor()
+ loading={isEnablingExtension}
+ onClick={() => {
track('index_advisor_enable_button_clicked', { origin: 'dialog' })
+ return onEnableIndexAdvisor()
}}
- disabled={isEnablingExtension}
>
{isEnablingExtension ? 'Enabling...' : 'Enable'}
</AlertDialogAction>
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx
index 399e60ebe04..8831e0e4144 100644
--- a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx
@@ -8,6 +8,7 @@ import { toast } from 'sonner'
import {
AlertDialog,
AlertDialogAction,
+ AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
@@ -69,7 +70,9 @@ export const JitDbAccessConfiguration = () => {
const [, setShowCreateRuleSheet] = useQueryState('jit_new', parseAsBoolean.withDefault(false))
const [ruleIdToEdit, setRuleIdToEdit] = useQueryState('jit_edit', parseAsString)
const [showEnableJitDialog, setShowEnableJitDialog] = useState(false)
+ const [enableJitError, setEnableJitError] = useState<string | null>(null)
const [selectedUserToDelete, setSelectedUserToDelete] = useState<JitUserRule | null>(null)
+ const [deleteRuleError, setDeleteRuleError] = useState<string | null>(null)
const {
data: jitDbAccessConfiguration,
@@ -104,7 +107,7 @@ export const JitDbAccessConfiguration = () => {
{ resource: { project_id: project?.id } }
)
- const { mutate: updateJitDbAccess, isPending: isUpdatingJitDbAccess } =
+ const { mutateAsync: updateJitDbAccess, isPending: isUpdatingJitDbAccess } =
useJitDbAccessUpdateMutation({
onSuccess: (_, variables) => {
const nextEnabled = variables.requestedConfig.state === 'enabled'
@@ -119,22 +122,18 @@ export const JitDbAccessConfiguration = () => {
)
}
},
- onError: (error) => {
- setEnabled(initialIsEnabled ?? false)
- toast.error(`Failed to update temporary access: ${error.message}`)
- },
+ onError: () => {},
})
- const { mutate: revokeUserAccess, isPending: isRevokingAccess } = useJitDbAccessRevokeMutation({
- onSuccess: (_, variables) => {
- toast.success('Successfully revoked user access')
- setSelectedUserToDelete(null)
- if (ruleIdToEdit === variables.userId) resetSheetState()
- },
- onError: (error) => {
- toast.error(`Failed to revoke user access: ${error.message}`)
- },
- })
+ const { mutateAsync: revokeUserAccess, isPending: isRevokingAccess } =
+ useJitDbAccessRevokeMutation({
+ onSuccess: (_, variables) => {
+ toast.success('Successfully revoked user access')
+ setSelectedUserToDelete(null)
+ if (ruleIdToEdit === variables.userId) resetSheetState()
+ },
+ onError: () => {},
+ })
const isMutating = isUpdatingJitDbAccess || isRevokingAccess
const disableRuleActions = isMutating || isLoadingDatabaseRoles || isLoadingOrganizationMembers
@@ -201,14 +200,23 @@ export const JitDbAccessConfiguration = () => {
setRuleIdToEdit(null)
}
- const submitJitToggle = (nextEnabled: boolean) => {
- if (!ref) return console.error('Project ref is required')
+ const getErrorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : 'An unknown error occurred'
+
+ const submitJitToggle = async (nextEnabled: boolean) => {
+ if (!ref) throw new Error('Project ref is required')
setEnabled(nextEnabled)
- updateJitDbAccess({
- projectRef: ref,
- requestedConfig: { state: nextEnabled ? 'enabled' : 'disabled' },
- })
+
+ try {
+ await updateJitDbAccess({
+ projectRef: ref,
+ requestedConfig: { state: nextEnabled ? 'enabled' : 'disabled' },
+ })
+ } catch (error) {
+ setEnabled(initialIsEnabled ?? false)
+ throw error
+ }
}
const handleJitToggleChange = (checked: boolean) => {
@@ -216,19 +224,30 @@ export const JitDbAccessConfiguration = () => {
if (checked && !enabled) {
if (activeRuleCount > 0) {
+ setEnableJitError(null)
return setShowEnableJitDialog(true)
}
- return submitJitToggle(true)
+ return void submitJitToggle(true).catch((error) => {
+ toast.error(`Failed to update temporary access: ${getErrorMessage(error)}`)
+ })
}
if (!checked && enabled) {
- submitJitToggle(false)
+ void submitJitToggle(false).catch((error) => {
+ toast.error(`Failed to update temporary access: ${getErrorMessage(error)}`)
+ })
}
}
- const handleConfirmEnableJit = () => {
- setShowEnableJitDialog(false)
- submitJitToggle(true)
+ const handleConfirmEnableJit = async () => {
+ setEnableJitError(null)
+
+ try {
+ await submitJitToggle(true)
+ } catch (error) {
+ setEnableJitError(getErrorMessage(error))
+ throw error
+ }
}
const openAddRuleSheet = () => {
@@ -245,13 +264,22 @@ export const JitDbAccessConfiguration = () => {
const openDeleteDialog = (user: JitUserRule) => {
if (!canUpdateJitDbAccess) return
+ setDeleteRuleError(null)
setSelectedUserToDelete(user)
}
- const handleConfirmDelete = () => {
- if (!ref) return console.error('Project ref is required')
- if (!selectedUserToDelete) return toast.error('User is required')
- revokeUserAccess({ projectRef: ref, userId: selectedUserToDelete.memberId })
+ const handleConfirmDelete = async () => {
+ setDeleteRuleError(null)
+
+ try {
+ if (!ref) throw new Error('Project ref is required')
+ if (!selectedUserToDelete) throw new Error('User is required')
+
+ await revokeUserAccess({ projectRef: ref, userId: selectedUserToDelete.memberId })
+ } catch (error) {
+ setDeleteRuleError(getErrorMessage(error))
+ throw error
+ }
}
const switchDisabled = isLoadingConfiguration || isUpdatingJitDbAccess || !canUpdateJitDbAccess
@@ -462,7 +490,11 @@ export const JitDbAccessConfiguration = () => {
<JitDbAccessDeleteDialog
user={selectedUserToDelete}
isDeleting={isRevokingAccess}
- onClose={() => setSelectedUserToDelete(null)}
+ error={deleteRuleError}
+ onClose={() => {
+ setDeleteRuleError(null)
+ setSelectedUserToDelete(null)
+ }}
onConfirm={handleConfirmDelete}
/>
@@ -480,11 +512,20 @@ export const JitDbAccessConfiguration = () => {
</div>
</AlertDialogDescription>
</AlertDialogHeader>
+ {enableJitError && (
+ <AlertDialogBody>
+ <Admonition
+ type="destructive"
+ title="Unable to enable temporary access"
+ description={enableJitError}
+ />
+ </AlertDialogBody>
+ )}
<AlertDialogFooter>
<AlertDialogCancel disabled={isUpdatingJitDbAccess}>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="warning"
- disabled={isUpdatingJitDbAccess}
+ loading={isUpdatingJitDbAccess}
onClick={handleConfirmEnableJit}
>
Enable temporary access
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx
index 92215a4175f..5a605439069 100644
--- a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx
@@ -1,27 +1,30 @@
import {
AlertDialog,
AlertDialogAction,
+ AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
- Button,
} from 'ui'
+import { Admonition } from 'ui-patterns/admonition'
import type { JitUserRule } from './JitDbAccess.types'
interface JitDbAccessDeleteDialogProps {
user: JitUserRule | null
isDeleting: boolean
+ error?: string | null
onClose: () => void
- onConfirm: () => void
+ onConfirm: () => unknown
}
export function JitDbAccessDeleteDialog({
user,
isDeleting = false,
+ error,
onClose,
onConfirm,
}: JitDbAccessDeleteDialogProps) {
@@ -29,7 +32,7 @@ export function JitDbAccessDeleteDialog({
return (
<AlertDialog open={!!user} onOpenChange={(open) => !open && !isDeleting && onClose()}>
- <AlertDialogContent size="medium">
+ <AlertDialogContent size="small">
<AlertDialogHeader>
<AlertDialogTitle>Delete temporary access rule</AlertDialogTitle>
<AlertDialogDescription asChild>
@@ -45,19 +48,19 @@ export function JitDbAccessDeleteDialog({
</div>
</AlertDialogDescription>
</AlertDialogHeader>
+ {error && (
+ <AlertDialogBody>
+ <Admonition
+ type="destructive"
+ title="Unable to delete temporary access rule"
+ description={error}
+ />
+ </AlertDialogBody>
+ )}
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
- <AlertDialogAction variant="danger" asChild>
- <Button
- loading={isDeleting}
- disabled={isDeleting}
- onClick={(e) => {
- e.preventDefault()
- onConfirm()
- }}
- >
- Delete rule
- </Button>
+ <AlertDialogAction variant="danger" loading={isDeleting} onClick={onConfirm}>
+ Delete rule
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx
index 732be4ad65d..3e8ce9cc634 100644
--- a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx
@@ -170,7 +170,7 @@ export function JitDbAccessRulesTable({
aria-label="More actions"
type="default"
size="tiny"
- className="w-7"
+ className="w-7 hit-area-2"
disabled={!canUpdate || disableActions}
/>
</DropdownMenuTrigger>
diff --git a/packages/ui/src/components/shadcn/ui/alert-dialog.test.tsx b/packages/ui/src/components/shadcn/ui/alert-dialog.test.tsx
new file mode 100644
index 00000000000..53984d4db1f
--- /dev/null
+++ b/packages/ui/src/components/shadcn/ui/alert-dialog.test.tsx
@@ -0,0 +1,169 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from './alert-dialog'
+
+const createDeferred = <T,>() => {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((promiseResolve, promiseReject) => {
+ resolve = promiseResolve
+ reject = promiseReject
+ })
+
+ return { promise, reject, resolve }
+}
+
+const TestAlertDialog = ({
+ action,
+ actionLabel = 'Continue',
+ actionLoading,
+}: {
+ action?: () => void | Promise<void>
+ actionLabel?: string
+ actionLoading?: boolean
+}) => (
+ <AlertDialog defaultOpen>
+ <AlertDialogTrigger>Open</AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Confirm action</AlertDialogTitle>
+ <AlertDialogDescription>This action needs confirmation.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction loading={actionLoading} onClick={action}>
+ {actionLabel}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+)
+
+describe('#AlertDialog', () => {
+ it('closes after a synchronous action', async () => {
+ const onAction = vi.fn()
+
+ render(<TestAlertDialog action={onAction} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ expect(onAction).toHaveBeenCalledTimes(1)
+ await waitFor(() => {
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
+ })
+
+ it('keeps the dialog open and shows loading while an async action is pending', async () => {
+ const deferred = createDeferred<void>()
+ render(<TestAlertDialog action={() => deferred.promise} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()
+ expect(document.querySelector('.animate-spin')).toBeInTheDocument()
+ })
+
+ it('closes after an async action resolves', async () => {
+ const deferred = createDeferred<void>()
+
+ render(<TestAlertDialog action={() => deferred.promise} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ await act(async () => {
+ deferred.resolve()
+ await deferred.promise
+ })
+
+ await waitFor(() => {
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
+ })
+
+ it('keeps the dialog open after an async action rejects', async () => {
+ const deferred = createDeferred<void>()
+
+ render(<TestAlertDialog action={() => deferred.promise} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+
+ await act(async () => {
+ deferred.reject(new Error('Unable to complete action'))
+ await deferred.promise.catch(() => undefined)
+ })
+
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Continue' })).not.toBeDisabled()
+ })
+
+ it('blocks cancel, Escape, and outside interaction while an async action is pending', () => {
+ const deferred = createDeferred<void>()
+
+ render(<TestAlertDialog action={() => deferred.promise} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+
+ fireEvent.keyDown(screen.getByRole('alertdialog'), { key: 'Escape' })
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+
+ fireEvent.pointerDown(document.body)
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ })
+
+ it('disables action and cancel when loading is controlled by a parent', () => {
+ render(<TestAlertDialog actionLoading />)
+
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()
+ })
+
+ it('uses the latest onOpenChange callback after a rerender', () => {
+ const firstOnOpenChange = vi.fn()
+ const secondOnOpenChange = vi.fn()
+
+ const InlineCallbackDialog = ({ label }: { label: string }) => {
+ const onOpenChange = (open: boolean) => {
+ if (label === 'first') firstOnOpenChange(label, open)
+ else secondOnOpenChange(label, open)
+ }
+
+ return (
+ <AlertDialog defaultOpen onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Confirm action</AlertDialogTitle>
+ <AlertDialogDescription>This action needs confirmation.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+ }
+
+ const { rerender } = render(<InlineCallbackDialog label="first" />)
+
+ rerender(<InlineCallbackDialog label="latest" />)
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ expect(firstOnOpenChange).not.toHaveBeenCalled()
+ expect(secondOnOpenChange).toHaveBeenCalledWith('latest', false)
+ })
+})
diff --git a/packages/ui/src/components/shadcn/ui/alert-dialog.tsx b/packages/ui/src/components/shadcn/ui/alert-dialog.tsx
index 16da36c9bff..eabbef051c5 100644
--- a/packages/ui/src/components/shadcn/ui/alert-dialog.tsx
+++ b/packages/ui/src/components/shadcn/ui/alert-dialog.tsx
@@ -1,13 +1,79 @@
'use client'
-import { AlertDialog as AlertDialogPrimitive } from 'radix-ui'
import { cva, VariantProps } from 'class-variance-authority'
+import { AlertDialog as AlertDialogPrimitive } from 'radix-ui'
import * as React from 'react'
import { cn } from '../../../lib/utils/cn'
-import { ButtonVariantProps, buttonVariants } from './../../Button'
+import { Button, ButtonVariantProps, buttonVariants } from './../../Button'
+
+type AlertDialogContextValue = {
+ loading: boolean
+ setActionLoading: (id: symbol, loading: boolean) => void
+ setOpen: (open: boolean, options?: { force?: boolean }) => void
+}
+
+const AlertDialogContext = React.createContext<AlertDialogContextValue | null>(null)
+
+const useAlertDialogContext = () => React.useContext(AlertDialogContext)
+
+type AlertDialogProps = React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Root>
+
+const AlertDialog = ({
+ children,
+ defaultOpen = false,
+ onOpenChange,
+ open: openProp,
+ ...props
+}: AlertDialogProps) => {
+ const onOpenChangeRef = React.useRef(onOpenChange)
+ const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen)
+ const [loadingActionIds, setLoadingActionIds] = React.useState<Set<symbol>>(() => new Set())
+ const loading = loadingActionIds.size > 0
+ const open = openProp ?? uncontrolledOpen
+
+ React.useEffect(() => {
+ onOpenChangeRef.current = onOpenChange
+ }, [onOpenChange])
+
+ const setActionLoading = React.useCallback((id: symbol, actionLoading: boolean) => {
+ setLoadingActionIds((currentIds) => {
+ const nextIds = new Set(currentIds)
+
+ if (actionLoading) nextIds.add(id)
+ else nextIds.delete(id)
+
+ return nextIds
+ })
+ }, [])
+
+ const setOpen = React.useCallback(
+ (nextOpen: boolean, options?: { force?: boolean }) => {
+ if (loading && !nextOpen && !options?.force) return
+
+ if (openProp === undefined) {
+ setUncontrolledOpen(nextOpen)
+ }
+
+ onOpenChangeRef.current?.(nextOpen)
+ },
+ [loading, openProp]
+ )
+
+ const contextValue = React.useMemo(
+ () => ({ loading, setActionLoading, setOpen }),
+ [loading, setActionLoading, setOpen]
+ )
-const AlertDialog = AlertDialogPrimitive.Root
+ return (
+ <AlertDialogContext.Provider value={contextValue}>
+ <AlertDialogPrimitive.Root open={open} onOpenChange={setOpen} {...props}>
+ {children}
+ </AlertDialogPrimitive.Root>
+ </AlertDialogContext.Provider>
+ )
+}
+AlertDialog.displayName = AlertDialogPrimitive.Root.displayName
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
@@ -40,10 +106,7 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContentVariants = cva(
cn(
'relative z-50 w-full max-w-screen border shadow-md dark:shadow-xs',
- 'data-[state=open]:animate-in data-[state=closed]:animate-out',
- 'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
- 'data-[state=closed]:slide-out-to-left-[0%] data-[state=closed]:slide-out-to-top-[0%]',
- 'data-[state=open]:slide-in-from-left-[0%] data-[state=open]:slide-in-from-top-[0%]',
+ 'data-open:animate-overlay-show data-closed:animate-overlay-hide',
'sm:rounded-lg md:w-full',
'bg-dash-sidebar'
),
@@ -73,19 +136,45 @@ const AlertDialogContent = React.forwardRef<
dialogOverlayProps?: React.ComponentPropsWithoutRef<typeof AlertDialogOverlay>
centered?: boolean
}
->(({ className, children, size, dialogOverlayProps, centered = true, ...props }, ref) => (
- <AlertDialogPortal>
- <AlertDialogOverlay centered={centered} {...dialogOverlayProps}>
- <AlertDialogPrimitive.Content
- ref={ref}
- className={cn(AlertDialogContentVariants({ size }), className)}
- {...props}
- >
- {children}
- </AlertDialogPrimitive.Content>
- </AlertDialogOverlay>
- </AlertDialogPortal>
-))
+>(
+ (
+ {
+ className,
+ children,
+ size,
+ dialogOverlayProps,
+ centered = true,
+ onEscapeKeyDown,
+ onFocusOutside,
+ ...props
+ },
+ ref
+ ) => {
+ const alertDialogContext = useAlertDialogContext()
+
+ return (
+ <AlertDialogPortal>
+ <AlertDialogOverlay centered={centered} {...dialogOverlayProps}>
+ <AlertDialogPrimitive.Content
+ ref={ref}
+ className={cn(AlertDialogContentVariants({ size }), className)}
+ onEscapeKeyDown={(event) => {
+ onEscapeKeyDown?.(event)
+ if (alertDialogContext?.loading) event.preventDefault()
+ }}
+ onFocusOutside={(event) => {
+ onFocusOutside?.(event)
+ if (alertDialogContext?.loading) event.preventDefault()
+ }}
+ {...props}
+ >
+ {children}
+ </AlertDialogPrimitive.Content>
+ </AlertDialogOverlay>
+ </AlertDialogPortal>
+ )
+ }
+)
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
@@ -93,10 +182,24 @@ const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDiv
)
AlertDialogHeader.displayName = 'AlertDialogHeader'
+const AlertDialogBody = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ data-slot="alert-dialog-body"
+ className={cn(
+ '[&>[role=alert]]:mb-0 [&>[role=alert]]:rounded-none [&>[role=alert]]:border-x-0',
+ className
+ )}
+ {...props}
+ />
+)
+AlertDialogBody.displayName = 'AlertDialogBody'
+
+// Full-width alerts own the visual separator above the footer.
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
+ data-slot="alert-dialog-footer"
className={cn(
- 'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 border-t py-3 px-5',
+ 'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 border-t py-3 px-5 [[data-slot=alert-dialog-body]:has(>[role=alert])+&]:border-t-0',
className
)}
{...props}
@@ -133,38 +236,139 @@ const AlertDialogDescription = React.forwardRef<
))
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName
-type AlertDialogActionProps = React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action> & {
+const isPromiseLike = (value: unknown): value is PromiseLike<unknown> => {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'then' in value &&
+ typeof value.then === 'function'
+ )
+}
+
+type AlertDialogActionProps = Omit<
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>,
+ 'onClick'
+> & {
variant?: NonNullable<ButtonVariantProps['type']>
+ loading?: boolean
+ onClick?: (event: React.MouseEvent<HTMLButtonElement>) => unknown
}
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
AlertDialogActionProps
->(({ className, variant = 'primary', type = 'button', ...props }, ref) => (
- <AlertDialogPrimitive.Action
- ref={ref}
- type={type}
- className={cn(buttonVariants({ type: variant, size: 'tiny' }), className)}
- {...props}
- />
-))
+>(
+ (
+ {
+ asChild,
+ children,
+ className,
+ disabled,
+ loading: loadingProp = false,
+ onClick,
+ variant = 'primary',
+ type = 'button',
+ ...props
+ },
+ ref
+ ) => {
+ const alertDialogContext = useAlertDialogContext()
+ const dialogLoading = alertDialogContext?.loading ?? false
+ const setActionLoading = alertDialogContext?.setActionLoading
+ const setOpen = alertDialogContext?.setOpen
+ const actionId = React.useRef(Symbol('AlertDialogAction'))
+ const [internalLoading, setInternalLoading] = React.useState(false)
+ const loading = loadingProp || internalLoading
+ const isDisabled = disabled || loading || dialogLoading
+
+ React.useEffect(() => {
+ setActionLoading?.(actionId.current, loading)
+
+ return () => {
+ setActionLoading?.(actionId.current, false)
+ }
+ }, [loading, setActionLoading])
+
+ const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
+ if (isDisabled) {
+ event.preventDefault()
+ return
+ }
+
+ const result = onClick?.(event)
+
+ if (!isPromiseLike(result)) return
+
+ event.preventDefault()
+ setInternalLoading(true)
+
+ void (async () => {
+ try {
+ await result
+ setOpen?.(false, { force: true })
+ } catch {
+ // Keep the dialog open so consumers can surface mutation errors in context.
+ } finally {
+ setInternalLoading(false)
+ }
+ })()
+ }
+
+ if (asChild) {
+ return (
+ <AlertDialogPrimitive.Action
+ ref={ref}
+ asChild
+ className={cn(buttonVariants({ type: variant, size: 'tiny' }), className)}
+ disabled={isDisabled}
+ onClick={handleClick}
+ type={type}
+ {...props}
+ >
+ {children}
+ </AlertDialogPrimitive.Action>
+ )
+ }
+
+ return (
+ <AlertDialogPrimitive.Action asChild onClick={handleClick} {...props}>
+ <Button
+ ref={ref}
+ className={className}
+ disabled={isDisabled}
+ htmlType={type}
+ loading={loading}
+ type={variant}
+ >
+ {children}
+ </Button>
+ </AlertDialogPrimitive.Action>
+ )
+ }
+)
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
->(({ className, ...props }, ref) => (
- <AlertDialogPrimitive.Cancel
- ref={ref}
- className={cn(buttonVariants({ type: 'default', size: 'tiny' }), 'mt-2 sm:mt-0', className)}
- {...props}
- />
-))
+>(({ className, disabled, ...props }, ref) => {
+ const alertDialogContext = useAlertDialogContext()
+
+ return (
+ <AlertDialogPrimitive.Cancel
+ ref={ref}
+ className={cn(buttonVariants({ type: 'default', size: 'tiny' }), 'mt-2 sm:mt-0', className)}
+ disabled={disabled || alertDialogContext?.loading}
+ {...props}
+ />
+ )
+})
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogAction,
+ AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,