The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
[Dashboard] Chore/refactor new project form (#26997)
Jonathan Summers-Muir330ae6e407fa
diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.tsindex 35f51a1f92e..806557652b0 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts@@ -3,9 +3,7 @@ import { pluckObjectFields } from 'lib/helpers'export function getAvailableRegions(cloudProvider: CloudProvider): Region {if (cloudProvider === 'AWS') {- return process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'- ? pluckObjectFields(AWS_REGIONS, ['SOUTHEAST_ASIA'])- : AWS_REGIONS+ return AWS_REGIONS} else if (cloudProvider === 'FLY') {return FLY_REGIONS}diff --git a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsxindex dc0e81b0deb..1665de5ee8d 100644--- a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx@@ -1,74 +1,67 @@+import { useDefaultRegionQuery } from 'data/misc/get-default-region-query'import { CloudProvider, PROVIDERS } from 'lib/constants'import { useRouter } from 'next/router'-import { useEffect } from 'react'-import { Listbox } from 'ui'--import { useDefaultRegionQuery } from 'data/misc/get-default-region-query'+import { ControllerRenderProps, UseFormReturn } from 'react-hook-form'+import {+ SelectContent_Shadcn_,+ SelectGroup_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ SelectValue_Shadcn_,+ Select_Shadcn_,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { getAvailableRegions } from './ProjectCreation.utils'+import { useEffect } from 'react'interface RegionSelectorProps {cloudProvider: CloudProvider- selectedRegion: string- onSelectRegion: (value: string) => void+ field: ControllerRenderProps<any, 'dbRegion'>+ form: UseFormReturn<any>}-export const RegionSelector = ({- cloudProvider,- selectedRegion,- onSelectRegion,-}: RegionSelectorProps) => {+export const RegionSelector = ({ cloudProvider, field, form }: RegionSelectorProps) => {const router = useRouter()const availableRegions = getAvailableRegions(PROVIDERS[cloudProvider].id)- const {- data: region,- isSuccess,- isError,- } = useDefaultRegionQuery(- { cloudProvider },- { refetchOnMount: false, refetchOnWindowFocus: false, refetchInterval: false }- )- useEffect(() => {- // only pick a region if one hasn't already been selected- if (isSuccess && region && !selectedRegion) {- onSelectRegion(region)- } else if (isError && !selectedRegion) {- // if an error happened, and the user haven't selected a region, just select the default one for him- onSelectRegion(PROVIDERS[cloudProvider].default_region)- }- }, [cloudProvider, isError, isSuccess, region, selectedRegion])+ const { isLoading: isLoadingDefaultRegion } = useDefaultRegionQuery({+ cloudProvider,+ })return (- <Listbox+ <FormItemLayoutlayout="horizontal"label="Region"- type="select"- value={selectedRegion}- onChange={(value) => onSelectRegion(value)}- descriptionText="Select the region closest to your users for the best performance."+ description="Select the region closest to your users for the best performance.">- <Listbox.Option disabled key="empty" label="---" value="">- <span className="text-foreground">Select a region for your project</span>- </Listbox.Option>- {Object.keys(availableRegions).map((option: string, i) => {- const label = Object.values(availableRegions)[i] as string- return (- <Listbox.Option- key={option}- label={label}- value={label}- addOnBefore={() => (- <img- alt="region icon"- className="w-5 rounded-sm"- src={`${router.basePath}/img/regions/${Object.keys(availableRegions)[i]}.svg`}- />- )}- >- <span className="text-foreground">{label}</span>- </Listbox.Option>- )- })}- </Listbox>+ <Select_Shadcn_+ value={field.value}+ onValueChange={field.onChange}+ disabled={isLoadingDefaultRegion}+ >+ <SelectTrigger_Shadcn_>+ <SelectValue_Shadcn_ placeholder="Select a region for your project.." />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {Object.keys(availableRegions).map((option: string, i) => {+ const label = Object.values(availableRegions)[i] as string+ return (+ <SelectItem_Shadcn_ key={option} value={label}>+ <div className="flex items-center gap-3">+ <img+ alt="region icon"+ className="w-5 rounded-sm"+ src={`${router.basePath}/img/regions/${Object.keys(availableRegions)[i]}.svg`}+ />+ <span className="text-foreground">{label}</span>+ </div>+ </SelectItem_Shadcn_>+ )+ })}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormItemLayout>)}diff --git a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsxindex 836dde124d4..171494f2053 100644--- a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx+++ b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx@@ -1,5 +1,12 @@import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { indexOf } from 'lodash'+import Link from 'next/link'+import { useEffect } from 'react'+import { useForm } from 'react-hook-form'+import toast from 'react-hot-toast'+import { z } from 'zod'+import { useParams } from 'common'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import {@@ -11,15 +18,9 @@ import {} from 'components/ui/Forms'import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'import { useProjectPostgrestConfigUpdateMutation } from 'data/config/project-postgrest-config-update-mutation'-import { useDatabaseExtensionDisableMutation } from 'data/database-extensions/database-extension-disable-mutation'import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'import { useSchemasQuery } from 'data/database/schemas-query'import { useCheckPermissions } from 'hooks'-import { indexOf } from 'lodash'-import Link from 'next/link'-import { useEffect } from 'react'-import { useForm } from 'react-hook-form'-import toast from 'react-hot-toast'import {Admonition,AlertDescription_Shadcn_,@@ -37,7 +38,6 @@ import {Skeleton,Switch,} from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import {@@ -48,7 +48,6 @@ import {MultiSelectorList,MultiSelectorTrigger,} from 'ui-patterns/multi-select'-import { z } from 'zod'const formSchema = z.object({diff --git a/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx b/apps/studio/components/layouts/ProjectLayout/BuildingState.tsxindex 84e5429d32b..78777a23cc8 100644--- a/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx@@ -13,6 +13,7 @@ import { invalidateProjectsQuery } from 'data/projects/projects-query'import { useSelectedProject } from 'hooks'import { getWithTimeout } from 'lib/common/fetch'import { API_URL, PROJECT_STATUS } from 'lib/constants'+import { Loader2 } from 'lucide-react'const BuildingState = () => {const { ref } = useParams()@@ -53,9 +54,9 @@ const BuildingState = () => {<div className=" flex flex-col gap-4"><div className="flex items-center space-x-3"><h1 className="text-3xl text-foreground">{project?.name}</h1>- <Badge variant="brand">+ <Badge variant="default" className="bg-surface-100 bg-opacity-100"><div className="flex items-center gap-2">- <IconLoader className="animate-spin" size={12} />+ <Loader2 className="animate-spin" size={12} /><span>{project.status === PROJECT_STATUS.UNKNOWN? 'Initiating project set up'diff --git a/apps/studio/components/ui/PasswordStrengthBar.tsx b/apps/studio/components/ui/PasswordStrengthBar.tsxindex 4ee9414cdb3..45fdc93b2c7 100644--- a/apps/studio/components/ui/PasswordStrengthBar.tsx+++ b/apps/studio/components/ui/PasswordStrengthBar.tsx@@ -22,13 +22,13 @@ const PasswordStrengthBar = ({aria-valuenow={(PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]}aria-valuetext={(PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]}role="progressbar"- className="mb-2 overflow-hidden transition-all border rounded bg-studio"+ className="mb-2 overflow-hidden transition-all border rounded bg-200 w-full"><divstyle={{width: (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore],}}- className={`relative h-2 w-full ${+ className={`relative h-1 w-full ${(PASSWORD_STRENGTH_COLOR as any)[passwordStrengthScore]} transition-all duration-500 ease-out shadow-inner`}></div>diff --git a/apps/studio/data/misc/get-default-region-query.ts b/apps/studio/data/misc/get-default-region-query.tsindex 31b0fbd20d5..6880f31e58b 100644--- a/apps/studio/data/misc/get-default-region-query.ts+++ b/apps/studio/data/misc/get-default-region-query.ts@@ -8,12 +8,12 @@ import {AWS_REGIONS_COORDINATES,FLY_REGIONS_COORDINATES,} from 'components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants'-import { AWS_REGIONS, FLY_REGIONS } from 'lib/constants'+import { AWS_REGIONS, CloudProvider, FLY_REGIONS } from 'lib/constants'const RESTRICTED_POOL = ['WEST_US', 'CENTRAL_EU', 'SOUTHEAST_ASIA']export type DefaultRegionVariables = {- cloudProvider?: 'AWS' | 'FLY'+ cloudProvider?: CloudProvideruseRestrictedPool?: boolean}diff --git a/apps/studio/lib/constants/infrastructure.ts b/apps/studio/lib/constants/infrastructure.tsindex 0c7b996f600..a8f3212bd34 100644--- a/apps/studio/lib/constants/infrastructure.ts+++ b/apps/studio/lib/constants/infrastructure.ts@@ -50,8 +50,7 @@ export const PRICING_TIER_PRODUCT_IDS = {ENTERPRISE: 'tier_enterprise',}-export const DEFAULT_PROVIDER: CloudProvider =- process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod' ? 'FLY' : 'AWS'+export const DEFAULT_PROVIDER: CloudProvider = 'AWS'export const PROVIDERS = {FLY: {diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsxindex 5389d65c83e..0b8ab1f307f 100644--- a/apps/studio/pages/new/[slug].tsx+++ b/apps/studio/pages/new/[slug].tsx@@ -1,34 +1,25 @@+import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'-import generator from 'generate-password-browser'-import { debounce } from 'lodash'-import { ExternalLink, Users } from 'lucide-react'-import Link from 'next/link'-import { useRouter } from 'next/router'-import { PropsWithChildren, useEffect, useRef, useState } from 'react'-import toast from 'react-hot-toast'-+import { components } from 'api-types'import { useParams } from 'common'import {FreeProjectLimitWarning,NotOrganizationOwnerWarning,} from 'components/interfaces/Organization/NewProject'-import {- AVAILABLE_SIZES,- INSTANCE_SIZE_SPECS,-} from 'components/interfaces/ProjectCreation/ProjectCreation.constants'import { RegionSelector } from 'components/interfaces/ProjectCreation/RegionSelector'import { WizardLayoutWithoutAuth } from 'components/layouts/WizardLayout'import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'import Panel from 'components/ui/Panel'import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'+import { useDefaultRegionQuery } from 'data/misc/get-default-region-query'import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'import { useOrganizationsQuery } from 'data/organizations/organizations-query'import {- DbInstanceSize,ProjectCreateVariables,useProjectCreateMutation,} from 'data/projects/project-create-mutation'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import generator from 'generate-password-browser'import { useCheckPermissions, useFlag, withAuth } from 'hooks'import {CloudProvider,@@ -37,8 +28,33 @@ import {PROVIDERS,} from 'lib/constants'import { passwordStrength } from 'lib/helpers'+import { debounce } from 'lodash'+import { ExternalLink } from 'lucide-react'+import Link from 'next/link'+import { useRouter } from 'next/router'+import { PropsWithChildren, useEffect, useRef, useState } from 'react'+import { useForm } from 'react-hook-form'+import toast from 'react-hot-toast'import type { NextPageWithLayout } from 'types'-import { Badge, Button, Input, Listbox } from 'ui'+import {+ Badge,+ Button,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Form_Shadcn_,+ Input_Shadcn_,+ SelectContent_Shadcn_,+ SelectGroup_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ SelectValue_Shadcn_,+ Select_Shadcn_,+} from 'ui'+import { Input } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { z } from 'zod'++type DesiredInstanceSize = components['schemas']['DesiredInstanceSize']const Wizard: NextPageWithLayout = () => {const router = useRouter()@@ -49,29 +65,24 @@ const Wizard: NextPageWithLayout = () => {const { data: membersExceededLimit, isLoading: isLoadingFreeProjectLimitCheck } =useFreeProjectLimitCheckQuery({ slug })- const [projectName, setProjectName] = useState('')- const [postgresVersion, setPostgresVersion] = useState('')- const [cloudProvider, setCloudProvider] = useState<CloudProvider>(PROVIDERS[DEFAULT_PROVIDER].id)-- const [dbPass, setDbPass] = useState('')- // Auto select region on staging/local for convenience as there's only one supported- const [dbRegion, setDbRegion] = useState(- ['staging', 'local'].includes(process.env.NEXT_PUBLIC_ENVIRONMENT ?? '')- ? PROVIDERS[cloudProvider].default_region- : ''- )const [passwordStrengthMessage, setPasswordStrengthMessage] = useState('')const [passwordStrengthWarning, setPasswordStrengthWarning] = useState('')- const [passwordStrengthScore, setPasswordStrengthScore] = useState(0)-- const [instanceSize, setInstanceSize] = useState<DbInstanceSize>('micro')const { data: organizations, isSuccess: isOrganizationsSuccess } = useOrganizationsQuery()const currentOrg = organizations?.find((o: any) => o.slug === slug)-const { data: orgSubscription } = useOrgSubscriptionQuery({orgSlug: slug,})+ const { data: defaultRegion, error: defaultRegionError } = useDefaultRegionQuery(+ {+ cloudProvider: PROVIDERS[DEFAULT_PROVIDER].id,+ },+ {+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchInterval: false,+ }+ )const {mutate: createProject,@@ -95,59 +106,181 @@ const Wizard: NextPageWithLayout = () => {const canCreateProject = isAdmin && !freePlanWithExceedingLimits- const canSubmit =- projectName !== '' &&- passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH &&- dbRegion !== undefined-const delayedCheckPasswordStrength = useRef(debounce((value) => checkPasswordStrength(value), 300)).current- function onProjectNameChange(e: any) {- e.target.value = e.target.value.replace(/\./g, '')- setProjectName(e.target.value)- }+ async function checkPasswordStrength(value: any) {+ const { message, warning, strength } = await passwordStrength(value)++ form.setValue('dbPassStrength', strength)+ form.trigger('dbPassStrength')+ form.trigger('dbPass')- function onDbPassChange(e: any) {- const value = e.target.value- setDbPass(value)- if (value == '') {- setPasswordStrengthScore(-1)- setPasswordStrengthMessage('')- } else delayedCheckPasswordStrength(value)+ setPasswordStrengthWarning(warning)+ setPasswordStrengthMessage(message)}- function onCloudProviderChange(cloudProviderId: CloudProvider) {- setCloudProvider(cloudProviderId)- // on local/staging quick-select the default region, don't wait for the cloudflare location- setDbRegion(- ['staging', 'local'].includes(process.env.NEXT_PUBLIC_ENVIRONMENT ?? '')- ? PROVIDERS[cloudProviderId].default_region- : ''- )+ const sizes: DesiredInstanceSize[] = [+ 'micro',+ 'small',+ 'medium',+ 'large',+ 'xlarge',+ '2xlarge',+ '4xlarge',+ '8xlarge',+ '12xlarge',+ '16xlarge',+ ]++ const instanceSizeSpecs: Record<+ DesiredInstanceSize,+ { label: string; ram: string; cpu: string; price: string }+ > = {+ micro: {+ label: 'Micro',+ ram: '1 GB',+ cpu: '2-core ARM',+ price: '$0.01344/hour (~$10/month)',+ },+ small: {+ label: 'Small',+ ram: '2 GB',+ cpu: '2-core ARM',+ price: '$0.0206/hour (~$15/month)',+ },+ medium: {+ label: 'Medium',+ ram: '4 GB',+ cpu: '2-core ARM',+ price: '$0.0822/hour (~$60/month)',+ },+ large: {+ label: 'Large',+ ram: '8 GB',+ cpu: '2-core ARM',+ price: '$0.1517/hour (~$110/month)',+ },+ xlarge: {+ label: 'XL',+ ram: '16 GB',+ cpu: '4-core ARM',+ price: '$0.2877/hour (~$210/month)',+ },+ '2xlarge': {+ label: '2XL',+ ram: '32 GB',+ cpu: '8-core ARM',+ price: '$0.562/hour (~$410/month)',+ },+ '4xlarge': {+ label: '4XL',+ ram: '64 GB',+ cpu: '16-core ARM',+ price: '$1.32/hour (~$960/month)',+ },+ '8xlarge': {+ label: '8XL',+ ram: '128 GB',+ cpu: '32-core ARM',+ price: '$2.562/hour (~$1,870/month)',+ },+ '12xlarge': {+ label: '12XL',+ ram: '192 GB',+ cpu: '48-core ARM',+ price: '$3.836/hour (~$2,800/month)',+ },+ '16xlarge': {+ label: '16XL',+ ram: '256 GB',+ cpu: '64-core ARM',+ price: '$5.12/hour (~$3,730/month)',+ },}- async function checkPasswordStrength(value: any) {- const { message, warning, strength } = await passwordStrength(value)- setPasswordStrengthScore(strength)- setPasswordStrengthWarning(warning)- setPasswordStrengthMessage(message)+ const FormSchema = z+ .object({+ organization: z.string({+ required_error: 'Please select an organization',+ }),+ projectName: z+ .string()+ .min(1, 'Please enter a project name.') // Required field check+ .min(3, 'Project name must be at least 3 characters long.') // Minimum length check+ .max(64, 'Project name must be no longer than 64 characters.'), // Maximum length check+ postgresVersion: z.string({+ required_error: 'Please enter a Postgres version.',+ }),+ dbRegion: z.string({+ required_error: 'Please select a region.',+ }),+ cloudProvider: z.string({+ required_error: 'Please select a cloud provider.',+ }),+ dbPassStrength: z.number(),+ dbPass: z+ .string({+ required_error: 'Please enter a database password.',+ })+ .min(1, 'Password is required.'),+ instanceSize: z.string(),+ })+ .superRefine(({ dbPassStrength }, refinementContext) => {+ if (dbPassStrength < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {+ refinementContext.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['dbPass'],+ message: passwordStrengthWarning || 'Password not secure enough',+ })+ }+ })++ const form = useForm<z.infer<typeof FormSchema>>({+ resolver: zodResolver(FormSchema),+ mode: 'onChange',+ defaultValues: {+ organization: slug,+ projectName: '',+ postgresVersion: '',+ cloudProvider: PROVIDERS[DEFAULT_PROVIDER].id,+ dbPass: '',+ dbPassStrength: 0,+ dbRegion: defaultRegion || undefined,+ instanceSize: sizes[0],+ },+ })++ // [Joshen] Refactor: DB Password could be a common component+ // used in multiple pages with repeated logic+ function generateStrongPassword() {+ const password = generator.generate({+ length: 16,+ numbers: true,+ uppercase: true,+ })++ form.setValue('dbPass', password)+ delayedCheckPasswordStrength(password)}- const onClickNext = async () => {+ const onClickNext = async (values: z.infer<typeof FormSchema>) => {if (!currentOrg) return console.error('Unable to retrieve current organization')+ const { cloudProvider, projectName, dbPass, dbRegion, postgresVersion, instanceSize } = values+const data: ProjectCreateVariables = {- cloudProvider,+ cloudProvider: cloudProvider,organizationId: currentOrg.id,- name: projectName.trim(),+ name: projectName,dbPass: dbPass,dbRegion: dbRegion,// gets ignored due to org billing subscription anywaydbPricingTierId: 'tier_free',// only set the instance size on pro+ plans. Free plans always use micro (nano in the future) size.- dbInstanceSize: orgSubscription?.plan.id === 'free' ? undefined : instanceSize,+ dbInstanceSize:+ orgSubscription?.plan.id === 'free' ? undefined : (instanceSize as DesiredInstanceSize),}if (postgresVersion) {if (!postgresVersion.match(/1[2-9]\..*/)) {@@ -164,301 +297,372 @@ const Wizard: NextPageWithLayout = () => {createProject(data)}- // [Joshen] Refactor: DB Password could be a common component- // used in multiple pages with repeated logic- function generateStrongPassword() {- const password = generator.generate({- length: 16,- numbers: true,- uppercase: true,- })-- setDbPass(password)- delayedCheckPasswordStrength(password)- }-useEffect(() => {- /*- * Handle no org- * redirect to new org route- */+ // Handle no org: redirect to new org routeif (isEmptyOrganizations) {router.push(`/new`)}}, [isEmptyOrganizations, router])useEffect(() => {- /*- * Redirect to first org if the slug doesn't match an org slug- * this is mainly to capture the /new/new-project url, which is redirected from database.new- */- if (isInvalidSlug && (organizations?.length ?? 0) > 0) {+ // [Joshen] Cause slug depends on router which doesnt load immediately on render+ // While the form data does load immediately+ if (slug) form.setValue('organization', slug)+ }, [slug])++ useEffect(() => {+ // Redirect to first org if the slug doesn't match an org slug+ // this is mainly to capture the /new/new-project url, which is redirected from database.new+ if (isInvalidSlug && isOrganizationsSuccess && (organizations?.length ?? 0) > 0) {router.push(`/new/${organizations?.[0].slug}`)}- }, [isInvalidSlug, organizations])+ }, [isInvalidSlug, isOrganizationsSuccess, organizations])++ useEffect(() => {+ if (form.getValues('dbRegion') === undefined && defaultRegion) {+ form.setValue('dbRegion', defaultRegion)+ }+ }, [defaultRegion])useEffect(() => {- // User added a new payment method- if (router.query.setup_intent && router.query.redirect_status) {- toast.success('Successfully added new payment method')+ if (defaultRegionError) {+ form.setValue('dbRegion', PROVIDERS[DEFAULT_PROVIDER].default_region)}- }, [router.query.redirect_status, router.query.setup_intent])+ }, [defaultRegionError])return (- <Panel- loading={!isOrganizationsSuccess || isLoadingFreeProjectLimitCheck}- title={- <div key="panel-title">- <h3>Create a new project</h3>- <p className="text-sm text-foreground-lighter">- Your project will have its own dedicated instance and full postgres database.- <br />- An API will be set up so you can easily interact with your new database.- <br />- </p>- </div>- }- footer={- <div key="panel-footer" className="flex items-center justify-between w-full">- <Button- type="default"- disabled={isCreatingNewProject || isSuccessNewProject}- onClick={() => router.push('/projects')}- >- Cancel- </Button>- <div className="items-center space-x-3">- {!projectCreationDisabled && (- <span className="text-xs text-foreground-lighter">- You can rename your project later- </span>- )}- <Button- onClick={onClickNext}- loading={isCreatingNewProject || isSuccessNewProject}- disabled={isCreatingNewProject || isSuccessNewProject || !canSubmit}- >- Create new project- </Button>- </div>- </div>- }- >- <>- {projectCreationDisabled ? (- <Panel.Content className="pb-8">- <DisabledWarningDueToIncident title="Project creation is currently disabled" />- </Panel.Content>- ) : (- <div className="divide-y divide-border-muted">- <Panel.Content className={['space-y-4'].join(' ')}>- {(organizations?.length ?? 0) > 0 && (- <Listbox- label="Organization"- layout="horizontal"- value={currentOrg?.slug}- onChange={(slug) => router.push(`/new/${slug}`)}+ <Form_Shadcn_ {...form}>+ <form onSubmit={form.handleSubmit(onClickNext)}>+ <Panel+ loading={!isOrganizationsSuccess || isLoadingFreeProjectLimitCheck}+ title={+ <div key="panel-title">+ <h3>Create a new project</h3>+ <p className="text-sm text-foreground-lighter">+ Your project will have its own dedicated instance and full postgres database.+ <br />+ An API will be set up so you can easily interact with your new database.+ <br />+ </p>+ </div>+ }+ footer={+ <div key="panel-footer" className="flex items-center justify-between w-full">+ <Button+ type="default"+ disabled={isCreatingNewProject || isSuccessNewProject}+ onClick={() => router.push('/projects')}+ >+ Cancel+ </Button>+ <div className="items-center space-x-3">+ {!projectCreationDisabled && (+ <span className="text-xs text-foreground-lighter">+ You can rename your project later+ </span>+ )}+ <Button+ htmlType="submit"+ loading={isCreatingNewProject || isSuccessNewProject}+ disabled={isCreatingNewProject || isSuccessNewProject}>- {organizations?.map((x: any) => (- <Listbox.Option- key={x.id}- label={x.name}- value={x.slug}- addOnBefore={() => <Users size={18} />}- >- {x.name}- </Listbox.Option>- ))}- </Listbox>- )}-- {!isAdmin && <NotOrganizationOwnerWarning />}- </Panel.Content>-- {canCreateProject && (- <>- <Panel.Content>- <Input- id="project-name"- layout="horizontal"- label="Name"- type="text"- placeholder="Project name"- value={projectName}- onChange={onProjectNameChange}- autoFocus+ Create new project+ </Button>+ </div>+ </div>+ }+ >+ <>+ {projectCreationDisabled ? (+ <Panel.Content className="pb-8">+ <DisabledWarningDueToIncident title="Project creation is currently disabled" />+ </Panel.Content>+ ) : (+ <div className="divide-y divide-border-muted">+ <Panel.Content className={['space-y-4'].join(' ')}>+ <FormField_Shadcn_+ control={form.control}+ name="organization"+ render={({ field }) => (+ <FormItemLayout label="Organization" layout="horizontal">+ {(organizations?.length ?? 0) > 0 && (+ <Select_Shadcn_+ onValueChange={(slug) => {+ field.onChange(slug)+ router.push(`/new/${slug}`)+ }}+ defaultValue={field.value}+ >+ <FormControl_Shadcn_>+ <SelectTrigger_Shadcn_>+ <SelectValue_Shadcn_ placeholder="Select an organization" />+ </SelectTrigger_Shadcn_>+ </FormControl_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {organizations?.map((x: any) => (+ <SelectItem_Shadcn_ key={x.id} value={x.slug}>+ {x.name}+ </SelectItem_Shadcn_>+ ))}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ )}+ </FormItemLayout>+ )}/>- </Panel.Content>- {showNonProdFields && (- <Panel.Content>- <Input- id="custom-postgres-version"- layout="horizontal"- label="Postgres Version"- autoComplete="off"- descriptionText={- <p>- Specify a custom version of Postgres (Defaults to the latest)- <br />- This is only applicable for local/staging projects- </p>- }- type="text"- placeholder="Postgres Version"- value={postgresVersion}- onChange={(event: any) => setPostgresVersion(event.target.value)}- />- </Panel.Content>- )}-- {cloudProviderEnabled && showNonProdFields && (- <Panel.Content>- <Listbox- layout="horizontal"- label="Cloud Provider"- type="select"- value={cloudProvider}- onChange={(value) => onCloudProviderChange(value)}- descriptionText="Cloud Provider (only for staging/local)"- >- {Object.values(PROVIDERS).map((providerObj) => {- const label = providerObj['name']- const value = providerObj['id']- return (- <Listbox.Option key={value} label={label} value={value}>- <span className="text-foreground">{label}</span>- </Listbox.Option>- )- })}- </Listbox>- </Panel.Content>- )}+ {!isAdmin && <NotOrganizationOwnerWarning />}+ </Panel.Content>- {orgSubscription?.plan.id !== 'free' && (- <Panel.Content>- <Listbox- layout="horizontal"- label={- <div className="space-y-4">- <span>Instance Size</span>-- <div className="flex flex-col space-y-2">- <Link- href="https://supabase.com/docs/guides/platform/compute-add-ons"- target="_blank"+ {canCreateProject && (+ <>+ <Panel.Content>+ <FormField_Shadcn_+ control={form.control}+ name="projectName"+ render={({ field }) => (+ <FormItemLayout label="Project name" layout="horizontal">+ <FormControl_Shadcn_>+ <Input_Shadcn_+ placeholder="Project name"+ {...field}+ onChange={(event) => {+ field.onChange(event.target.value.replace(/\./g, ''))+ }}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </Panel.Content>++ {showNonProdFields && (+ <Panel.Content>+ <FormField_Shadcn_+ control={form.control}+ name="postgresVersion"+ render={({ field }) => (+ <FormItemLayout+ label="Postgres version"+ layout="horizontal"+ description="Specify a custom version of Postgres (Defaults to the latest). This is only applicable for local/staging projects">- <div className="flex items-center space-x-2 opacity-75 hover:opacity-100 transition">- <p className="text-sm m-0">Compute Add-Ons</p>- <ExternalLink size={16} strokeWidth={1.5} />- </div>- </Link>-- <Link- href="https://supabase.com/docs/guides/platform/org-based-billing#usage-based-billing-for-compute"- target="_blank"+ <FormControl_Shadcn_>+ <Input_Shadcn_+ placeholder="Postgres version"+ {...field}+ autoComplete="off"+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </Panel.Content>+ )}++ {cloudProviderEnabled && showNonProdFields && (+ <Panel.Content>+ <FormField_Shadcn_+ control={form.control}+ name="cloudProvider"+ render={({ field }) => (+ <FormItemLayout label="Cloud provider" layout="horizontal">+ <Select_Shadcn_+ onValueChange={field.onChange}+ defaultValue={field.value}+ >+ <FormControl_Shadcn_>+ <SelectTrigger_Shadcn_>+ <SelectValue_Shadcn_ placeholder="Select a cloud provider" />+ </SelectTrigger_Shadcn_>+ </FormControl_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {Object.values(PROVIDERS).map((providerObj) => {+ const label = providerObj['name']+ const value = providerObj['id']+ return (+ <SelectItem_Shadcn_ key={value} value={value}>+ {label}+ </SelectItem_Shadcn_>+ )+ })}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormItemLayout>+ )}+ />+ </Panel.Content>+ )}++ {orgSubscription?.plan && orgSubscription?.plan.id !== 'free' && (+ <Panel.Content>+ <FormField_Shadcn_+ control={form.control}+ name="instanceSize"+ render={({ field }) => (+ <FormItemLayout+ layout="horizontal"+ label={+ <div className="space-y-4">+ <span>Instance Size</span>++ <div className="flex flex-col space-y-2">+ <Link+ href="https://supabase.com/docs/guides/platform/compute-add-ons"+ target="_blank"+ >+ <div className="flex items-center space-x-2 opacity-75 hover:opacity-100 transition">+ <p className="text-sm m-0">Compute Add-Ons</p>+ <ExternalLink size={16} strokeWidth={1.5} />+ </div>+ </Link>++ <Link+ href="https://supabase.com/docs/guides/platform/org-based-billing#usage-based-billing-for-compute"+ target="_blank"+ >+ <div className="flex items-center space-x-2 opacity-75 hover:opacity-100 transition">+ <p className="text-sm m-0">Compute Billing</p>+ <ExternalLink size={16} strokeWidth={1.5} />+ </div>+ </Link>+ </div>+ </div>+ }+ description={+ <>+ <p>+ Select the size for your dedicated database. You can always+ change this later.+ </p>+ <p className="mt-1">+ Your organization has $10/month in Compute Credits to cover one+ instance on Micro Compute or parts of any other instance size.+ </p>+ </>+ }>- <div className="flex items-center space-x-2 opacity-75 hover:opacity-100 transition">- <p className="text-sm m-0">Compute Billing</p>- <ExternalLink size={16} strokeWidth={1.5} />- </div>- </Link>- </div>- </div>- }- type="select"- value={instanceSize}- onChange={(value) => setInstanceSize(value)}- descriptionText={- <>- <p>- Select the size for your dedicated database. You can always change this- later.- </p>- <p className="mt-1">- Your organization has $10/month in Compute Credits to cover one instance- on Micro Compute or parts of any other instance size.- </p>- </>- }- >- {AVAILABLE_SIZES.map((option) => {- return (- <Listbox.Option- key={option}- label={`${INSTANCE_SIZE_SPECS[option].ram} RAM / ${INSTANCE_SIZE_SPECS[option].cpu} CPU (${INSTANCE_SIZE_SPECS[option].label})`}- value={option}+ <Select_Shadcn_+ value={field.value}+ onValueChange={(value) => field.onChange(value)}+ >+ <SelectTrigger_Shadcn_ className="[&_.instance-details]:hidden">+ <SelectValue_Shadcn_ placeholder="Select an instance size" />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {sizes.map((option) => {+ return (+ <SelectItem_Shadcn_ key={option} value={option}>+ <div className="flex flex-row i gap-2">+ <div className="text-center w-[80px]">+ <Badge+ variant={option === 'micro' ? 'default' : 'brand'}+ className="rounded-md w-16 text-center flex justify-center font-mono uppercase"+ >+ {instanceSizeSpecs[option].label}+ </Badge>+ </div>+ <div className="text-sm">+ <span className="text-foreground">+ {instanceSizeSpecs[option].ram} RAM /{' '}+ {instanceSizeSpecs[option].cpu} CPU+ </span>+ <p className="text-xs text-muted instance-details">+ {instanceSizeSpecs[option].price}+ </p>+ </div>+ </div>+ </SelectItem_Shadcn_>+ )+ })}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormItemLayout>+ )}+ />+ </Panel.Content>+ )}++ <Panel.Content>+ <FormField_Shadcn_+ control={form.control}+ name="dbPass"+ render={({ field }) => (+ <FormItemLayout+ label="Database Password"+ layout="horizontal"+ description={+ <>+ <PasswordStrengthBar+ passwordStrengthScore={form.getValues('dbPassStrength')}+ password={field.value}+ passwordStrengthMessage={passwordStrengthMessage}+ generateStrongPassword={generateStrongPassword}+ />+ </>+ }>- <div className="flex space-x-2">- <div className="text-center w-[80px]">- <Badge- variant={option === 'micro' ? 'default' : 'brand'}- className="rounded-md w-16 text-center flex justify-center font-mono uppercase"- >- {INSTANCE_SIZE_SPECS[option].label}- </Badge>- </div>- <div className="text-sm">- <span className="text-foreground">- {INSTANCE_SIZE_SPECS[option].ram} RAM /{' '}- {INSTANCE_SIZE_SPECS[option].cpu} CPU- </span>- <p className="text-xs text-muted">- {INSTANCE_SIZE_SPECS[option].price}- </p>- </div>- </div>- </Listbox.Option>- )- })}- </Listbox>- </Panel.Content>- )}-- <Panel.Content>- <Input- id="password"- copy={dbPass.length > 0}- layout="horizontal"- label="Database Password"- type="password"- placeholder="Type in a strong password"- value={dbPass}- onChange={onDbPassChange}- descriptionText={- <PasswordStrengthBar- passwordStrengthScore={passwordStrengthScore}- password={dbPass}- passwordStrengthMessage={passwordStrengthMessage}- generateStrongPassword={generateStrongPassword}+ <FormControl_Shadcn_>+ <Input+ copy={field.value.length > 0}+ type="password"+ placeholder="Type in a strong password"+ {...field}+ autoComplete="off"+ onChange={async (event) => {+ field.onChange(event)+ form.trigger('dbPassStrength')+ const value = event.target.value+ if (event.target.value === '') {+ await form.setValue('dbPassStrength', 0)+ await form.trigger('dbPass')+ } else {+ await delayedCheckPasswordStrength(value)+ }+ }}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}/>- }- error={passwordStrengthWarning}- />- </Panel.Content>-- <Panel.Content>- <RegionSelector- cloudProvider={cloudProvider}- selectedRegion={dbRegion}- onSelectRegion={setDbRegion}- />- </Panel.Content>- </>- )}+ </Panel.Content>++ <Panel.Content>+ <FormField_Shadcn_+ control={form.control}+ name="dbRegion"+ render={({ field }) => (+ <RegionSelector+ field={field}+ form={form}+ cloudProvider={form.getValues('cloudProvider') as CloudProvider}+ />+ )}+ />+ </Panel.Content>+ </>+ )}- {isAdmin && freePlanWithExceedingLimits && slug && (- <Panel.Content>- <FreeProjectLimitWarning- membersExceededLimit={membersExceededLimit || []}- orgSlug={slug}- />- </Panel.Content>+ {isAdmin && freePlanWithExceedingLimits && slug && (+ <Panel.Content>+ <FreeProjectLimitWarning+ membersExceededLimit={membersExceededLimit || []}+ orgSlug={slug}+ />+ </Panel.Content>+ )}+ </div>)}- </div>- )}- </>- </Panel>+ </>+ </Panel>+ </form>+ </Form_Shadcn_>)}