Skip to content

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

fix(studio): reset rename form between same-named SQL snippets (#49275)

Charis474bf5da4a67
diff --git a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx
index 1113bd5bf07..477a9229795 100644
--- a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx
@@ -34,6 +34,8 @@ const createSnippet = (id: string, name: string): SnippetWithContent => ({
const SNIPPET_A = createSnippet('snippet-a', 'First query')
const SNIPPET_B = createSnippet('snippet-b', 'Second query')
+const UNTITLED_A = createSnippet('untitled-a', 'Untitled query')
+const UNTITLED_B = createSnippet('untitled-b', 'Untitled query')
/** The modal renders the AI title generator, which checks for an OpenAI key when self-hosted. */
const mockOpenAIKeyCheck = () =>
@@ -108,6 +110,47 @@ describe('RenameQueryModal', () => {
expect(screen.getByRole('button', { name: 'Rename query' })).toBeDisabled()
})
+ test('resets for the next snippet when both snippets share a name', async () => {
+ mockOpenAIKeyCheck()
+ const requests = mockUpsert()
+ const onComplete = vi.fn()
+
+ const { rerender } = customRender(
+ <RenameQueryModal snippet={UNTITLED_A} visible onCancel={vi.fn()} onComplete={onComplete} />
+ )
+
+ await userEvent.clear(getNameInput())
+ await userEvent.type(getNameInput(), 'Renamed query')
+ fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))
+ await waitFor(() => expect(onComplete).toHaveBeenCalledOnce())
+
+ // The parent keeps the renamed snippet selected while closing the modal, then reopens it for
+ // a second snippet that still carries the same original name
+ rerender(
+ <RenameQueryModal
+ snippet={UNTITLED_A}
+ visible={false}
+ onCancel={vi.fn()}
+ onComplete={onComplete}
+ />
+ )
+ rerender(
+ <RenameQueryModal snippet={UNTITLED_B} visible onCancel={vi.fn()} onComplete={onComplete} />
+ )
+
+ await waitFor(() => expect(getNameInput()).toHaveValue('Untitled query'))
+
+ await userEvent.clear(getNameInput())
+ await userEvent.type(getNameInput(), 'Second renamed query')
+ fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))
+
+ await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(2))
+ expect(requests).toEqual([
+ { id: 'untitled-a', name: 'Renamed query' },
+ { id: 'untitled-b', name: 'Second renamed query' },
+ ])
+ })
+
test('discards an abandoned edit when cancelled', async () => {
mockOpenAIKeyCheck()
const onCancel = vi.fn()
diff --git a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
index 1ae91dc20c1..8041ebe9b7d 100644
--- a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
@@ -49,12 +49,13 @@ const formSchema = z.object({
description: z.string().optional(),
})
-export const RenameQueryModal = ({
- snippet = {} as any,
- visible,
- onCancel,
- onComplete,
-}: RenameQueryModalProps) => {
+interface RenameQueryFormProps {
+ snippet: SqlSnippet | Snippet
+ onCancel: () => void
+ onComplete: () => void
+}
+
+const RenameQueryForm = ({ snippet, onCancel, onComplete }: RenameQueryFormProps) => {
const { ref } = useParams()
const router = useRouter()
@@ -145,7 +146,7 @@ export const RenameQueryModal = ({
}
toast.success('Successfully renamed snippet!')
- reset({ name, description }, { keepDirtyValues: false })
+ reset({ name, description })
if (onComplete) onComplete()
} catch (error: any) {
// [Joshen] We probably need some rollback cause all the saving is async
@@ -156,98 +157,105 @@ export const RenameQueryModal = ({
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: { name: name ?? '', description: description ?? '' },
- values: { name: name ?? '', description: description ?? '' },
- resetOptions: { keepDirtyValues: true },
})
const { reset, formState } = form
const { isDirty, isSubmitting } = formState
- const handleCancel = () => {
- onCancel()
- reset(undefined, { keepDirtyValues: false })
- }
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} noValidate>
+ <DialogSection className="space-y-4">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItemLayout name="name" layout="vertical" label="Name">
+ <FormControl>
+ <Input {...field} id="name" />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ <div className="flex w-full justify-end mt-2">
+ <ButtonTooltip
+ variant="default"
+ onClick={() => generateTitle()}
+ size="tiny"
+ disabled={
+ isTitleGenerationLoading || !isApiKeySet || isHipaaProjectDisallowed || isAiOptedOut
+ }
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: isHipaaProjectDisallowed
+ ? 'This feature is not available for HIPAA projects.'
+ : isAiOptedOut
+ ? 'Your organization has opted out of AI features.'
+ : isApiKeySet
+ ? undefined
+ : 'Add your "OPENAI_API_KEY" to your environment variables to use this feature.',
+ },
+ }}
+ >
+ <div className="flex items-center gap-1">
+ <div className="scale-75">
+ <AiIconAnimation loading={isTitleGenerationLoading} />
+ </div>
+ <span>Rename with Supabase AI</span>
+ </div>
+ </ButtonTooltip>
+ </div>
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItemLayout name="description" layout="vertical" label="Description">
+ <FormControl>
+ <Textarea
+ {...field}
+ id="description"
+ rows={4}
+ placeholder="Describe query"
+ className="resize-none"
+ />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ </DialogSection>
+ <DialogFooter>
+ <Button type="reset" variant="default" onClick={onCancel} disabled={isSubmitting}>
+ Cancel
+ </Button>
+ <Button type="submit" loading={isSubmitting} disabled={isSubmitting || !isDirty}>
+ Rename query
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ )
+}
+export const RenameQueryModal = ({
+ snippet = {} as any,
+ visible,
+ onCancel,
+ onComplete,
+}: RenameQueryModalProps) => {
return (
- <Dialog open={visible} onOpenChange={handleCancel}>
+ <Dialog open={visible} onOpenChange={onCancel}>
<DialogContent size="small">
<DialogHeader>
<DialogTitle>Rename</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} noValidate>
- <DialogSection className="space-y-4">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItemLayout name="name" layout="vertical" label="Name">
- <FormControl>
- <Input {...field} id="name" />
- </FormControl>
- </FormItemLayout>
- )}
- />
- <div className="flex w-full justify-end mt-2">
- <ButtonTooltip
- variant="default"
- onClick={() => generateTitle()}
- size="tiny"
- disabled={
- isTitleGenerationLoading ||
- !isApiKeySet ||
- isHipaaProjectDisallowed ||
- isAiOptedOut
- }
- tooltip={{
- content: {
- side: 'bottom',
- text: isHipaaProjectDisallowed
- ? 'This feature is not available for HIPAA projects.'
- : isAiOptedOut
- ? 'Your organization has opted out of AI features.'
- : isApiKeySet
- ? undefined
- : 'Add your "OPENAI_API_KEY" to your environment variables to use this feature.',
- },
- }}
- >
- <div className="flex items-center gap-1">
- <div className="scale-75">
- <AiIconAnimation loading={isTitleGenerationLoading} />
- </div>
- <span>Rename with Supabase AI</span>
- </div>
- </ButtonTooltip>
- </div>
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItemLayout name="description" layout="vertical" label="Description">
- <FormControl>
- <Textarea
- {...field}
- id="description"
- rows={4}
- placeholder="Describe query"
- className="resize-none"
- />
- </FormControl>
- </FormItemLayout>
- )}
- />
- </DialogSection>
- <DialogFooter>
- <Button type="reset" variant="default" onClick={handleCancel} disabled={isSubmitting}>
- Cancel
- </Button>
- <Button type="submit" loading={isSubmitting} disabled={isSubmitting || !isDirty}>
- Rename query
- </Button>
- </DialogFooter>
- </form>
- </Form>
+ {/* Keyed by snippet so that each snippet gets a fresh form, with no state carried over */}
+ <RenameQueryForm
+ key={snippet.id}
+ snippet={snippet}
+ onCancel={onCancel}
+ onComplete={onComplete}
+ />
</DialogContent>
</Dialog>
)
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
index 57ef4715aea..0a3eb0c034b 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
@@ -84,7 +84,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
const [showMoveModal, setShowMoveModal] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [showRenameModal, setShowRenameModal] = useState(false)
const [expandedFolderIds, setExpandedFolderIds] = useState<string[]>([])
const [selectedSnippets, setSelectedSnippets] = useState<Snippet[]>([])
@@ -564,7 +563,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
setSelectedSnippets([element.metadata as unknown as Snippet])
}}
onSelectRename={() => {
- setShowRenameModal(true)
setSelectedSnippetToRename(element.metadata as Snippet)
}}
onSelectDownload={() => {
@@ -646,7 +644,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
setSelectedSnippets([element.metadata as unknown as Snippet])
}}
onSelectRename={() => {
- setShowRenameModal(true)
setSelectedSnippetToRename(element.metadata as Snippet)
}}
onSelectDownload={() => {
@@ -754,7 +751,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
if (props.isBranch) {
snapV2.editFolder(element.id as string)
} else {
- setShowRenameModal(true)
setSelectedSnippetToRename(element.metadata as Snippet)
}
}}
@@ -817,7 +813,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
setSelectedSnippets([snippet])
}}
onSelectRename={(snippet) => {
- setShowRenameModal(true)
setSelectedSnippetToRename(snippet)
}}
/>
@@ -832,9 +827,9 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
<RenameQueryModal
snippet={selectedSnippetToRename}
- visible={showRenameModal}
- onCancel={() => setShowRenameModal(false)}
- onComplete={() => setShowRenameModal(false)}
+ visible={!!selectedSnippetToRename}
+ onCancel={() => setSelectedSnippetToRename(undefined)}
+ onComplete={() => setSelectedSnippetToRename(undefined)}
/>
<MoveQueryModal