Files
Drake Costa ca4b3bc624 Refactor Storage Create/Edit/Empty/Delete Modals to use Shadcn components (#37517)
* Refactor `StorageMenu` modals to replace deprecated patterns

* add test for `DeleteBucketModal` and update test setup

Note: Because this component uses `useParams`, it's necessary to have the dynamic route segment passed to `next-router-mock`'s `createDynamicRouteParser`. In order not to have to manually list all of these as the application grows, I added a glob utility that uses the `pages/` directory  to automatically generate an array of dynamic route paths in this case.

* add test for `EmptyBucketModal`

* add test for `EditBucketModal` and add `isNonNullable` utility function

* add test for `CreateBucketModal`

* implement requested changes

* implement visual fixes
2025-08-14 21:23:08 +02:00

185 lines
5.8 KiB
TypeScript

import { get as _get, find } from 'lodash'
import { useRouter } from 'next/router'
import { SubmitHandler, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import z from 'zod'
import { toast } from 'sonner'
import { useParams } from 'common'
import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'
import { useDatabasePolicyDeleteMutation } from 'data/database-policies/database-policy-delete-mutation'
import { useBucketDeleteMutation } from 'data/storage/bucket-delete-mutation'
import { Bucket, useBucketsQuery } from 'data/storage/buckets-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { formatPoliciesForStorage } from './Storage.utils'
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
Form_Shadcn_,
FormControl_Shadcn_,
FormField_Shadcn_,
Input_Shadcn_,
Label_Shadcn_,
} from 'ui'
import { Admonition } from 'ui-patterns'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
export interface DeleteBucketModalProps {
visible: boolean
bucket: Bucket
onClose: () => void
}
const formId = `delete-storage-bucket-form`
export const DeleteBucketModal = ({ visible, bucket, onClose }: DeleteBucketModalProps) => {
const router = useRouter()
const { ref: projectRef } = useParams()
const { data: project } = useSelectedProjectQuery()
const schema = z.object({
confirm: z.literal(bucket.name, {
errorMap: () => ({ message: `Please enter "${bucket.name}" to confirm` }),
}),
})
const form = useForm<z.infer<typeof schema>>({
resolver: zodResolver(schema),
})
const { data } = useBucketsQuery({ projectRef })
const { data: policies } = useDatabasePoliciesQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
schema: 'storage',
})
const { mutateAsync: deletePolicy } = useDatabasePolicyDeleteMutation()
const { mutate: deleteBucket, isLoading } = useBucketDeleteMutation({
onSuccess: async () => {
if (!project) return console.error('Project is required')
// Clean up policies from the corresponding bucket that was deleted
const storageObjectsPolicies = (policies ?? []).filter((policy) => policy.table === 'objects')
const formattedStorageObjectPolicies = formatPoliciesForStorage(
buckets,
storageObjectsPolicies
)
const bucketPolicies = _get(
find(formattedStorageObjectPolicies, { name: bucket.name }),
['policies'],
[]
)
try {
await Promise.all(
bucketPolicies.map((policy: any) =>
deletePolicy({
projectRef: project?.ref,
connectionString: project?.connectionString,
originalPolicy: policy,
})
)
)
toast.success(`Successfully deleted bucket ${bucket.name}`)
router.push(`/project/${projectRef}/storage/buckets`)
onClose()
} catch (error) {
toast.success(
`Successfully deleted bucket ${bucket.name}. However, there was a problem deleting the policies tied to the bucket. Please review them in the storage policies section`
)
}
},
})
const buckets = data ?? []
const onSubmit: SubmitHandler<z.infer<typeof schema>> = async () => {
if (!projectRef) return console.error('Project ref is required')
if (!bucket) return console.error('No bucket is selected')
deleteBucket({ projectRef, id: bucket.id, type: bucket.type })
}
return (
<Dialog
open={visible}
onOpenChange={(open) => {
if (!open) {
onClose()
}
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{`Confirm deletion of ${bucket.name}`}</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
<DialogSection className="flex flex-col gap-4">
<Admonition
type="destructive"
title="You cannot recover this bucket once deleted."
description="All bucket data will be lost."
/>
<p>
Your bucket <span className="font-bold text-foreground">{bucket.name}</span> and all its
contents will be permanently deleted.
</p>
</DialogSection>
<DialogSectionSeparator />
<DialogSection>
<Form_Shadcn_ {...form}>
<form
id={formId}
className="flex flex-col gap-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField_Shadcn_
key="confirm"
name="confirm"
control={form.control}
render={({ field }) => (
<FormItemLayout
name="confirm"
label={
<>
Type <span className="font-bold text-foreground">{bucket.name}</span> to
confirm.
</>
}
>
<FormControl_Shadcn_>
<Input_Shadcn_
id="confirm"
autoComplete="off"
{...field}
placeholder="Type in name of bucket"
/>
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
</form>
</Form_Shadcn_>
</DialogSection>
<DialogFooter>
<Button type="default" disabled={isLoading} onClick={onClose}>
Cancel
</Button>
<Button form={formId} htmlType="submit" type="danger" loading={isLoading}>
Delete Bucket
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default DeleteBucketModal