import { zodResolver } from '@hookform/resolvers/zod' import dayjs from 'dayjs' import { SubmitHandler, useForm, useWatch } from 'react-hook-form' import { Button, Form, FormControl, FormField, Input, Modal, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import * as z from 'zod' import { useCopyUrl } from './useCopyUrl' import { DATETIME_FORMAT } from '@/lib/constants' import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer' const unitMap = { days: 3600 * 24, weeks: 3600 * 24 * 7, months: 3600 * 24 * 30, years: 3600 * 24 * 365, } as const const formSchema = z.object({ expiresIn: z.preprocess( (val) => (val ? val : undefined), z.coerce .number({ required_error: 'Required', invalid_type_error: 'Required' }) .positive('Expiry duration must be greater than 0') ), units: z.enum(['days', 'weeks', 'months', 'years']), }) type FormSchema = z.infer const formId = 'storage-custom-expiry-form' export const CustomExpiryModal = () => { const { onCopyUrl } = useCopyUrl() const snap = useStorageExplorerStateSnapshot() const { selectedFileCustomExpiry, setSelectedFileCustomExpiry } = snap const visible = selectedFileCustomExpiry !== undefined const onClose = () => setSelectedFileCustomExpiry(undefined) const form = useForm({ resolver: zodResolver(formSchema as any), defaultValues: { expiresIn: 0, units: 'days' }, }) const handleClose = () => { onClose() form.reset() } const { isDirty, isSubmitting, isValid } = form.formState const handleSubmit: SubmitHandler = async (values) => { await onCopyUrl(selectedFileCustomExpiry!.path!, values.expiresIn * unitMap[values.units]) handleClose() } const [expiresIn, units] = useWatch({ name: ['expiresIn', 'units'], control: form.control, }) return (

Enter the duration for which the URL will be valid for:

( { field.onChange( isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber ) }} /> )} />
( )} />
{isDirty && isValid && (

URL will expire on {dayjs().add(expiresIn, units).format(DATETIME_FORMAT)}

)}
) }