Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Fix value set for storage upload unit (#26803)

Terry Sutton0c7d5dc306b4
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx
index c6012952989..7fdda3f4b93 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx
@@ -2,10 +2,23 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
-import { Button, Form, IconClock, Input, Listbox } from 'ui'
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Form_Shadcn_,
+ Input_Shadcn_,
+ Select_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ SelectContent_Shadcn_,
+} from 'ui'
import AlertError from 'components/ui/AlertError'
-import { FormHeader } from 'components/ui/Forms'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import UpgradeToPro from 'components/ui/UpgradeToPro'
import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'
@@ -14,6 +27,10 @@ import { useCheckPermissions, useSelectedOrganization } from 'hooks'
import { IS_PLATFORM } from 'lib/constants'
import { STORAGE_FILE_SIZE_LIMIT_MAX_BYTES, StorageSizeUnits } from './StorageSettings.constants'
import { convertFromBytes, convertToBytes } from './StorageSettings.utils'
+import * as z from 'zod'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useForm, SubmitHandler } from 'react-hook-form'
+import { Clock } from 'lucide-react'
const StorageSettings = () => {
const { ref: projectRef } = useParams()
@@ -29,198 +46,197 @@ const StorageSettings = () => {
isSuccess,
isError,
} = useProjectStorageConfigQuery({ projectRef }, { enabled: IS_PLATFORM })
- const { fileSizeLimit, isFreeTier } = config || {}
- const { value, unit } = convertFromBytes(fileSizeLimit ?? 0)
+ const { isFreeTier } = config || {}
+
+ const [initialValues, setInitialValues] = useState({
+ fileSizeLimit: 0,
+ unit: StorageSizeUnits.BYTES,
+ })
+
+ useEffect(() => {
+ if (isSuccess && config) {
+ const { fileSizeLimit } = config
+ const { value, unit } = convertFromBytes(fileSizeLimit ?? 0)
+ setInitialValues({ fileSizeLimit: value, unit: unit })
+ // Reset the form values when the config values load
+ form.reset({ fileSizeLimit: value, unit: unit })
+ }
+ }, [isSuccess, config])
+
+ const formattedMaxSizeBytes = `${new Intl.NumberFormat('en-US').format(
+ STORAGE_FILE_SIZE_LIMIT_MAX_BYTES
+ )} bytes`
+
+ const FormSchema = z
+ .object({
+ fileSizeLimit: z.coerce.number(),
+ unit: z.nativeEnum(StorageSizeUnits),
+ })
+ .superRefine((data, ctx) => {
+ const { unit, fileSizeLimit } = data
+ const { value: formattedMaxLimit } = convertFromBytes(STORAGE_FILE_SIZE_LIMIT_MAX_BYTES, unit)
+
+ if (fileSizeLimit > formattedMaxLimit) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Maximum limit is up to ${formattedMaxLimit.toLocaleString()} ${unit}.`,
+ path: ['fileSizeLimit'],
+ })
+ }
+ })
- const [selectedUnit, setSelectedUnit] = useState(unit)
- let initialValues = { fileSizeLimit: value, unformattedFileSizeLimit: fileSizeLimit }
+ const form = useForm<z.infer<typeof FormSchema>>({
+ resolver: zodResolver(FormSchema),
+ defaultValues: initialValues,
+ })
+ const { fileSizeLimit: limit, unit: storageUnit } = form.watch()
const { mutate: updateStorageConfig, isLoading: isUpdating } =
useProjectStorageConfigUpdateUpdateMutation({
- onSuccess: (res) => {
- const updatedValue = convertFromBytes(res.fileSizeLimit)
- initialValues = {
- fileSizeLimit: updatedValue.value,
- unformattedFileSizeLimit: res.fileSizeLimit,
- }
+ onSuccess: () => {
toast.success('Successfully updated storage settings')
},
})
- const formattedMaxSizeBytes = `${new Intl.NumberFormat('en-US').format(
- STORAGE_FILE_SIZE_LIMIT_MAX_BYTES
- )} bytes`
-
- const { value: formattedMaxLimit } = convertFromBytes(
- STORAGE_FILE_SIZE_LIMIT_MAX_BYTES,
- selectedUnit
- )
-
- const onValidate = (values: any) => {
- const errors = {} as any
- if (values.fileSizeLimit > formattedMaxLimit) {
- errors['fileSizeLimit'] =
- `Maximum limit is up to ${formattedMaxLimit.toLocaleString()} ${selectedUnit}.`
- }
- return errors
- }
-
- const onSubmit = async (values: any) => {
+ const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
if (!projectRef) return console.error('Project ref is required')
-
- const errors = onValidate(values)
-
- if (errors.fileSizeLimit) {
- return toast.error(`Upload file size limit must be up to 50GB (${formattedMaxSizeBytes})`)
- }
-
updateStorageConfig({
projectRef,
- fileSizeLimit: convertToBytes(values.fileSizeLimit, selectedUnit),
+ fileSizeLimit: convertToBytes(data.fileSizeLimit, data.unit),
})
}
+ const formId = 'storage-settings-form'
+
return (
<div>
- <Form validateOnBlur initialValues={initialValues} validate={onValidate} onSubmit={onSubmit}>
- {({
- values,
- resetForm,
- handleReset,
- }: {
- values: any
- resetForm: any
- handleReset: () => void
- }) => {
- const hasChanges =
- initialValues.unformattedFileSizeLimit !==
- convertToBytes(values.fileSizeLimit, selectedUnit)
-
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- resetForm({ values: initialValues, initialValues })
- }, [isSuccess])
-
- return (
- <>
- {isLoading && <GenericSkeletonLoader />}
- {isError && (
- <AlertError
- error={error}
- subject="Failed to retrieve project's storage configuration"
- />
- )}
- {isSuccess && (
- <div
- className={[
- 'bg-surface-100',
- 'overflow-hidden border-muted',
- 'rounded-md border shadow',
- ].join(' ')}
- >
- <div className="flex flex-col gap-0 divide-y divide-border-muted">
- <div className="grid grid-cols-12 gap-6 px-8 py-8 lg:gap-12">
- <div className="relative flex flex-col col-span-12 gap-6 lg:col-span-4">
- <p className="text-sm">Upload file size limit</p>
+ <Form_Shadcn_ {...form}>
+ {isLoading && <GenericSkeletonLoader />}
+ {isError && (
+ <AlertError error={error} subject="Failed to retrieve project's storage configuration" />
+ )}
+ {isSuccess && (
+ <form id={formId} className="" onSubmit={form.handleSubmit(onSubmit)}>
+ <div className="bg-surface-100 overflow-hidden border-muted rounded-md border shadow">
+ <div className="flex flex-col gap-0 divide-y divide-border-muted">
+ <div className="grid grid-cols-12 gap-6 px-8 py-8 lg:gap-12">
+ <div className="relative flex flex-col col-span-12 gap-6 lg:col-span-4">
+ <p className="text-sm">Upload file size limit</p>
+ </div>
+
+ <div className="relative flex flex-col col-span-12 gap-x-6 gap-y-2 lg:col-span-8">
+ <div className="grid grid-cols-12 col-span-12 gap-2">
+ <div className="col-span-8">
+ <FormField_Shadcn_
+ control={form.control}
+ name="fileSizeLimit"
+ render={({ field }) => (
+ <FormItem_Shadcn_>
+ <FormLabel_Shadcn_ className="text-foreground-light hidden">
+ size
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Input_Shadcn_ type="number" {...field} className="w-full" />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
+ </FormItem_Shadcn_>
+ )}
+ />
</div>
- <div className="relative flex flex-col col-span-12 gap-x-6 gap-y-2 lg:col-span-8">
- <div className="grid grid-cols-12 col-span-12 gap-2">
- <div className="col-span-8">
- <Input
- id="fileSizeLimit"
- name="fileSizeLimit"
- type="number"
- disabled={isFreeTier || !canUpdateStorageSettings}
- step={1}
- onKeyPress={(event) => {
- if (event.charCode < 48 || event.charCode > 57) {
- event.preventDefault()
- }
- }}
- />
- </div>
- <div className="col-span-4">
- <Listbox
- disabled={isFreeTier}
- value={selectedUnit}
- onChange={setSelectedUnit}
- >
- {Object.values(StorageSizeUnits).map((unit: string) => (
- <Listbox.Option
- key={unit}
+ <div className="col-span-4">
+ <FormField_Shadcn_
+ control={form.control}
+ name="unit"
+ render={({ field }) => (
+ <FormItem_Shadcn_>
+ <FormLabel_Shadcn_ className="hidden">Unit</FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Select_Shadcn_
disabled={isFreeTier}
- label={unit}
- value={unit}
+ value={field.value}
+ onValueChange={field.onChange}
>
- <div>{unit}</div>
- </Listbox.Option>
- ))}
- </Listbox>
- </div>
- </div>
- <p className="text-sm text-foreground-light">
- {selectedUnit !== StorageSizeUnits.BYTES &&
- `Equivalent to ${convertToBytes(
- values.fileSizeLimit,
- selectedUnit
- ).toLocaleString()} bytes. `}
- Maximum size in bytes of a file that can be uploaded is 5 GB (
- {formattedMaxSizeBytes}).
- </p>
+ <SelectTrigger_Shadcn_ className="w-[180px]">
+ <SelectValue_Shadcn_ placeholder="Choose a prefix">
+ {storageUnit}
+ </SelectValue_Shadcn_>
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ {Object.values(StorageSizeUnits).map((unit: string) => (
+ <SelectItem_Shadcn_
+ key={unit}
+ disabled={isFreeTier}
+ value={unit}
+ >
+ {unit}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
</div>
</div>
+ <p className="text-sm text-foreground-light">
+ {storageUnit !== StorageSizeUnits.BYTES &&
+ `Equivalent to ${convertToBytes(
+ limit,
+ storageUnit
+ ).toLocaleString()} bytes. `}
+ Maximum size in bytes of a file that can be uploaded is 5 GB (
+ {formattedMaxSizeBytes}).
+ </p>
</div>
- {isFreeTier && (
- <div className="px-6 pb-6">
- <UpgradeToPro
- icon={<IconClock size="large" />}
- organizationSlug={organizationSlug ?? ''}
- primaryText="Free Plan has a fixed upload file size limit of 50 MB."
- projectRef={projectRef ?? ''}
- secondaryText="Upgrade to the Pro plan for a configurable upload file size limit of up to 5 GB."
- />
- </div>
+ </div>
+ </div>
+ {isFreeTier && (
+ <div className="px-6 pb-6">
+ <UpgradeToPro
+ icon={<Clock size="large" />}
+ organizationSlug={organizationSlug ?? ''}
+ primaryText="Free Plan has a fixed upload file size limit of 50 MB."
+ projectRef={projectRef ?? ''}
+ secondaryText="Upgrade to the Pro plan for a configurable upload file size limit of up to 5 GB."
+ />
+ </div>
+ )}
+ <div className="border-t border-overlay" />
+ <div className="flex justify-between px-8 py-4">
+ <div className="flex items-center justify-between w-full gap-2">
+ {!canUpdateStorageSettings ? (
+ <p className="text-sm text-foreground-light">
+ You need additional permissions to update storage settings
+ </p>
+ ) : (
+ <div />
)}
- <div className="border-t border-overlay" />
- <div className="flex justify-between px-8 py-4">
- <div className="flex items-center justify-between w-full gap-2">
- {!canUpdateStorageSettings ? (
- <p className="text-sm text-foreground-light">
- You need additional permissions to update storage settings
- </p>
- ) : (
- <div />
- )}
- <div className="flex gap-2">
- <Button
- type="default"
- htmlType="reset"
- onClick={() => handleReset()}
- disabled={isUpdating || (!hasChanges && hasChanges !== undefined)}
- >
- Cancel
- </Button>
- <Button
- type="primary"
- htmlType="submit"
- loading={isUpdating}
- disabled={
- !canUpdateStorageSettings ||
- isUpdating ||
- (!hasChanges && hasChanges !== undefined)
- }
- >
- Save
- </Button>
- </div>
- </div>
+ <div className="flex gap-2">
+ <Button
+ type="default"
+ htmlType="reset"
+ onClick={() => form.reset()}
+ disabled={isUpdating}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ htmlType="submit"
+ loading={isUpdating}
+ disabled={!canUpdateStorageSettings || isUpdating}
+ >
+ Save
+ </Button>
</div>
</div>
- )}
- </>
- )
- }}
- </Form>
+ </div>
+ </div>
+ </form>
+ )}
+ </Form_Shadcn_>
</div>
)
}
diff --git a/packages/ui/src/components/Listbox/Listbox2.tsx b/packages/ui/src/components/Listbox/Listbox2.tsx
index 98b9f3dac64..348c497acb9 100644
--- a/packages/ui/src/components/Listbox/Listbox2.tsx
+++ b/packages/ui/src/components/Listbox/Listbox2.tsx
@@ -12,6 +12,7 @@ import { cn } from '../../lib/utils/cn'
import { useFormContext } from '../Form/FormContext'
import { IconCheck } from '../Icon/icons/IconCheck'
import { SelectContext } from './SelectContext'
+import { Select_Shadcn_ } from 'ui'
export interface Props extends Omit<React.InputHTMLAttributes<HTMLButtonElement>, 'size'> {
className?: string