The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: use `react-hook-form` in SQL snippets modals (#44232)
Gildas Garcia91ee6e64f35a
diff --git a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsxindex 9201b8f032f..b8613ddf11b 100644--- a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx+++ b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx@@ -1,6 +1,4 @@-import { useEffect, useState } from 'react'-import { toast } from 'sonner'-+import { zodResolver } from '@hookform/resolvers/zod'import { useParams } from 'common'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useCheckOpenAIKeyQuery } from 'data/ai/check-api-key-query'@@ -17,9 +15,24 @@ import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-queimport { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { IS_PLATFORM } from 'lib/constants'import { useRouter } from 'next/router'+import { useEffect } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import { toast } from 'sonner'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { createTabId, useTabsStateSnapshot } from 'state/tabs'-import { AiIconAnimation, Button, Form, Input, Modal } from 'ui'+import {+ AiIconAnimation,+ Button,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Modal,+ Textarea,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import * as z from 'zod'+import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'export interface RenameQueryModalProps {@@ -29,6 +42,11 @@ export interface RenameQueryModalProps {onComplete: () => void}+const formSchema = z.object({+ name: z.string().min(1, 'Please enter a query name'),+ description: z.string().optional(),+})+const RenameQueryModal = ({snippet = {} as any,visible,@@ -53,48 +71,41 @@ const RenameQueryModal = ({const { id, name, description } = snippet- const [nameInput, setNameInput] = useState(name)- const [descriptionInput, setDescriptionInput] = useState(description)-- const { mutate: titleSql, isPending: isTitleGenerationLoading } = useSqlTitleGenerateMutation({- onSuccess: (data) => {- const { title, description } = data- setNameInput(title)- if (!descriptionInput) setDescriptionInput(description)- },- onError: (error) => {- toast.error(`Failed to rename query: ${error.message}`)- },- })+ const { mutate: getGeneratedValues, isPending: isTitleGenerationLoading } =+ useSqlTitleGenerateMutation({+ onSuccess: (data) => {+ const { title, description } = data+ form.setValue('name', title, { shouldDirty: true })+ if (!form.getValues().description) {+ form.setValue('description', description, { shouldDirty: true })+ }+ },+ onError: (error) => {+ toast.error(`Failed to generate title and description: ${error.message}`)+ },+ })const { data: check } = useCheckOpenAIKeyQuery()const isApiKeySet = !!check?.hasKeyconst generateTitle = async () => {if ('content' in snippet && isSQLSnippet) {- titleSql({ sql: snippet.content.sql })+ getGeneratedValues({ sql: snippet.content.sql })} else {try {const { content } = await getContentById({ projectRef: ref, id: snippet.id })- if ('sql' in content) titleSql({ sql: content.sql })+ if ('sql' in content) getGeneratedValues({ sql: content.sql })} catch (error) {toast.error('Unable to generate title based on query contents')}}}- const validate = () => {- const errors: any = {}- if (!nameInput) errors.name = 'Please enter a query name'- return errors- }-const { mutateAsync: upsertContent } = useContentUpsertMutation()- const onSubmit = async (values: any, { setSubmitting }: any) => {+ const onSubmit: SubmitHandler<z.infer<typeof formSchema>> = async ({ name, description }) => {if (!ref) return console.error('Project ref is required')if (!id) return console.error('Snippet ID is required')- setSubmitting(true)try {let localSnippet = snippet@@ -108,16 +119,16 @@ const RenameQueryModal = ({projectRef: ref,payload: {...localSnippet,- name: nameInput,- description: descriptionInput,+ name,+ description,} as UpsertContentPayload,})if (IS_PLATFORM) {- snapV2.renameSnippet({ id, name: nameInput, description: descriptionInput })+ snapV2.renameSnippet({ id, name, description })const tabId = createTabId('sql', { id })- tabsSnap.updateTab(tabId, { label: nameInput })+ tabsSnap.updateTab(tabId, { label: name })} else if (changedSnippet) {// In self-hosted, the snippet also updates the id when renaming it. This code is to ensure the previous snippet// is removed, new one is added, tab state is updated and the router is updated.@@ -138,86 +149,100 @@ const RenameQueryModal = ({toast.success('Successfully renamed snippet!')if (onComplete) onComplete()} catch (error: any) {- setSubmitting(false)// [Joshen] We probably need some rollback cause all the saving is asynctoast.error(`Failed to rename snippet: ${error.message}`)}}+ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: { name: name ?? '', description: description ?? '' },+ })+ const { reset, formState } = form+ const { isDirty, isSubmitting } = formState+useEffect(() => {- setNameInput(name)- setDescriptionInput(description)- }, [snippet.id])+ if (isDirty) return+ reset({ name: name ?? '', description: description ?? '' })+ }, [id, name, description, reset, isDirty])++ const handleCancel = () => {+ onCancel()+ reset()+ }return (- <Modal visible={visible} onCancel={onCancel} hideFooter header="Rename" size="small">- <Form- onReset={onCancel}- validateOnBlur- initialValues={{- name: name ?? '',- description: description ?? '',- }}- validate={validate}- onSubmit={onSubmit}- >- {({ isSubmitting }: { isSubmitting: boolean }) => (- <>- <Modal.Content className="space-y-4">- <Input- label="Name"- id="name"- name="name"- value={nameInput}- onChange={(e) => setNameInput(e.target.value)}- />- <div className="flex w-full justify-end mt-2">- {!hasHipaaAddon && (- <ButtonTooltip- type="default"- onClick={() => generateTitle()}- size="tiny"- disabled={isTitleGenerationLoading || !isApiKeySet}- tooltip={{- content: {- side: 'bottom',- text: 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>+ <Modal visible={visible} onCancel={handleCancel} hideFooter header="Rename" size="small">+ <Form_Shadcn_ {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} noValidate>+ <Modal.Content className="space-y-4">+ <FormField_Shadcn_+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItemLayout name="name" layout="vertical" label="Name">+ <FormControl_Shadcn_>+ <Input_Shadcn_ {...field} id="name" />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ <div className="flex w-full justify-end mt-2">+ {!hasHipaaAddon && (+ <ButtonTooltip+ type="default"+ onClick={() => generateTitle()}+ size="tiny"+ disabled={isTitleGenerationLoading || !isApiKeySet}+ tooltip={{+ content: {+ side: 'bottom',+ text: 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>- </ButtonTooltip>- )}- </div>- <Input.TextArea- label="Description"- id="description"- placeholder="Describe query"- size="medium"- textAreaClassName="resize-none"- value={descriptionInput}- onChange={(e) => setDescriptionInput(e.target.value)}- />- </Modal.Content>- <Modal.Separator />- <Modal.Content className="flex items-center justify-end gap-2">- <Button htmlType="reset" type="default" onClick={onCancel} disabled={isSubmitting}>- Cancel- </Button>- <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting}>- Rename query- </Button>- </Modal.Content>- </>- )}- </Form>+ <span>Rename with Supabase AI</span>+ </div>+ </ButtonTooltip>+ )}+ </div>+ </Modal.Content>+ <Modal.Content>+ <FormField_Shadcn_+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItemLayout name="description" layout="vertical" label="Description">+ <FormControl_Shadcn_>+ <Textarea+ {...field}+ id="description"+ rows={4}+ placeholder="Describe query"+ className="resize-none"+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </Modal.Content>+ <Modal.Separator />+ <Modal.Content className="flex items-center justify-end gap-2">+ <Button htmlType="reset" type="default" onClick={handleCancel} disabled={isSubmitting}>+ Cancel+ </Button>+ <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting || !isDirty}>+ Rename query+ </Button>+ </Modal.Content>+ </form>+ </Form_Shadcn_></Modal>)}