Skip to content

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

Consolidate project creation UI for vercel integration flow (#47995)

Joshen Lim6e0078182b1d
diff --git a/apps/studio/components/interfaces/ProjectCreation/DataSeeding.tsx b/apps/studio/components/interfaces/ProjectCreation/DataSeeding.tsx
new file mode 100644
index 00000000000..54ab2be0dd7
--- /dev/null
+++ b/apps/studio/components/interfaces/ProjectCreation/DataSeeding.tsx
@@ -0,0 +1,46 @@
+import { UseFormReturn } from 'react-hook-form'
+import { Checkbox, FormControl, FormDescription, FormField, FormItem, FormLabel } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+
+import { CreateProjectForm } from './ProjectCreation.schema'
+import Panel from '@/components/ui/Panel'
+
+interface DataSeedingProps {
+ form: UseFormReturn<CreateProjectForm>
+ layout?: 'vertical' | 'horizontal'
+}
+
+export const DataSeeding = ({ form, layout = 'horizontal' }: DataSeedingProps) => {
+ return (
+ <Panel.Content className="pb-8">
+ <FormItemLayout layout={layout} label="Data seeding" isReactForm={false}>
+ <div className="flex flex-col gap-4">
+ <FormField
+ name="shouldRunMigrations"
+ control={form.control}
+ render={({ field }) => (
+ <FormItem className="flex items-start gap-3">
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ disabled={field.disabled}
+ onCheckedChange={(value) => field.onChange(value === true)}
+ />
+ </FormControl>
+ <div className="space-y-1">
+ <FormLabel className="text-sm text-foreground">
+ Create sample tables with seed data
+ </FormLabel>
+ <FormDescription className="text-foreground-lighter">
+ To get you started quickly, we can create new tables for you with seed (sample)
+ data. You can delete these tables later.
+ </FormDescription>
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ </FormItemLayout>
+ </Panel.Content>
+ )
+}
diff --git a/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx
index 070ab1292e2..13effc013d9 100644
--- a/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx
+++ b/apps/studio/components/interfaces/ProjectCreation/OrganizationSelector.tsx
@@ -28,9 +28,13 @@ import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganizati
interface OrganizationSelectorProps {
form: UseFormReturn<CreateProjectForm>
+ disableOrganizationSelection: boolean
}
-export const OrganizationSelector = ({ form }: OrganizationSelectorProps) => {
+export const OrganizationSelector = ({
+ form,
+ disableOrganizationSelection,
+}: OrganizationSelectorProps) => {
const router = useRouter()
const { slug } = useParams()
const queryClient = useQueryClient()
@@ -65,6 +69,7 @@ export const OrganizationSelector = ({ form }: OrganizationSelectorProps) => {
}}
value={field.value}
defaultValue={field.value}
+ disabled={disableOrganizationSelection}
>
<SelectTrigger id="organization">
<SelectValue placeholder="Select an organization" />
diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts
index 1d3948c47c2..38b3369873a 100644
--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts
+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts
@@ -42,6 +42,7 @@ export const FormSchema = z
enableRlsEventTrigger: z.boolean(),
postgresVersionSelection: z.string(),
useOrioleDb: z.boolean(),
+ shouldRunMigrations: z.boolean(),
})
.superRefine(
(
diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx
index 8d237ed1525..e01c2be3dd6 100644
--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx
+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.tsx
@@ -29,6 +29,7 @@ interface ProjectCreationFooterProps {
organizationProjects: OrgProject[]
isCreatingNewProject: boolean
isSuccessNewProject: boolean
+ hideCancelButton: boolean
}
export const ProjectCreationFooter = ({
@@ -38,6 +39,7 @@ export const ProjectCreationFooter = ({
organizationProjects,
isCreatingNewProject,
isSuccessNewProject,
+ hideCancelButton,
}: ProjectCreationFooterProps) => {
const router = useRouter()
const { data: currentOrg } = useSelectedOrganizationQuery()
@@ -167,16 +169,18 @@ export const ProjectCreationFooter = ({
</div>
<div className="flex items-end col-span-8 space-x-2 ml-auto">
- <Button
- variant="default"
- disabled={isCreatingNewProject || isSuccessNewProject}
- onClick={() => {
- if (!!lastVisitedOrganization) router.push(`/org/${lastVisitedOrganization}`)
- else router.push('/organizations')
- }}
- >
- Cancel
- </Button>
+ {!hideCancelButton && (
+ <Button
+ variant="default"
+ disabled={isCreatingNewProject || isSuccessNewProject}
+ onClick={() => {
+ if (!!lastVisitedOrganization) router.push(`/org/${lastVisitedOrganization}`)
+ else router.push('/organizations')
+ }}
+ >
+ Cancel
+ </Button>
+ )}
<Button
type="submit"
loading={isCreatingNewProject || isSuccessNewProject}
diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx
index 78c064b7d20..75516031101 100644
--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx
+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { acceptUntrustedSql, joinSqlFragments, untrustedSql } from '@supabase/pg-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useFeatureFlags, useFlag, useParams } from 'common'
import Link from 'next/link'
@@ -15,6 +16,7 @@ import { z } from 'zod'
import { AdvancedConfiguration } from './AdvancedConfiguration'
import { ComputeSizeSelector } from './ComputeSizeSelector'
import { DatabasePasswordInput } from './DatabasePasswordInput'
+import { DataSeeding } from './DataSeeding'
import { DisabledWarningDueToIncident } from './DisabledWarningDueToIncident'
import { FreeProjectLimitWarning } from './FreeProjectLimitWarning'
import { InternalOnlyConfiguration } from './InternalOnlyConfiguration'
@@ -64,20 +66,47 @@ import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganizat
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { usePHFlag } from '@/hooks/ui/useFlag'
import { DOCS_URL, PROJECT_STATUS, PROVIDERS, useDefaultProvider } from '@/lib/constants'
+import { getInitialMigrationSQLFromGitHubRepo } from '@/lib/integration-utils'
import { useProfile } from '@/lib/profile'
+import { trimSafeSqlFragment } from '@/lib/sql'
import { classifyApiError, classifyValidationError } from '@/lib/telemetry/funnel-errors'
import { useTrack } from '@/lib/telemetry/track'
import { useTrackFunnelError } from '@/lib/telemetry/use-track-funnel-error'
const sizesWithNoCostConfirmationRequired: DesiredInstanceSize[] = ['micro', 'small']
-export const ProjectCreationForm = () => {
+interface ProjectCreationFormProps {
+ isVercelIntegrationFlow?: boolean
+ onCreateSuccess?: (ref: string) => void
+}
+
+/**
+ * [Joshen] JFYI am only adding the `isVercelIntegrationFlow` flag to keep the existing
+ * behaviour for project creation via Vercel integration as similar to keep current state
+ * for now, what it controls if `true`:
+ * - Disables organization selection
+ * - Hides the following:
+ * - "Internal configuration" section
+ * - "GitHub repository" field
+ * - "Free project info" at the bottom
+ * - "Cancel" button
+ * - Shows the following:
+ * - "Data seeding" section
+ * Eventually we could looking into reducing the differences more, e.g having data seeding
+ * for both ways, and showing GitHub repository field for Vercel integration
+ */
+export const ProjectCreationForm = ({
+ isVercelIntegrationFlow = false,
+ onCreateSuccess,
+}: ProjectCreationFormProps) => {
const track = useTrack()
- const trackFunnelError = useTrackFunnelError()
const router = useRouter()
- const { slug, projectName } = useParams()
- const defaultProvider = useDefaultProvider()
const { profile } = useProfile()
+ const { slug, projectName, externalId } = useParams()
+ const trackFunnelError = useTrackFunnelError()
+ const defaultProvider = useDefaultProvider()
+
+ const surface = isVercelIntegrationFlow ? 'vercel' : 'main'
const { data: currentOrg } = useSelectedOrganizationQuery()
const isFreePlan = currentOrg?.plan?.id === 'free'
@@ -96,7 +125,8 @@ export const ProjectCreationForm = () => {
const { hasLoaded: flagsLoaded } = useFeatureFlags()
const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
- const showInternalOnlyConfiguration = useFlag('newProjectInternalOnlyConfiguration')
+ const showInternalOnlyConfiguration =
+ useFlag('newProjectInternalOnlyConfiguration') && !isVercelIntegrationFlow
// Read the raw flag for telemetry — coerce-undefined-to-false would record false for
// users whose flags haven't loaded yet. The raw value preserves undefined (omitted from
@@ -136,6 +166,7 @@ export const ProjectCreationForm = () => {
enableRlsEventTrigger: false,
postgresVersionSelection: '',
useOrioleDb: false,
+ shouldRunMigrations: true,
},
})
const { getFieldState, resetField, setValue } = form
@@ -262,7 +293,8 @@ export const ProjectCreationForm = () => {
(member) => member.primary_email?.toLowerCase() === userPrimaryEmail
)
: false
- const shouldShowFreeProjectInfo = !!currentOrg && !isFreePlan && !isUserAtFreeProjectLimit
+ const shouldShowFreeProjectInfo =
+ !!currentOrg && !isFreePlan && !isUserAtFreeProjectLimit && !isVercelIntegrationFlow
const {
gitHubAuthorization,
githubRepos,
@@ -280,7 +312,7 @@ export const ProjectCreationForm = () => {
track(
'project_creation_simple_version_submitted',
{
- surface: 'main',
+ surface,
instanceSize: form.getValues('instanceSize'),
enableRlsEventTrigger: form.getValues('enableRlsEventTrigger'),
dataApiEnabled: form.getValues('dataApi'),
@@ -295,7 +327,8 @@ export const ProjectCreationForm = () => {
organization: res.organization_slug,
}
)
- router.push(`/project/${res.ref}`)
+ onCreateSuccess?.(res.ref)
+ if (surface === 'main') router.push(`/project/${res.ref}`)
},
onError: (error) => {
const toastId = toast.error(`Failed to create new project: ${error.message}`)
@@ -342,8 +375,15 @@ export const ProjectCreationForm = () => {
useOrioleDb,
githubInstallationId,
githubRepositoryId,
+ shouldRunMigrations,
} = values
+ if (postgresVersion && !postgresVersion.match(/1[2-9]\..*/)) {
+ return toast.error(
+ `Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`
+ )
+ }
+
if (useOrioleDb && !availableOrioleVersion) {
const toastId = toast.error('No available OrioleDB image found, only Postgres is available')
trackFunnelError(
@@ -367,7 +407,33 @@ export const ProjectCreationForm = () => {
const shouldIncludeGitHubFields =
githubInstallationId !== undefined && Number.isFinite(parsedGitHubRepositoryId)
+ let dbSql = enableRlsEventTrigger ? AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL : undefined
+ if (isVercelIntegrationFlow && shouldRunMigrations && !!externalId) {
+ const id = toast.loading(`Fetching initial migrations from GitHub repository...`)
+
+ try {
+ const migrationSql = await getInitialMigrationSQLFromGitHubRepo(externalId)
+ if (migrationSql) {
+ const safeMigrationSql = trimSafeSqlFragment(
+ acceptUntrustedSql(untrustedSql(migrationSql))
+ )
+ dbSql = dbSql
+ ? joinSqlFragments([trimSafeSqlFragment(dbSql), safeMigrationSql], ';\n')
+ : safeMigrationSql
+ toast.loading(`Migrations fetched! Creating project...`, { id })
+ } else {
+ toast.loading('No migrations found, creating project...')
+ }
+ } catch (error) {
+ toast.loading(
+ `Failed to fetch migrations: ${error instanceof Error ? error.message : ''}. Proceeding to create project...`,
+ { id }
+ )
+ }
+ }
+
const data: ProjectCreateVariables = {
+ dbSql,
dbPass,
cloudProvider,
organizationSlug: currentOrg.slug,
@@ -383,7 +449,6 @@ export const ProjectCreationForm = () => {
postgresEngine: useOrioleDb ? availableOrioleVersion?.postgres_engine : postgresEngine,
releaseChannel: useOrioleDb ? availableOrioleVersion?.release_channel : releaseChannel,
...(smartRegionEnabled ? { regionSelection: selectedRegion } : { dbRegion }),
- dbSql: enableRlsEventTrigger ? AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL : undefined,
...(shouldIncludeGitHubFields
? {
githubInstallationId,
@@ -392,12 +457,6 @@ export const ProjectCreationForm = () => {
: {}),
}
- if (postgresVersion && !postgresVersion.match(/1[2-9]\..*/)) {
- return toast.error(
- `Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`
- )
- }
-
if (postgresVersion || instanceType) {
data['customSupabaseRequest'] = {
ami: {
@@ -413,12 +472,13 @@ export const ProjectCreationForm = () => {
}
const hasTrackedFormExposed = useRef(false)
+
useEffect(() => {
if (hasTrackedFormExposed.current) return
if (!isOrganizationsSuccess || !canCreateProject || !currentOrg) return
hasTrackedFormExposed.current = true
- track('project_creation_form_exposed', { surface: 'main' })
- }, [isOrganizationsSuccess, canCreateProject, currentOrg, track])
+ track('project_creation_form_exposed', { surface })
+ }, [isOrganizationsSuccess, canCreateProject, currentOrg, track, surface])
useEffect(() => {
// Only set once to ensure compute credits dont change while project is being created
@@ -429,10 +489,10 @@ export const ProjectCreationForm = () => {
useEffect(() => {
// Handle no org: redirect to new org route
- if (isEmptyOrganizations) {
+ if (isEmptyOrganizations && !isVercelIntegrationFlow) {
router.push(`/new`)
}
- }, [isEmptyOrganizations, router])
+ }, [isEmptyOrganizations, isVercelIntegrationFlow, router])
useEffect(() => {
// [Joshen] Cause slug depends on router which doesnt load immediately on render
@@ -538,6 +598,7 @@ export const ProjectCreationForm = () => {
organizationProjects={organizationProjects}
isCreatingNewProject={isCreatingNewProject}
isSuccessNewProject={isSuccessNewProject}
+ hideCancelButton={isVercelIntegrationFlow}
/>
}
>
@@ -546,11 +607,14 @@ export const ProjectCreationForm = () => {
<DisabledWarningDueToIncident title="Project creation is currently disabled" />
) : (
<div className="divide-y divide-border-border">
- <OrganizationSelector form={form} />
+ <OrganizationSelector
+ form={form}
+ disableOrganizationSelection={isVercelIntegrationFlow}
+ />
{canCreateProject && (
<>
- {canConfigureGitHubOnCreate && (
+ {!isVercelIntegrationFlow && canConfigureGitHubOnCreate && (
<Panel.Content>
<GitHubRepositoryField
form={form}
@@ -593,7 +657,9 @@ export const ProjectCreationForm = () => {
instanceSize={instanceSize as DesiredInstanceSize}
/>
- <SecurityOptions form={form} />
+ {isVercelIntegrationFlow && !!externalId && <DataSeeding form={form} />}
+
+ <SecurityOptions form={form} surface={surface} />
{showInternalOnlyConfiguration && <InternalOnlyConfiguration form={form} />}
diff --git a/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx b/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx
index bca84b51169..0751b109007 100644
--- a/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx
+++ b/apps/studio/components/interfaces/ProjectCreation/SecurityOptions.tsx
@@ -1,3 +1,4 @@
+import { useParams } from 'common'
import { UseFormReturn } from 'react-hook-form'
import {
Checkbox,
@@ -24,9 +25,11 @@ import { DOCS_URL } from '@/lib/constants'
interface SecurityOptionsProps {
form: UseFormReturn<CreateProjectForm>
layout?: 'vertical' | 'horizontal'
+ surface: 'main' | 'vercel'
}
-export const SecurityOptions = ({ form, layout = 'horizontal' }: SecurityOptionsProps) => {
+export const SecurityOptions = ({ form, layout = 'horizontal', surface }: SecurityOptionsProps) => {
+ const { slug } = useParams()
const dataApi = useWatch({ control: form.control, name: 'dataApi' })
const dataApiDefaultPrivileges = useWatch({
control: form.control,
@@ -34,11 +37,20 @@ export const SecurityOptions = ({ form, layout = 'horizontal' }: SecurityOptions
})
const hasUserModified = form.getFieldState('dataApiDefaultPrivileges', form.formState).isDirty
- useTrackDefaultPrivilegesExposure({
- surface: 'main',
- dataApiDefaultPrivileges: dataApiDefaultPrivileges ?? true,
- hasUserModified,
- })
+ useTrackDefaultPrivilegesExposure(
+ surface === 'main'
+ ? {
+ surface: 'main',
+ dataApiDefaultPrivileges: dataApiDefaultPrivileges ?? true,
+ hasUserModified,
+ }
+ : {
+ surface: 'vercel',
+ orgSlug: slug,
+ dataApiDefaultPrivileges: dataApiDefaultPrivileges ?? true,
+ hasUserModified,
+ }
+ )
return (
<Panel.Content className="pb-8">
diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx
index 5d5d0b5fb84..7ec922a48da 100644
--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx
+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx
@@ -159,15 +159,11 @@ export const GitHubRepositoryField = <TFormValues extends FieldValues>({
id={name}
variant="default"
type="button"
- className="justify-start h-[34px] w-full"
+ className="justify-start h-[34px] w-full [&>div:last-child]:ml-auto"
disabled={disabled || isLoading}
loading={isLoading}
icon={GITHUB_ICON}
- iconRight={
- <span className="grow flex justify-end">
- <ChevronDown />
- </span>
- }
+ iconRight={<ChevronDown />}
>
{selectedRepository?.name ||
selectedRepositoryName ||
diff --git a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
index 1b55a32e4b9..2e1f3b8d277 100644
--- a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
+++ b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
@@ -1,223 +1,36 @@
import { useParams } from 'common'
-import { ChangeEvent, useEffect, useRef, useState } from 'react'
-import { AWS_REGIONS } from 'shared-data'
-import { toast } from 'sonner'
-import {
- Button,
- Checkbox,
- Input,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from 'ui'
+import { useEffect, useState } from 'react'
import { Admonition } from 'ui-patterns/admonition'
-import { Input as PasswordInput } from 'ui-patterns/DataInputs/Input'
-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { isVercelUrl } from '@/components/interfaces/Integrations/Vercel/VercelIntegration.utils'
-import { Markdown } from '@/components/interfaces/Markdown'
+import { ProjectCreationForm } from '@/components/interfaces/ProjectCreation/ProjectCreationForm'
import VercelIntegrationWindowLayout from '@/components/layouts/IntegrationsLayout/VercelIntegrationWindowLayout'
import { ScaffoldColumn, ScaffoldContainer } from '@/components/layouts/Scaffold'
-import { PasswordStrengthBar } from '@/components/ui/PasswordStrengthBar'
import { useProjectSettingsV2Query } from '@/data/config/project-settings-v2-query'
import { useIntegrationsQuery } from '@/data/integrations/integrations-query'
import { useIntegrationVercelConnectionsCreateMutation } from '@/data/integrations/integrations-vercel-connections-create-mutation'
import { useVercelProjectsQuery } from '@/data/integrations/integrations-vercel-projects-query'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
-import { useProjectCreateMutation } from '@/data/projects/project-create-mutation'
-import {
- isInDataApiRevokeTreatment,
- useDataApiRevokeOnCreateDefaultEnabled,
- useTrackDefaultPrivilegesExposure,
-} from '@/hooks/misc/useDataApiRevokeOnCreateDefault'
-import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
-import { usePHFlag } from '@/hooks/ui/useFlag'
-import { BASE_PATH, PROVIDERS } from '@/lib/constants'
-import { getInitialMigrationSQLFromGitHubRepo } from '@/lib/integration-utils'
-import { passwordStrength, PasswordStrengthScore } from '@/lib/password-strength'
-import { generateStrongPassword } from '@/lib/project'
-import { useTrack } from '@/lib/telemetry/track'
import { useIntegrationInstallationSnapshot } from '@/state/integration-installation'
import type { NextPageWithLayout } from '@/types'
const VercelIntegration: NextPageWithLayout = () => {
- return (
- <>
- <ScaffoldContainer className="flex flex-col gap-6 grow py-8">
- <ScaffoldColumn className="mx-auto w-full max-w-md">
- <header>
- <h2>New project</h2>
- <Markdown
- className="text-foreground-light"
- content={`Choose the Supabase organization you wish to install in`}
- />
- </header>
- <CreateProject />
- <Admonition
- type="default"
- layout="horizontal"
- title="You can uninstall this Integration at any time."
- description="You can remove this integration at any time via Vercel or the Supabase dashboard"
- />
- </ScaffoldColumn>
- </ScaffoldContainer>
- </>
- )
-}
-
-VercelIntegration.getLayout = (page) => (
- <VercelIntegrationWindowLayout>{page}</VercelIntegrationWindowLayout>
-)
-
-const CreateProject = () => {
- const { data: selectedOrganization } = useSelectedOrganizationQuery()
- const [projectName, setProjectName] = useState('')
- const [dbPass, setDbPass] = useState('')
- const [passwordStrengthMessage, setPasswordStrengthMessage] = useState('')
- const [passwordStrengthScore, setPasswordStrengthScore] = useState(-1)
- const [shouldRunMigrations, setShouldRunMigrations] = useState(true)
- const [dbRegion, setDbRegion] = useState<string>(PROVIDERS.AWS.default_region.displayName)
-
- const track = useTrack()
+ const { slug, next, currentProjectId: foreignProjectId } = useParams()
const snapshot = useIntegrationInstallationSnapshot()
- const isDataApiRevokeOnCreateDefault = useDataApiRevokeOnCreateDefaultEnabled()
- const dataApiRevokeOnCreateDefaultFlag = usePHFlag<boolean | string>(
- 'dataApiRevokeOnCreateDefault'
- )
- const [dataApiDefaultPrivileges, setDataApiDefaultPrivileges] = useState(
- !isDataApiRevokeOnCreateDefault
- )
- const hasUserModifiedDataApiDefaultPrivileges = useRef(false)
- useEffect(() => {
- if (dataApiRevokeOnCreateDefaultFlag === undefined) return
- if (hasUserModifiedDataApiDefaultPrivileges.current) return
- setDataApiDefaultPrivileges(!isInDataApiRevokeTreatment(dataApiRevokeOnCreateDefaultFlag))
- }, [dataApiRevokeOnCreateDefaultFlag])
+ const [newProjectRef, setNewProjectRef] = useState<string>()
- const { slug, next, currentProjectId: foreignProjectId, externalId } = useParams()
-
- useTrackDefaultPrivilegesExposure({
- surface: 'vercel',
- orgSlug: slug,
- dataApiDefaultPrivileges,
- hasUserModified: hasUserModifiedDataApiDefaultPrivileges.current,
- })
-
- async function checkPasswordStrength(value: string) {
- const { message, strength } = await passwordStrength(value)
- setPasswordStrengthScore(strength)
- setPasswordStrengthMessage(message)
- }
-
- const { mutateAsync: createConnections } = useIntegrationVercelConnectionsCreateMutation()
+ const { data: integrationData } = useIntegrationsQuery()
+ const organizationIntegration = integrationData?.find((x) => x.organization.slug === slug)
const { data: organizationData } = useOrganizationsQuery()
const organization = organizationData?.find((x) => x.slug === slug)
- const hasTrackedFormExposed = useRef(false)
- useEffect(() => {
- if (hasTrackedFormExposed.current) return
- if (!slug) return
- hasTrackedFormExposed.current = true
- track('project_creation_form_exposed', { surface: 'vercel' }, { organization: slug })
- }, [slug, track])
-
- /**
- * array of integrations installed
- */
- const { data: integrationData } = useIntegrationsQuery()
-
- /**
- * the vercel integration installed for organization chosen
- */
- const organizationIntegration = integrationData?.find((x) => x.organization.slug === slug)
-
- /**
- * Vercel projects available for this integration
- */
const { data: vercelProjects } = useVercelProjectsQuery(
- {
- organization_integration_id: organizationIntegration?.id,
- },
+ { organization_integration_id: organizationIntegration?.id },
{ enabled: organizationIntegration !== undefined }
)
- function onProjectNameChange(e: ChangeEvent<HTMLInputElement>) {
- e.target.value = e.target.value.replace(/\./g, '')
- setProjectName(e.target.value)
- }
-
- function onDbPassChange(e: ChangeEvent<HTMLInputElement>) {
- const value = e.target.value
- setDbPass(value)
- if (value == '') {
- setPasswordStrengthScore(-1)
- setPasswordStrengthMessage('')
- } else checkPasswordStrength(value)
- }
-
- function generatePassword() {
- const password = generateStrongPassword()
- setDbPass(password)
- checkPasswordStrength(password)
- }
-
- const [newProjectRef, setNewProjectRef] = useState<string | undefined>(undefined)
-
- const { mutate: createProject } = useProjectCreateMutation({
- onSuccess: (res) => {
- setNewProjectRef(res.ref)
- track(
- 'project_creation_simple_version_submitted',
- {
- surface: 'vercel',
- dataApiEnabled: true,
- dataApiDefaultPrivilegesGranted: dataApiDefaultPrivileges,
- ...(dataApiRevokeOnCreateDefaultFlag !== undefined && {
- dataApiRevokeOnCreateDefaultEnabled: dataApiRevokeOnCreateDefaultFlag,
- }),
- },
- {
- project: res.ref,
- organization: res.organization_slug,
- }
- )
- },
- onError: (error) => {
- toast.error(error.message)
- snapshot.setLoading(false)
- },
- })
-
- async function onCreateProject() {
- if (!organizationIntegration) return console.error('No organization installation details found')
- if (!organizationIntegration?.id) return console.error('No organization installation ID found')
- if (!foreignProjectId) return console.error('No foreignProjectId set')
- if (!organization) return console.error('No organization set')
-
- snapshot.setLoading(true)
-
- let dbSql: string | undefined
- if (shouldRunMigrations) {
- const id = toast(`Fetching initial migrations from GitHub repo`)
- const migrationSql = await getInitialMigrationSQLFromGitHubRepo(externalId)
- if (migrationSql) dbSql = migrationSql
- toast.success(`Done fetching initial migrations`, { id })
- }
-
- createProject({
- organizationSlug: organization.slug,
- name: projectName,
- dbPass,
- dbRegion,
- dbSql,
- dataApiRevokeDefaultPrivileges: !dataApiDefaultPrivileges,
- })
- }
-
// Wait for the new project to be created before creating the connection
const { data, isSuccess } = useProjectSettingsV2Query(
{ projectRef: newProjectRef },
@@ -230,8 +43,12 @@ const CreateProject = () => {
},
}
)
+
+ const { mutateAsync: createConnections } = useIntegrationVercelConnectionsCreateMutation()
+
useEffect(() => {
if (!isSuccess) return
+
const onSuccessFunc = async () => {
const isReady = (data.service_api_keys ?? []).length > 0
@@ -239,7 +56,7 @@ const CreateProject = () => {
return
}
- const projectDetails = vercelProjects?.find((x: any) => x.id === foreignProjectId)
+ const projectDetails = vercelProjects?.find((x) => x.id === foreignProjectId)
try {
await createConnections({
@@ -257,7 +74,7 @@ const CreateProject = () => {
},
},
},
- orgSlug: selectedOrganization?.slug,
+ orgSlug: organization?.slug,
})
} catch (error) {
console.error('An error occurred during createConnections:', error)
@@ -266,157 +83,31 @@ const CreateProject = () => {
snapshot.setLoading(false)
- if (next && isVercelUrl(next)) {
- window.location.href = next
- }
+ if (next && isVercelUrl(next)) window.location.href = next
}
+
onSuccessFunc()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [data, isSuccess])
return (
- <div>
- <p className="mb-2">Supabase project details</p>
- <div className="py-2">
- <FormItemLayout
- id="projectName"
- isReactForm={false}
- layout="vertical"
- label="Project name"
- size="tiny"
- >
- <Input
- autoFocus
- id="projectName"
- type="text"
- placeholder=""
- value={projectName}
- onChange={onProjectNameChange}
- />
- </FormItemLayout>
- </div>
- <div className="py-2">
- <FormItemLayout
- id="dbPass"
- isReactForm={false}
- layout="vertical"
- label="Database password"
- size="tiny"
- description={
- <PasswordStrengthBar
- passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}
- password={dbPass}
- passwordStrengthMessage={passwordStrengthMessage}
- generateStrongPassword={generatePassword}
- />
- }
- >
- <PasswordInput
- id="dbPass"
- type="password"
- placeholder="Type in a strong password"
- value={dbPass}
- reveal
- copy={dbPass.length > 0}
- onChange={onDbPassChange}
- />
- </FormItemLayout>
- </div>
- <div className="py-2">
- <div className="mt-1">
- <FormItemLayout
- id="region"
- isReactForm={false}
- layout="vertical"
- label="Region"
- description="Select a region close to your users for the best performance."
- className="gap-[2px]"
- size="tiny"
- >
- <Select value={dbRegion} onValueChange={(region) => setDbRegion(region)}>
- <SelectTrigger id="region">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {Object.keys(AWS_REGIONS).map((option: string, i) => {
- const label = Object.values(AWS_REGIONS)[i].displayName
- return (
- <SelectItem key={option} value={label}>
- <div className="flex gap-2">
- <img
- alt="region icon"
- className="w-5 rounded-xs"
- src={`${BASE_PATH}/img/regions/${Object.values(AWS_REGIONS)[i].code}.svg`}
- />
- <span>{label}</span>
- </div>
- </SelectItem>
- )
- })}
- </SelectContent>
- </Select>
- </FormItemLayout>
- </div>
- </div>
- <div className="py-2 pb-4">
- <div className="items-top flex space-x-2">
- <Checkbox
- id="shouldRunMigrations"
- name="shouldRunMigrations"
- checked={shouldRunMigrations}
- onCheckedChange={(checked) => setShouldRunMigrations(!!checked)}
- />
- <div className="grid gap-1.5 leading-none">
- <label
- htmlFor="enable-realtime"
- className="text-sm text-foreground-light flex items-center space-x-2 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
- >
- Create sample tables with seed data
- </label>
- <p className="text-sm text-foreground-muted">
- To get you started quickly, we can create new tables for you with seed (sample) data.
- You can delete these tables later.
- </p>
- </div>
- </div>
- </div>
- <div className="py-2 pb-4">
- <div className="items-top flex space-x-2">
- <Checkbox
- id="dataApiDefaultPrivileges"
- name="dataApiDefaultPrivileges"
- checked={dataApiDefaultPrivileges}
- onCheckedChange={(checked) => {
- hasUserModifiedDataApiDefaultPrivileges.current = true
- setDataApiDefaultPrivileges(!!checked)
- }}
- />
- <div className="grid gap-1.5 leading-none">
- <label
- htmlFor="dataApiDefaultPrivileges"
- className="text-sm text-foreground-light flex items-center space-x-2 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
- >
- Automatically expose new tables
- </label>
- <p className="text-sm text-foreground-muted">
- Grants privileges to Data API roles by default, exposing new tables. We recommend
- disabling this to control access manually.
- </p>
- </div>
- </div>
- </div>
- <div className="flex flex-row w-full justify-end">
- <Button
- size="medium"
- className="self-end"
- disabled={snapshot.loading}
- loading={snapshot.loading}
- onClick={onCreateProject}
- >
- Create Project
- </Button>
- </div>
- </div>
+ <ScaffoldContainer className="flex flex-col gap-6 grow py-8">
+ <ScaffoldColumn className="mx-auto w-full max-w-2xl">
+ <Admonition
+ type="default"
+ layout="horizontal"
+ title="You can uninstall this Integration at any time."
+ description="You can remove this integration at any time via Vercel or the Supabase dashboard"
+ />
+
+ <ProjectCreationForm isVercelIntegrationFlow onCreateSuccess={setNewProjectRef} />
+ </ScaffoldColumn>
+ </ScaffoldContainer>
)
}
+VercelIntegration.getLayout = (page) => (
+ <VercelIntegrationWindowLayout>{page}</VercelIntegrationWindowLayout>
+)
+
export default VercelIntegration