Skip to content

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

6.0 KB
Raw Blame
import { AnimatePresence } from 'motion/react'
import { useWatch, type UseFormReturn } from 'react-hook-form'
import { Badge, DialogSection, DialogSectionSeparator, FormControl, FormField, Switch } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'

import { type BucketFormValues } from '../FilesBucket.schema'
import {
  getRetentionTightening,
  RETENTION_TIGHTENING_DESCRIPTION,
  toNullableNumber,
} from './BucketVersioningFields.utils'
import { LifecyclePolicySection } from './LifecyclePolicySection'
import type { BucketVersioningState } from '@/components/interfaces/Storage/StorageVersioning.constants'
import { FormSectionCollapse } from '@/components/ui/FormSectionCollapse'

interface BucketVersioningFieldsProps {
  form: UseFormReturn<BucketFormValues>
  initialVersioningState?: BucketVersioningState
  initialRetentionDays?: number | null
  initialMaxVersions?: number | null
  isPublicBucket?: boolean
  /** The bucket's stored lifecycle policy is still being fetched. */
  isLoadingPolicy?: boolean
  /** The stored policy holds rules these fields cannot represent, so it is left alone. */
  isUnsupportedPolicy?: boolean
  /** The bucket's stored lifecycle policy could not be fetched. */
  policyError?: { message: string } | null
}

export const BucketVersioningFields = ({
  form,
  initialVersioningState = 'disabled',
  initialRetentionDays,
  initialMaxVersions,
  isPublicBucket = false,
  isLoadingPolicy = false,
  isUnsupportedPolicy = false,
  policyError,
}: BucketVersioningFieldsProps) => {
  const { control } = form

  const isVersioningEnabled = useWatch({ control, name: 'enable_versioning' })
  const retentionDays = useWatch({ control, name: 'version_expiry_days' })
  const maxVersions = useWatch({ control, name: 'max_noncurrent_versions' })
  const expirationMode = useWatch({ control, name: 'expiration_mode' })

  // Turning the switch off suspends rather than disables, so this is a heads-up.
  const isSuspending = !isVersioningEnabled && initialVersioningState !== 'disabled'

  // A suspended bucket keeps expiring the versions it still holds, so the policy stays editable.
  const canEditLifecycle = isVersioningEnabled || initialVersioningState === 'suspended'

  // A bound nobody has read, or that the fields only partly represent, can't be compared against.
  const hasKnownBounds = !isLoadingPolicy && !isUnsupportedPolicy && !policyError

  const tightening = getRetentionTightening({
    initialVersioningState,
    isVersioningEnabled,
    initialRetentionDays: hasKnownBounds ? initialRetentionDays : undefined,
    initialMaxVersions: hasKnownBounds ? initialMaxVersions : undefined,
    nextRetentionDays: toNullableNumber(retentionDays),
    nextMaxVersions: toNullableNumber(maxVersions),
  })

  const hasDays = typeof retentionDays === 'number' && retentionDays > 0
  const hasVersions = typeof maxVersions === 'number' && maxVersions > 0

  return (
    <>
      <DialogSectionSeparator />

      <DialogSection className="space-y-3">
        <FormField
          name="enable_versioning"
          control={control}
          render={({ field }) => (
            <FormItemLayout
              hideMessage
              name="enable_versioning"
              label={
                <span className="flex items-center gap-x-2">
                  Object versioning
                  <Badge variant="warning">Private Alpha</Badge>
                </span>
              }
              description="Retains previous versions of an object when it is overwritten or deleted"
              layout="flex"
            >
              <FormControl>
                <Switch
                  id="enable_versioning"
                  aria-label="Object versioning"
                  size="large"
                  checked={field.value}
                  onCheckedChange={field.onChange}
                />
              </FormControl>
            </FormItemLayout>
          )}
        />

        <AnimatePresence initial={false}>
          {isSuspending && (
            <FormSectionCollapse key="suspension-notice">
              <Admonition
                type="default"
                title={
                  initialVersioningState === 'enabled'
                    ? 'Saving will suspend versioning'
                    : 'Versioning is suspended on this bucket'
                }
                description="Existing versions stay put. Re-enable versioning at any time."
              />
            </FormSectionCollapse>
          )}

          {isVersioningEnabled && isPublicBucket && (
            <FormSectionCollapse key="public-bucket-warning">
              <Admonition
                type="warning"
                title="A public bucket serves every version"
                description={
                  <>
                    Anyone with a version ID can fetch a noncurrent version of a public object. To
                    hide noncurrent versions, add an RLS policy on <code>storage.objects</code> that
                    filters on <code>metadata-&gt;&gt;'isCurrent' = 'true'</code>.
                  </>
                }
              />
            </FormSectionCollapse>
          )}

          {isVersioningEnabled && tightening !== 'none' && (
            <FormSectionCollapse key="tightening-warning">
              <Admonition
                type="warning"
                title="Tightening retention expires some versions"
                description={RETENTION_TIGHTENING_DESCRIPTION[tightening]}
              />
            </FormSectionCollapse>
          )}

          {canEditLifecycle && (
            <FormSectionCollapse key="lifecycle-policy">
              <LifecyclePolicySection
                form={form}
                hasDays={hasDays}
                hasVersions={hasVersions}
                mode={expirationMode}
                isLoading={isLoadingPolicy}
                isUnsupported={isUnsupportedPolicy}
                error={policyError}
              />
            </FormSectionCollapse>
          )}
        </AnimatePresence>
      </DialogSection>
    </>
  )
}