The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(studio): confirm before discarding dirty replication destination forms (#48522)
Danny White7a77760a1022
diff --git a/.claude/skills/react-hook-form/SKILL.md b/.claude/skills/react-hook-form/SKILL.mdindex 29571cb24c7..c08c5037a2b 100644--- a/.claude/skills/react-hook-form/SKILL.md+++ b/.claude/skills/react-hook-form/SKILL.md@@ -235,6 +235,12 @@ schema, `onChange`, rendering, and the submit mapping.- Gate Save on `isDirty`; show Cancel only when dirty. In the owner, destructurefrom `form.formState`; anywhere else, `useFormState({ control })`.+- When the form lives in a Sheet or Dialog, also wire dirty dismissal:+ `useConfirmOnClose` + `DiscardChangesConfirmationDialog`. Route Cancel,+ Escape, and backdrop through the guard; call the raw `onClose` on successful+ submit so you do not prompt after save. Details:+ `apps/design-system/content/docs/ui-patterns/modality.mdx` (Dirty form+ dismissal) and the studio-ui-patterns skill Sheets section.- To show _which_ fields changed (review/summary dialogs), read `dirtyFields`from the same subscription instead of hand-comparing`defaultValues.x !== watchedX`. RHF already does that comparison correctly;diff --git a/.claude/skills/studio-ui-patterns/SKILL.md b/.claude/skills/studio-ui-patterns/SKILL.mdindex cc875ec5710..3f8740ec504 100644--- a/.claude/skills/studio-ui-patterns/SKILL.md+++ b/.claude/skills/studio-ui-patterns/SKILL.md@@ -125,6 +125,10 @@ Forms in sheets:- `layout="horizontal"` for wider sheets- `layout="vertical"` for narrow sheets (`size="sm"` or below)+- When the sheet contains a form, wire dirty dismissal with `useConfirmOnClose` ++ `DiscardChangesConfirmationDialog` (Cancel, Escape, and backdrop). Source of+ truth: `apps/design-system/content/docs/ui-patterns/modality.mdx` (Dirty form+ dismissal). Also see the react-hook-form skill for `isDirty` destructuring.## Copydiff --git a/apps/design-system/content/docs/ui-patterns/forms.mdx b/apps/design-system/content/docs/ui-patterns/forms.mdxindex add92626642..5c0560d2a27 100644--- a/apps/design-system/content/docs/ui-patterns/forms.mdx+++ b/apps/design-system/content/docs/ui-patterns/forms.mdx@@ -55,7 +55,7 @@ Build a custom row when the cells are mixed controls, such as an input paired wi4. **Use Cards for grouping**: Wrap form sections in `Card` components with `CardContent` and `CardFooter` for actions.-5. **Handle dirty state**: Show cancel buttons and disable save buttons based on `form.formState.isDirty`. Make sure you destructure `isDirty` from `form.formState` (see https://react-hook-form.com/docs/useform/formstate)+5. **Handle dirty state**: Show cancel buttons and disable save buttons based on `form.formState.isDirty`. Make sure you destructure `isDirty` from `form.formState` (see https://react-hook-form.com/docs/useform/formstate). When the form is in a dialog or sheet, also follow [Dirty form dismissal](./modality#dirty-form-dismissal) so Cancel, Escape, and backdrop ask before discarding unsaved changes.6. **Error handling**: Match feedback to its scope. Use `FormMessage` or `FieldError` for field validation. Show submission failures inline near the form actions when the user needs to retry or change something. Reserve toasts for non-blocking feedback or completed operations whose originating surface is no longer visible.diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.tsxindex 9e5ca2799dd..57991eda2e6 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.tsx@@ -20,10 +20,12 @@ import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { MultiSelector } from 'ui-patterns/multi-select'import { z } from 'zod'+import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { useCreatePublicationMutation } from '@/data/replication/publication-create-mutation'import { useReplicationSourceId } from '@/data/replication/sources-query'import { useReplicationTablesQuery } from '@/data/replication/tables-query'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'interface NewPublicationPanelProps {visible: boolean@@ -37,21 +39,12 @@ export const NewPublicationPanel = ({ visible, onClose }: NewPublicationPanelProconst { data: tables } = useReplicationTablesQuery({ projectRef, sourceId }, { enabled: visible })- const { mutate: createPublication, isPending: creatingPublication } =- useCreatePublicationMutation({- onSuccess: (_, vars) => {- toast.success('Successfully created publication')- form.reset(defaultValues)- onClose(vars.name)- },- })-const formId = 'publication-editor'const FormSchema = z.object({name: z.string().min(1, 'Name is required'),tables: z.array(z.string()).min(1, 'At least one table is required'),})- const defaultValues = {+ const defaultValues: z.infer<typeof FormSchema> = {name: '',tables: [],}@@ -62,6 +55,28 @@ export const NewPublicationPanel = ({ visible, onClose }: NewPublicationPanelProdefaultValues,})+ // Always destructure formState values otherwise they won't be updated+ // See https://react-hook-form.com/docs/useform/formstate+ const { isDirty } = form.formState++ const closePanel = (newPublication?: string) => {+ form.reset(defaultValues)+ onClose(newPublication)+ }++ const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({+ checkIsDirty: () => isDirty,+ onClose: () => closePanel(),+ })++ const { mutate: createPublication, isPending: creatingPublication } =+ useCreatePublicationMutation({+ onSuccess: (_, vars) => {+ toast.success('Successfully created publication')+ closePanel(vars.name)+ },+ })+const onSubmit = async (data: z.infer<typeof FormSchema>) => {if (!projectRef) return console.error('Project ref is required')if (!project) return console.error('Project is required')@@ -82,80 +97,83 @@ export const NewPublicationPanel = ({ visible, onClose }: NewPublicationPanelPro}return (- <Sheet open={visible} onOpenChange={() => onClose()}>- <SheetContent size="default">- <div className="flex flex-col h-full">- <SheetHeader>- <SheetTitle>Create a new publication</SheetTitle>- <SheetDescription>Choose which tables to replicate to destinations.</SheetDescription>- </SheetHeader>- <SheetSection className="grow overflow-auto">- <Form {...form}>- <form- id={formId}- onSubmit={form.handleSubmit(onSubmit)}- className="flex flex-col gap-y-4"- >- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItemLayout label="Name" layout="vertical">- <FormControl>- <Input {...field} placeholder="Name" />- </FormControl>- </FormItemLayout>- )}- />- <FormField- control={form.control}- name="tables"- render={({ field }) => (- <FormItemLayout- label="Tables"- description="Select at least one table to include in the publication."- >- <FormControl>- <MultiSelector- values={field.value}- onValuesChange={field.onChange}- disabled={creatingPublication}- >- <MultiSelector.Trigger- badgeLimit="wrap"- label="Select tables..."- mode="inline-combobox"- />- <MultiSelector.Content>- <MultiSelector.List>- {tables?.map((table) => (- <MultiSelector.Item- key={`${table.schema}.${table.name}`}- value={`${table.schema}.${table.name}`}- >- {`${table.schema}.${table.name}`}- </MultiSelector.Item>- ))}- </MultiSelector.List>- </MultiSelector.Content>- </MultiSelector>- </FormControl>- </FormItemLayout>- )}- />- </form>- </Form>- </SheetSection>- <SheetFooter>- <Button variant="default" disabled={creatingPublication} onClick={() => onClose()}>- Cancel- </Button>- <Button variant="primary" loading={creatingPublication} form={formId} type="submit">- Create publication- </Button>- </SheetFooter>- </div>- </SheetContent>- </Sheet>+ <>+ <Sheet open={visible} onOpenChange={handleOpenChange}>+ <SheetContent size="default">+ <div className="flex flex-col h-full">+ <SheetHeader>+ <SheetTitle>Create a new publication</SheetTitle>+ <SheetDescription>Choose which tables to replicate to destinations.</SheetDescription>+ </SheetHeader>+ <SheetSection className="grow overflow-auto">+ <Form {...form}>+ <form+ id={formId}+ onSubmit={form.handleSubmit(onSubmit)}+ className="flex flex-col gap-y-4"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItemLayout label="Name" layout="vertical">+ <FormControl>+ <Input {...field} placeholder="Name" />+ </FormControl>+ </FormItemLayout>+ )}+ />+ <FormField+ control={form.control}+ name="tables"+ render={({ field }) => (+ <FormItemLayout+ label="Tables"+ description="Select at least one table to include in the publication."+ >+ <FormControl>+ <MultiSelector+ values={field.value}+ onValuesChange={field.onChange}+ disabled={creatingPublication}+ >+ <MultiSelector.Trigger+ badgeLimit="wrap"+ label="Select tables..."+ mode="inline-combobox"+ />+ <MultiSelector.Content>+ <MultiSelector.List>+ {tables?.map((table) => (+ <MultiSelector.Item+ key={`${table.schema}.${table.name}`}+ value={`${table.schema}.${table.name}`}+ >+ {`${table.schema}.${table.name}`}+ </MultiSelector.Item>+ ))}+ </MultiSelector.List>+ </MultiSelector.Content>+ </MultiSelector>+ </FormControl>+ </FormItemLayout>+ )}+ />+ </form>+ </Form>+ </SheetSection>+ <SheetFooter>+ <Button variant="default" disabled={creatingPublication} onClick={confirmOnClose}>+ Cancel+ </Button>+ <Button variant="primary" loading={creatingPublication} form={formId} type="submit">+ Create publication+ </Button>+ </SheetFooter>+ </div>+ </SheetContent>+ </Sheet>+ <DiscardChangesConfirmationDialog {...modalProps} />+ </>)}diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsxindex a88710f4b53..69b6b7b1e8f 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx@@ -3,7 +3,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { AnimatePresence, motion } from 'framer-motion'import { Loader2 } from 'lucide-react'-import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'+import { RefObject, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'import { useForm, useWatch } from 'react-hook-form'import { AWS_REGIONS } from 'shared-data'import { toast } from 'sonner'@@ -83,7 +83,9 @@ interface DestinationFormProps {visible: booleanexistingDestination?: ExistingDestinationtypeSelection?: ReactNode+ checkIsDirtyRef?: RefObject<() => boolean>onClose: () => void+ onCancel?: () => void}export const DestinationForm = ({@@ -91,7 +93,9 @@ export const DestinationForm = ({visible,existingDestination,typeSelection,+ checkIsDirtyRef,onClose,+ onCancel = onClose,}: DestinationFormProps) => {const { ref: projectRef } = useParams()@@ -261,6 +265,10 @@ export const DestinationForm = ({defaultValues,})+ // Always destructure formState values otherwise they won't be updated+ // See https://react-hook-form.com/docs/useform/formstate+ const { isDirty } = form.formState+const publicationName = useWatch({ control: form.control, name: 'publicationName' })const publicationNames = useMemo(() => publications?.map((pub) => pub.name) ?? [], [publications])@@ -409,11 +417,22 @@ export const DestinationForm = ({}useEffect(() => {- if (visible && !form.formState.isDirty) {+ if (!checkIsDirtyRef) return++ checkIsDirtyRef.current = () => isDirty+ return () => {+ checkIsDirtyRef.current = () => false+ }+ }, [checkIsDirtyRef, isDirty])++ useEffect(() => {+ // Reset when closed (including after discard) so reopening does not restore+ // discarded values, and when open but pristine so async defaults can apply.+ if (!visible || !isDirty) {form.reset(defaultValues)resetValidation()}- }, [visible, defaultValues, form, resetValidation])+ }, [visible, defaultValues, form, isDirty, resetValidation])useEffect(() => {if (visible && projectRef && sourceId) {@@ -567,7 +586,7 @@ export const DestinationForm = ({)}</AnimatePresence><div className="flex items-center gap-x-2">- <Button disabled={isSaving} variant="default" onClick={onClose}>+ <Button disabled={isSaving} variant="default" onClick={onCancel}>Cancel</Button><Button disabled={isSubmitDisabled} loading={isSaving} form={formId} type="submit">diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsxindex d7f6f9cdcd7..dcc00c7a296 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx@@ -2,7 +2,7 @@ import { useParams } from 'common'import { ArrowUpRight } from 'lucide-react'import Link from 'next/link'import { parseAsInteger, parseAsStringEnum, useQueryState } from 'nuqs'-import { useEffect } from 'react'+import { useEffect, useRef } from 'react'import { toast } from 'sonner'import {Button,@@ -25,9 +25,11 @@ import { DestinationForm } from './DestinationForm'import { DestinationType } from './DestinationPanel.types'import { DestinationTypeSelection } from './DestinationTypeSelection'import { ReadReplicaForm } from './ReadReplicaForm'+import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { DocsButton } from '@/components/ui/DocsButton'import { useReplicationDestinationsQuery } from '@/data/replication/destinations-query'import { checkLocalETLNotSetUp } from '@/data/replication/utils'+import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'import { DOCS_URL } from '@/lib/constants'interface DestinationPanelProps {@@ -88,11 +90,19 @@ export const DestinationPanel = ({ onSuccessCreateReadReplica }: DestinationPane}: undefined+ const checkIsDirtyRef = useRef<() => boolean>(() => false)+const onClose = () => {+ checkIsDirtyRef.current = () => falsesetDestinationType(null)setEdit(null)}+ const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({+ checkIsDirty: () => checkIsDirtyRef.current(),+ onClose,+ })+const docsUrl =destinationType === 'BigQuery'? `${DOCS_URL}/guides/database/replication/bigquery#configure-bigquery-as-a-destination`@@ -129,12 +139,7 @@ export const DestinationPanel = ({ onSuccessCreateReadReplica }: DestinationPanereturn (<>- <Sheet- open={visible}- onOpenChange={(open) => {- if (!open) onClose()- }}- >+ <Sheet open={visible} onOpenChange={handleOpenChange}><SheetContent size="lg" showClose={false} className="max-w-3xl"><div className="flex flex-col h-full min-h-0" tabIndex={-1}><SheetHeader className="flex items-center justify-between">@@ -155,7 +160,9 @@ export const DestinationPanel = ({ onSuccessCreateReadReplica }: DestinationPane{destinationType === 'Read Replica' ? (<ReadReplicaFormtypeSelection={typeSelection}+ checkIsDirtyRef={checkIsDirtyRef}onClose={onClose}+ onCancel={confirmOnClose}onSuccess={() => onSuccessCreateReadReplica?.()}/>) : !enablePgReplicate ? (@@ -203,12 +210,15 @@ export const DestinationPanel = ({ onSuccessCreateReadReplica }: DestinationPaneselectedType={destinationType ?? 'Read Replica'}existingDestination={existingDestination}typeSelection={pipelinesTypeSelection}+ checkIsDirtyRef={checkIsDirtyRef}onClose={onClose}+ onCancel={confirmOnClose}/>)}</div></SheetContent></Sheet>+ <DiscardChangesConfirmationDialog {...modalProps} /></>)}diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/ReadReplicaForm/index.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/ReadReplicaForm/index.tsxindex 7e39afc1f00..0d43130e4ce 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/ReadReplicaForm/index.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/ReadReplicaForm/index.tsx@@ -1,5 +1,5 @@import { useParams } from 'common'-import { useState, type ReactNode } from 'react'+import { RefObject, useEffect, useState, type ReactNode } from 'react'import { AWS_REGIONS, AWS_REGIONS_KEYS } from 'shared-data'import { toast } from 'sonner'import {@@ -25,11 +25,19 @@ import { AWS_REGIONS_DEFAULT, BASE_PATH } from '@/lib/constants'interface ReadReplicaFormProps {typeSelection?: ReactNode+ checkIsDirtyRef?: RefObject<() => boolean>onSuccess: () => voidonClose: () => void+ onCancel?: () => void}-export const ReadReplicaForm = ({ typeSelection, onSuccess, onClose }: ReadReplicaFormProps) => {+export const ReadReplicaForm = ({+ typeSelection,+ checkIsDirtyRef,+ onSuccess,+ onClose,+ onCancel = onClose,+}: ReadReplicaFormProps) => {const { ref: projectRef } = useParams()const { data } = useReadReplicasQuery({ projectRef })@@ -39,6 +47,16 @@ export const ReadReplicaForm = ({ typeSelection, onSuccess, onClose }: ReadRepliconst { can: canDeployReplica } = useCheckEligibilityDeployReplica()const [selectedRegion, setSelectedRegion] = useState<string>(defaultRegion)+ const isDirty = selectedRegion !== defaultRegion++ useEffect(() => {+ if (!checkIsDirtyRef) return++ checkIsDirtyRef.current = () => isDirty+ return () => {+ checkIsDirtyRef.current = () => false+ }+ }, [checkIsDirtyRef, isDirty])const { mutate: setUpReplica, isPending: isSettingUp } = useReadReplicaSetUpMutation({onSuccess: () => {@@ -118,7 +136,7 @@ export const ReadReplicaForm = ({ typeSelection, onSuccess, onClose }: ReadRepli</div><div className="flex items-center gap-x-2">- <Button disabled={isSettingUp} variant="default" onClick={onClose}>+ <Button disabled={isSettingUp} variant="default" onClick={onCancel}>Cancel</Button><Button disabled={!canDeployReplica} loading={isSettingUp} onClick={onSubmit}>