Skip to content

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

20.0 KB
Raw Blame
import { useFeatureFlags, useParams } from 'common'
import { EarthIcon, Loader2Icon } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { UseFormReturn } from 'react-hook-form'
import type { CloudProvider } from 'shared-data'
import {
  Badge,
  cn,
  FormControl,
  FormField,
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
  useWatch,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'

import { CreateProjectForm } from './ProjectCreation.schema'
import {
  AUTO_REGION_VALUE,
  filterHighAvailabilityRegions,
  getAvailableRegions,
  getHighAvailabilityRegionCode,
} from './ProjectCreation.utils'
import { ProjectCreationStatusAdmonition } from './ProjectCreationStatusAdmonition'
import { getRegionRestrictionCopy, SELECT_DIFFERENT_REGION } from './RegionSelector.utils'
import { useRegionRestriction } from './useRegionRestriction'
import { AlertError } from '@/components/ui/AlertError'
import { InlineLink, InlineLinkClassName } from '@/components/ui/InlineLink'
import Panel from '@/components/ui/Panel'
import { RegionFlag } from '@/components/ui/RegionFlag'
import { useDefaultRegionQuery } from '@/data/misc/get-default-region-query'
import { useOrganizationAvailableRegionsQuery } from '@/data/organizations/organization-available-regions-query'
import type { DesiredInstanceSize } from '@/data/projects/new-project.constants'
import { DOCS_URL } from '@/lib/constants'
import { useTrack } from '@/lib/telemetry/track'

interface RegionSelectorProps {
  form: UseFormReturn<CreateProjectForm>
  hasSelectedOrganization: boolean
  instanceSize?: DesiredInstanceSize
  layout?: 'vertical' | 'horizontal'
  /** Hides specific regions and shows an upgrade prompt in their place */
  showGeneralRegionsOnly?: boolean
  isLoading?: boolean
  /** Specific regions collapse behind the "Need a specific region?" link only for free-plan orgs */
  isFreePlan: boolean
}

// [Joshen] Let's use a library to maintain the flag SVGs in the future
// I tried using https://flagpack.xyz/docs/development/react/ but couldn't get it to render
// ^ can try again next time

// Map backend region names to user-friendly display names
const getDisplayNameForSmartRegion = (name: string): string => {
  if (name === 'APAC') {
    return 'Asia-Pacific'
  }
  return name
}

const isLocal = process.env.NEXT_PUBLIC_ENVIRONMENT === 'local'

const BestAvailableRegionIcon = () => (
  <div className="w-5 h-4 border border-brand-500 rounded-xs bg-brand-300 flex items-center justify-center">
    <EarthIcon size={10} className="text-brand" />
  </div>
)

export const RegionSelector = ({
  form,
  hasSelectedOrganization,
  instanceSize,
  layout = 'horizontal',
  showGeneralRegionsOnly = false,
  isLoading: isParentLoading = false,
  isFreePlan,
}: RegionSelectorProps) => {
  const { slug } = useParams()
  const track = useTrack()
  const cloudProvider = form.getValues('cloudProvider') as CloudProvider
  const highAvailability = useWatch({ control: form.control, name: 'highAvailability' })
  const dbRegion = useWatch({ control: form.control, name: 'dbRegion' })
  const highAvailabilityRegionCode = getHighAvailabilityRegionCode()
  const hideSpecificRegions = showGeneralRegionsOnly && !highAvailability

  const { hasLoaded: flagsLoaded } = useFeatureFlags()
  const smartRegionEnabled = cloudProvider !== 'AWS_NIMBUS'
  const isSpecificRegionsLinkEnabled = isFreePlan && !hideSpecificRegions

  const { getRegionRestriction } = useRegionRestriction()

  const { isPending: isLoadingDefaultRegion } = useDefaultRegionQuery(
    { cloudProvider },
    { enabled: flagsLoaded && !smartRegionEnabled }
  )

  const {
    data: availableRegionsData,
    isPending: isLoadingAvailableRegions,
    isError: isErrorAvailableRegions,
    error: errorAvailableRegions,
  } = useOrganizationAvailableRegionsQuery(
    { slug, cloudProvider, desiredInstanceSize: instanceSize, highAvailability },
    {
      enabled: smartRegionEnabled && hasSelectedOrganization,
      staleTime: 1000 * 60 * 5,
    }
  )

  const allSmartRegions = availableRegionsData?.all.smartGroup ?? []
  const allRegions = availableRegionsData?.all.specific ?? []
  const restrictHighAvailabilityRegion =
    highAvailability && !isLocal && highAvailabilityRegionCode !== undefined
  const smartRegions = highAvailability ? [] : allSmartRegions

  const hasAutoOption = !highAvailability && availableRegionsData?.all.auto !== undefined
  const isAutoRecommended =
    hasAutoOption && availableRegionsData?.recommendations.auto !== undefined

  // Auto takes precedence, so the other recommendations are ignored while it's recommended
  const recommendedSmartRegions = new Set(
    isAutoRecommended
      ? []
      : [availableRegionsData?.recommendations.smartGroup?.code].filter(Boolean)
  )

  const recommendedSpecificRegions = new Set(
    isAutoRecommended
      ? []
      : availableRegionsData?.recommendations.specific?.map((region) => region.code)
  )

  const availableRegions = getAvailableRegions(cloudProvider)
  const regionsArray = Object.entries(availableRegions).map(([_key, value]) => {
    return {
      code: value.code,
      name: value.displayName,
      provider: cloudProvider,
      status: undefined,
    }
  })

  const unfilteredRegionOptions = smartRegionEnabled ? allRegions : regionsArray
  const regionOptions = filterHighAvailabilityRegions(
    [...unfilteredRegionOptions],
    highAvailability
  )
  const regionOptionsWithRestriction = regionOptions.map((region) => ({
    ...region,
    restriction: getRegionRestriction(region),
  }))
  const isLoading =
    isParentLoading || (smartRegionEnabled ? isLoadingAvailableRegions : isLoadingDefaultRegion)

  const isLocalEnvironment = process.env.NEXT_PUBLIC_ENVIRONMENT === 'local'
  const showNonProdFields = isLocalEnvironment || process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'

  const allSelectableRegions = [...smartRegions, ...regionOptions]

  const hasGeneralRegions = smartRegionEnabled && !highAvailability
  const isSpecificRegionSelected = regionOptions.some((region) => region.name === dbRegion)
  const [isOpen, setIsOpen] = useState(false)
  const [hasRevealedSpecificRegions, setHasRevealedSpecificRegions] = useState(false)
  const isSpecificRegionsCollapsedBehindLink =
    isSpecificRegionsLinkEnabled &&
    hasGeneralRegions &&
    !hasRevealedSpecificRegions &&
    !isSpecificRegionSelected
  const showSpecificRegions = !isSpecificRegionsCollapsedBehindLink && !hideSpecificRegions

  const handleRevealSpecificRegions = () => {
    track('project_creation_specific_region_link_clicked')
    setHasRevealedSpecificRegions(true)
    setIsOpen(true)
  }

  const lastValidRegionRef = useRef<string | undefined>(undefined)
  useEffect(() => {
    if (allSelectableRegions.length === 0) return
    const isRegionAvailable = (name: string | undefined) =>
      !!name &&
      ((hasAutoOption && name === AUTO_REGION_VALUE) ||
        allSelectableRegions.some((region) => region.name === name))

    if (isRegionAvailable(dbRegion)) {
      lastValidRegionRef.current = dbRegion
      return
    }

    const lastValidRegion = lastValidRegionRef.current
    if (lastValidRegion !== undefined && isRegionAvailable(lastValidRegion)) {
      form.setValue('dbRegion', lastValidRegion)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dbRegion, form])

  if (isErrorAvailableRegions) {
    return <AlertError subject="Error loading available regions" error={errorAvailableRegions} />
  }

  return (
    <Panel.Content>
      <FormField
        control={form.control}
        name="dbRegion"
        render={({ field }) => {
          const selectedRegion = allSelectableRegions.find((region) => {
            return !!region.name && region.name === dbRegion
          })

          const isAutoSelected = hasAutoOption && dbRegion === AUTO_REGION_VALUE
          const selectedRegionName = selectedRegion?.name
            ? getDisplayNameForSmartRegion(selectedRegion.name)
            : dbRegion
          const selectedRegionLabel = isAutoSelected ? 'Auto' : selectedRegionName
          const selectedRestriction = regionOptionsWithRestriction.find(
            (region) => region.name === dbRegion
          )?.restriction
          const selectedRestrictionCopy =
            selectedRestriction !== undefined
              ? getRegionRestrictionCopy(selectedRestriction)
              : undefined
          const triggerLabel = isLoading ? 'Loading available regions...' : selectedRegionLabel

          return (
            <>
              <FormItemLayout
                id="region"
                layout={layout}
                label="Region"
                description={
                  restrictHighAvailabilityRegion ? (
                    <div className="text-warning">
                      High Availability projects are currently limited to{' '}
                      {regionOptions[0]?.name ?? highAvailabilityRegionCode}.
                    </div>
                  ) : showNonProdFields ? (
                    <div className="text-warning">
                      <p>Only these regions are supported for local/staging projects:</p>
                      <ul className="list-disc list-inside mt-1">
                        <li>East US (North Virginia)</li>
                        <li>Central EU (Frankfurt)</li>
                        <li>Southeast Asia (Singapore)</li>
                      </ul>
                      {isLocalEnvironment && (
                        <p className="mt-1">
                          Use Central EU (Frankfurt) unless you're on a personal dev stack.
                        </p>
                      )}
                    </div>
                  ) : undefined
                }
              >
                <div className="flex flex-col items-start gap-y-1">
                  <FormControl>
                    <Select
                      open={isSpecificRegionsLinkEnabled ? isOpen : undefined}
                      onOpenChange={isSpecificRegionsLinkEnabled ? setIsOpen : undefined}
                      value={dbRegion}
                      onValueChange={(value) => {
                        if (value === '') return
                        field.onChange(value)
                      }}
                      disabled={isLoading}
                    >
                      <SelectTrigger
                        ref={field.ref}
                        id="region"
                        className="[&>:nth-child(1)]:w-full [&>:nth-child(1)]:flex [&>:nth-child(1)]:items-start"
                      >
                        <SelectValue
                          placeholder={
                            isLoading
                              ? 'Loading available regions...'
                              : 'Select a region for your project..'
                          }
                        >
                          {!!dbRegion && (
                            <div className="flex items-center gap-x-3">
                              {isLoading && <Loader2Icon size={14} className="animate-spin" />}
                              {isAutoSelected && <BestAvailableRegionIcon />}
                              {selectedRegion?.code && (
                                <RegionFlag className="w-5" region={selectedRegion.code} />
                              )}
                              <span className="text-foreground">{triggerLabel}</span>
                            </div>
                          )}
                        </SelectValue>
                      </SelectTrigger>
                      <SelectContent>
                        {hasAutoOption && (
                          <>
                            <SelectGroup>
                              <SelectLabel>Recommendation</SelectLabel>
                              <SelectItem
                                value={AUTO_REGION_VALUE}
                                className="w-full [&>:nth-child(2)]:w-full"
                              >
                                <div className="flex flex-row items-center justify-between w-full">
                                  <div className="flex items-center gap-x-3">
                                    <BestAvailableRegionIcon />
                                    <span className="text-foreground">Auto</span>
                                  </div>
                                  {isAutoRecommended && (
                                    <Badge variant="success" className="mr-1">
                                      Recommended
                                    </Badge>
                                  )}
                                </div>
                              </SelectItem>
                            </SelectGroup>
                            <SelectSeparator />
                          </>
                        )}
                        {hasGeneralRegions && (
                          <>
                            <SelectGroup>
                              <SelectLabel>General regions</SelectLabel>
                              {smartRegions.map((value) => {
                                return (
                                  <SelectItem
                                    key={value.code}
                                    value={value.name}
                                    className="w-full [&>:nth-child(2)]:w-full"
                                  >
                                    <div className="flex flex-row items-center justify-between w-full">
                                      <div className="flex items-center gap-x-3">
                                        <RegionFlag className="w-5" region={value.code} />
                                        <span className="text-foreground">
                                          {getDisplayNameForSmartRegion(value.name)}
                                        </span>
                                      </div>

                                      <div>
                                        {recommendedSmartRegions.has(value.code) && (
                                          <Badge variant="success" className="mr-1">
                                            Recommended
                                          </Badge>
                                        )}
                                      </div>
                                    </div>
                                  </SelectItem>
                                )
                              })}
                            </SelectGroup>
                            {showSpecificRegions && <SelectSeparator />}
                          </>
                        )}

                        {showSpecificRegions && (
                          <SelectGroup>
                            <SelectLabel>
                              {highAvailability ? 'High Availability Regions' : 'Specific regions'}
                            </SelectLabel>
                            {regionOptionsWithRestriction.map((value) => {
                              const restrictionCopy =
                                value.restriction !== undefined
                                  ? getRegionRestrictionCopy(value.restriction)
                                  : undefined
                              return (
                                <SelectItem
                                  key={value.code}
                                  value={value.name}
                                  className={cn(
                                    'w-full [&>:nth-child(2)]:w-full',
                                    restrictionCopy !== undefined && 'pointer-events-auto!'
                                  )}
                                >
                                  <div className="flex flex-row items-center justify-between w-full gap-x-2">
                                    <div className="flex items-center gap-x-3">
                                      <RegionFlag className="w-5" region={value.code} />
                                      <div className="flex items-center gap-x-2">
                                        <span className="text-foreground">{value.name}</span>
                                        <span className="text-xs text-foreground-lighter font-mono">
                                          {value.code}
                                        </span>
                                      </div>
                                    </div>

                                    {recommendedSpecificRegions.has(value.code) && (
                                      <Badge variant="success" className="mr-1">
                                        Recommended
                                      </Badge>
                                    )}

                                    {restrictionCopy !== undefined && (
                                      <Tooltip>
                                        <TooltipTrigger>
                                          <Badge variant="warning" className="mr-1">
                                            {restrictionCopy.badge}
                                          </Badge>
                                        </TooltipTrigger>
                                        <TooltipContent>{restrictionCopy.tooltip}</TooltipContent>
                                      </Tooltip>
                                    )}
                                  </div>
                                </SelectItem>
                              )
                            })}
                          </SelectGroup>
                        )}

                        {hideSpecificRegions && (
                          <>
                            <SelectSeparator />
                            <div
                              className="px-3 py-2.5 text-xs text-foreground-light"
                              onPointerDown={(e) => e.stopPropagation()}
                            >
                              <InlineLink
                                href={`/org/${slug ?? '_'}/billing?panel=subscriptionPlan&source=freeTierGeneralRegionSelector`}
                                onClick={() => track('free_tier_general_region_upgrade_clicked')}
                              >
                                Upgrade to Pro
                              </InlineLink>{' '}
                              to choose a{' '}
                              <InlineLink
                                href={`${DOCS_URL}/guides/platform/regions`}
                                onClick={() => track('free_tier_general_region_docs_link_clicked')}
                              >
                                specific region
                              </InlineLink>
                              .
                            </div>
                          </>
                        )}
                      </SelectContent>
                    </Select>
                  </FormControl>

                  {isSpecificRegionsCollapsedBehindLink && (
                    <p className="text-sm text-foreground-lighter">
                      <button
                        type="button"
                        tabIndex={0}
                        className={InlineLinkClassName}
                        onClick={handleRevealSpecificRegions}
                      >
                        Need a specific region?
                      </button>
                    </p>
                  )}
                </div>
              </FormItemLayout>

              <ProjectCreationStatusAdmonition selectedRegionCode={selectedRegion?.code} />

              {selectedRestrictionCopy !== undefined && (
                <FormItemLayout layout="horizontal" isReactForm={false}>
                  <Admonition
                    type="warning"
                    title={selectedRestrictionCopy.title}
                    description={`${selectedRestrictionCopy.notice} ${SELECT_DIFFERENT_REGION}`}
                    className="mt-3"
                  />
                </FormItemLayout>
              )}
            </>
          )
        }}
      />
    </Panel.Content>
  )
}