Files
supabase/apps/studio/components/interfaces/Integrations/Vault/Secrets/EditSecretModal.tsx
T
Gildas Garcia 3146650a5a Fix FormItemLayout usages for a11y (#49761)
Follow up of #49637. Usages that impacted tests were fixed in the
previous PR. This PR fixes the other usages so that label are correctly
linked to their inputs.

No visual changes

## How to test

1. Design system: [Form
examples](https://design-system-git-fix-form-item-layout-usages-supabase.vercel.app/design-system/docs/ui-patterns/forms):
moved `FormControl` around the `SelectTrigger` so that the label is
linked to the button (It's actually done like this in the [Select Form
example](https://design-system-git-fix-form-item-layout-usages-supabase.vercel.app/design-system/docs/components/select#form)
and Radix recommend targeting the button too in their
[documentation](https://www.radix-ui.com/primitives/docs/components/select#labelling))
2. [Access
tokens](https://studio-staging-463111oii-supabase.vercel.app/dashboard/account/tokens):
updated usage to fallback on generated ids and fixed the select just
like _1_
3. [New TOTP
factor](https://studio-staging-463111oii-supabase.vercel.app/dashboard/account/security):
updated usage to fallback on generated ids
4. _Studio/Database/Extensions_
(`https://studio-staging-463111oii-supabase.vercel.app/dashboard/project/[PROJECT]/database/extensions`):
updated the extension enabling modal to fallback on generated ids
5. _Studio/Integrations/Vault
(`https://studio-staging-463111oii-supabase.vercel.app/dashboard/project/[PROJECT]/integrations/vault/secrets`):
updated the secret edition modal to fallback on generated ids
6.
_Studio/Observability(`https://studio-staging-463111oii-supabase.vercel.app/dashboard/project/[PROJECT]/observability`):
updated the report creation and edition modals to fallback on generated
ids
7. _Studio/SQL
Editor(`https://studio-staging-463111oii-supabase.vercel.app/dashboard/project/[PROJECT]/sql/new`):
updated the query renaming modal to fallback on generated ids
8.
_Studio/Storage/Analytics(`https://studio-staging-463111oii-supabase.vercel.app/dashboard/project/[PROJECT]/storage/analytics`):
updated the table creation sheet to fallback on generated ids (you must
have a bucket first)
9.
_Studio/Workers(`https://studio-staging-463111oii-supabase.vercel.app/dashboard/project/[PROJECT]/workers`):
updated the worker creation modal to fallback on generated ids (you must
have a bucket first)
10. Updated
[Signup](https://studio-staging-463111oii-supabase.vercel.app/dashboard/sign-up?returnTo=%2Fnew),
[Signin](https://studio-staging-463111oii-supabase.vercel.app/dashboard/sign-in)
and [SSO
Signin](https://studio-staging-463111oii-supabase.vercel.app/dashboard/sign-in-sso)
forms to fallback on generated ids

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Improvements**
- Standardized form field presentation across access tokens,
authentication, reports, integrations, database extensions, SQL editor,
storage, and worker deployment workflows.
- Updated password fields and visibility toggles for more consistent
input behavior.
- Refined token expiration selection, verification code entry, and
dropdown layouts.
- Preserved existing labels, validation, options, and form functionality
while simplifying the interface structure.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-09-01 15:22:55 +02:00

235 lines
7.9 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { Eye, EyeOff } from 'lucide-react'
import { parseAsString, useQueryState } from 'nuqs'
import { useEffect, useState } from 'react'
import { useForm, type SubmitHandler } from 'react-hook-form'
import { toast } from 'sonner'
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
Form,
FormControl,
FormField,
Input,
Textarea,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { z } from 'zod'
import { useVaultSecretDecryptedValueQuery } from '@/data/vault/vault-secret-decrypted-value-query'
import { useVaultSecretUpdateMutation } from '@/data/vault/vault-secret-update-mutation'
import { useVaultSecretsQuery } from '@/data/vault/vault-secrets-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import type { VaultSecret } from '@/types'
const SecretSchema = z.object({
name: z.string().min(1, 'Please provide a name for your secret'),
description: z.string().optional(),
secret: z.string().min(1, 'Please enter your secret value'),
})
const formId = 'edit-vault-secret-form'
export const EditSecretModal = () => {
const { data: project } = useSelectedProjectQuery()
const { data: secrets = [], isSuccess } = useVaultSecretsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
const [secretIdToEdit, setSelectedSecretToEdit] = useQueryState('edit', parseAsString)
const secret = secrets.find((secret) => secret.id === secretIdToEdit)
const [showSecretValue, setShowSecretValue] = useState(false)
const { data, isPending: isLoadingSecretValue } = useVaultSecretDecryptedValueQuery(
{
projectRef: project?.ref,
id: secret?.id,
connectionString: project?.connectionString,
},
{ enabled: !!project?.ref }
)
const values = {
name: secret?.name ?? '',
description: secret?.description ?? '',
secret: secret?.decryptedSecret ?? data ?? '',
}
const form = useForm<z.infer<typeof SecretSchema>>({
resolver: zodResolver(SecretSchema),
defaultValues: values,
values,
})
const { mutate: updateSecret, isPending: isSubmitting } = useVaultSecretUpdateMutation()
const onSubmit: SubmitHandler<z.infer<typeof SecretSchema>> = async (values) => {
if (!project) return console.error('Project is required')
if (!secret) return console.error('Secret is required')
const payload: Partial<VaultSecret> = {
secret: values.secret,
}
if (values.name !== secret.name) payload.name = values.name
if (values.description !== secret.description) payload.description = values.description
if (Object.keys(payload).length > 0) {
updateSecret(
{
projectRef: project.ref,
connectionString: project?.connectionString,
id: secret.id,
...payload,
},
{
onSuccess: () => {
toast.success('Successfully updated secret')
setSelectedSecretToEdit(null)
},
onError: (error) => {
toast.error(`Failed to update secret: ${error.message}`)
},
}
)
}
}
useEffect(() => {
if (isSuccess && !!secretIdToEdit && !secret) {
toast('Secret not found')
setSelectedSecretToEdit(null)
}
}, [isSuccess, secretIdToEdit, secret, setSelectedSecretToEdit])
return (
<Dialog
open={!!secret}
onOpenChange={(open) => {
if (!open) {
form.reset()
setSelectedSecretToEdit(null)
}
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit secret</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
{isLoadingSecretValue ? (
<DialogSection>
<GenericSkeletonLoader />
</DialogSection>
) : (
<>
<DialogSection>
<Form {...form}>
<form
id={formId}
className="flex flex-col gap-4"
autoComplete="off"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField
key="name"
name="name"
control={form.control}
render={({ field }) => (
<FormItemLayout label="Name">
<FormControl>
<Input {...field} />
</FormControl>
</FormItemLayout>
)}
/>
<FormField
key="description"
name="description"
control={form.control}
render={({ field }) => (
<FormItemLayout label="Description" labelOptional="Optional">
<FormControl>
<Input {...field} data-lpignore="true" />
</FormControl>
</FormItemLayout>
)}
/>
<FormField
key="secret"
name="secret"
control={form.control}
render={({ field }) => (
<FormItemLayout label="Secret value">
<div className="relative">
<FormControl>
<Textarea
{...field}
rows={1}
ref={(el) => {
field.ref(el)
if (el) {
el.style.height = 'auto'
el.style.height = Math.max(40, el.scrollHeight) + 'px'
}
}}
data-lpignore="true"
className="min-h-0 resize-none"
style={
{
WebkitTextSecurity: showSecretValue ? undefined : 'disc',
} as React.CSSProperties
}
onChange={(e) => {
field.onChange(e)
e.currentTarget.style.height = 'auto'
e.currentTarget.style.height =
Math.max(40, e.currentTarget.scrollHeight) + 'px'
}}
/>
</FormControl>
<Button
variant="default"
title={showSecretValue ? `Hide secret value` : `Show secret value`}
aria-label={showSecretValue ? `Hide secret value` : `Show secret value`}
className="absolute right-1 top-1 w-7"
icon={showSecretValue ? <EyeOff /> : <Eye />}
onClick={() => setShowSecretValue(!showSecretValue)}
/>
</div>
</FormItemLayout>
)}
/>
</form>
</Form>
</DialogSection>
<DialogFooter>
<Button
variant="default"
disabled={isSubmitting}
onClick={() => {
form.reset()
setSelectedSecretToEdit(null)
}}
>
Cancel
</Button>
<Button form={formId} type="submit" loading={isSubmitting}>
Update secret
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
)
}