Files
supabase/apps/studio/components/interfaces/Integrations/Vault/Secrets/EditSecretModal.tsx
T
Drake CostaandTerry Sutton d6fe8476f3 Refactor EditSecretModal to use shadcn components (#37258)
* chore: Refactor `NewAccessTokenButton` to use shadcn components

This brings `NewAccessTokenButton` into conformance with the latest UI patterns of using shadcn based components, zod schemas, and react-hook-form for form submission.

I based this refactor on the implementation of `CreateSecretAPIKeyDialog`, which already made use of the above.

* add success and failure toasts

* add smoke test for `NewAccessTokenButton`, fix vitest config

This adds a minimal test for `NewAccessTokenButton` but more importantly fixes a critical bug in the vitest configuration for `studio`.

Because `restoreMocks: true` was set in the config, this meant that the mock implementation for `window.matchMedia` defined in the `tests/vitestSetup.ts` file was being **reset** to an empty function before each test suite was run. While this didn't appear to be a problem before, that appears to be because none of the existing tests had `motion.div` in their component trees. Since `motion.div` calls `addListener` on a media query as part of it's lifecycle, that meant that any test which included it would fail as `addListener` would be undefined in this situation. Removing `restoreMocks: true` from the config results in the desired mocking behavior.

This change is necessary in order to test any component that has the `FormItemLayout` component, as it uses `framer-motion` to animate in error messages for input elements.

* add warning comment in case of future config regression

* update test cases, reset form on dialog close, testing setup fixes

This fixes an issue with the polyfills for the testing environment, where a call to `useMutation` would fail as a result of `TransformStream` being set to `null`.

Basic tests for access token creation and form resetting added. Adds `@faker-js/faker` to the studio app devDependencies to generate mock data for `msw` endpoint response.

Adds `shx` to the docs app devDependencies to ensure that the `codegen:examples` script runs cross-platform.

* ensure mocked date is a string

* update testing setup, pollyfills and add rich type support to addAPIMock

* add missing changes

* Move `EditSecretModal` to be child of `SecretRow`

In the accompanying PR for `DeleteSecretModal`, that one will also be moved over to `SecretRow`

* Update studio testing setup files

Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components

* chore: Refactor `NewAccessTokenButton` to use shadcn components

This brings `NewAccessTokenButton` into conformance with the latest UI patterns of using shadcn based components, zod schemas, and react-hook-form for form submission.

I based this refactor on the implementation of `CreateSecretAPIKeyDialog`, which already made use of the above.

* add success and failure toasts

* add smoke test for `NewAccessTokenButton`, fix vitest config

This adds a minimal test for `NewAccessTokenButton` but more importantly fixes a critical bug in the vitest configuration for `studio`.

Because `restoreMocks: true` was set in the config, this meant that the mock implementation for `window.matchMedia` defined in the `tests/vitestSetup.ts` file was being **reset** to an empty function before each test suite was run. While this didn't appear to be a problem before, that appears to be because none of the existing tests had `motion.div` in their component trees. Since `motion.div` calls `addListener` on a media query as part of it's lifecycle, that meant that any test which included it would fail as `addListener` would be undefined in this situation. Removing `restoreMocks: true` from the config results in the desired mocking behavior.

This change is necessary in order to test any component that has the `FormItemLayout` component, as it uses `framer-motion` to animate in error messages for input elements.

* update test cases, reset form on dialog close, testing setup fixes

This fixes an issue with the polyfills for the testing environment, where a call to `useMutation` would fail as a result of `TransformStream` being set to `null`.

Basic tests for access token creation and form resetting added. Adds `@faker-js/faker` to the studio app devDependencies to generate mock data for `msw` endpoint response.

Adds `shx` to the docs app devDependencies to ensure that the `codegen:examples` script runs cross-platform.

* ensure mocked date is a string

* update testing setup, pollyfills and add rich type support to addAPIMock

* add missing changes

* Move `EditSecretModal` to be child of `SecretRow`

In the accompanying PR for `DeleteSecretModal`, that one will also be moved over to `SecretRow`

* fix imports

* Update test, fix rebase errors

* remove unnecessary code

* resolve type errors

* fix missing listen call for msw, resolve test type error

* fix imports

* Update studio testing setup files

Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components

* fix missing listen call for msw, resolve test type error

* fix imports

* remove duplicate test

* update testing setup

* implement requested changes

* cleanup unnecessary conditional logic for undefined `secret` prop

* remove unused import

* remove unnecessary code

* cleanup, replace lodash import with JS

* add required router mock

* fix broken lockfile

---------

Co-authored-by: Terry Sutton <saltcod@gmail.com>
2025-08-08 15:42:06 -02:30

209 lines
6.8 KiB
TypeScript

import { useState } from 'react'
import { EyeOff, Eye } from 'lucide-react'
import { type SubmitHandler, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
Form_Shadcn_,
FormControl_Shadcn_,
FormField_Shadcn_,
Input_Shadcn_,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useVaultSecretDecryptedValueQuery } from 'data/vault/vault-secret-decrypted-value-query'
import { useVaultSecretUpdateMutation } from 'data/vault/vault-secret-update-mutation'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import type { VaultSecret } from 'types'
interface EditSecretModalProps {
visible: boolean
secret: VaultSecret
onClose: () => void
}
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'
const EditSecretModal = ({ visible, secret, onClose }: EditSecretModalProps) => {
const [showSecretValue, setShowSecretValue] = useState(false)
const { data: project } = useSelectedProjectQuery()
const { data, isLoading: 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, isLoading: isSubmitting } = useVaultSecretUpdateMutation()
const onSubmit: SubmitHandler<z.infer<typeof SecretSchema>> = async (values) => {
if (!project) return console.error('Project 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')
onClose()
},
onError: (error) => {
toast.error(`Failed to update secret: ${error.message}`)
},
}
)
}
}
return (
<Dialog
open={visible}
onOpenChange={(open) => {
if (!open) {
form.reset()
onClose()
}
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit secret</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
{isLoadingSecretValue ? (
<DialogSection>
<GenericSkeletonLoader />
</DialogSection>
) : (
<>
<DialogSection>
<Form_Shadcn_ {...form}>
<form
id={formId}
className="flex flex-col gap-4"
autoComplete="off"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField_Shadcn_
key="name"
name="name"
control={form.control}
render={({ field }) => (
<FormItemLayout name="name" label="Name">
<FormControl_Shadcn_>
<Input_Shadcn_ id="name" {...field} />
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
<FormField_Shadcn_
key="description"
name="description"
control={form.control}
render={({ field }) => (
<FormItemLayout
name="description"
label="Description"
labelOptional="Optional"
>
<FormControl_Shadcn_>
<Input_Shadcn_ id="description" {...field} data-lpignore="true" />
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
<FormField_Shadcn_
key="secret"
name="secret"
control={form.control}
render={({ field }) => (
<FormItemLayout name="secret" label="Secret value">
<FormControl_Shadcn_>
<div className="relative">
<Input_Shadcn_
id="secret"
type={showSecretValue ? 'text' : 'password'}
{...field}
data-lpignore="true"
/>
<Button
type="default"
title={showSecretValue ? `Hide secret value` : `Show secret value`}
aria-label={
showSecretValue ? `Hide secret value` : `Show secret value`
}
className="absolute right-2 top-1 px-3 py-2"
icon={showSecretValue ? <EyeOff /> : <Eye />}
onClick={() => setShowSecretValue(!showSecretValue)}
/>
</div>
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
</form>
</Form_Shadcn_>
</DialogSection>
<DialogFooter>
<Button
type="default"
disabled={isSubmitting}
onClick={() => {
form.reset()
onClose()
}}
>
Cancel
</Button>
<Button form={formId} htmlType="submit" loading={isSubmitting}>
Update secret
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
)
}
export default EditSecretModal