import { useQuery } from '@tanstack/react-query' import type { HomeProjectCredentialCopiedEvent } from 'common/telemetry-constants' import { CheckIcon, ChevronDownIcon, CopyIcon, DatabaseIcon, KeyRoundIcon, Link2Icon, TerminalIcon, } from 'lucide-react' import { parseAsBoolean, useQueryState } from 'nuqs' import { useEffect, useMemo, useState } from 'react' import { Button, cn, copyToClipboard, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from 'ui' import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader' import { getConnectionStrings } from '@/components/interfaces/Connect/DatabaseSettings.utils' import { appendHighAvailabilitySslParams } from '@/components/interfaces/ConnectSheet/DatabaseSettings.utils' import { apiKeysQueryOptions, getKeys } from '@/data/api-keys/api-keys-query' import { useProjectApiUrl } from '@/data/config/project-endpoint-query' import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query' import { useIsHighAvailability } from '@/hooks/misc/useSelectedProject' import { IS_PLATFORM } from '@/lib/constants' import { useGrant } from '@/lib/grants' import { pluckObjectFields } from '@/lib/helpers' import { useTrack } from '@/lib/telemetry/track' import { useAppStateSnapshot } from '@/state/app-state' type CredentialType = HomeProjectCredentialCopiedEvent['properties']['credentialType'] const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user'] as const const EMPTY_CONNECTION_INFO = { db_user: '', db_host: '', db_port: '', db_name: '', } const getPublishableKeyDisplay = ({ grantStatus, isLoadingKeys, publishableKey, }: { grantStatus: 'loading' | 'granted' | 'denied' | 'error' isLoadingKeys: boolean publishableKey?: string }) => { if (grantStatus === 'loading' || isLoadingKeys) return 'Loading publishable key...' if (grantStatus === 'denied') return "You don't have permission to view API keys." if (grantStatus === 'error') return 'Failed to check API key permissions' return publishableKey ?? 'Publishable key unavailable' } interface ProjectConnectionPopoverProps { projectRef?: string } export const ProjectConnectionPopover = ({ projectRef }: ProjectConnectionPopoverProps) => { const [open, setOpen] = useState(false) const [copiedItem, setCopiedItem] = useState(null) const [, setShowConnect] = useQueryState('showConnect', parseAsBoolean.withDefault(false)) const { setConnectSheetSource } = useAppStateSnapshot() const track = useTrack() const apiKeysGrant = useGrant('GET /v1/projects/{ref}/api-keys', { projectRef }) const isLoadingPermissions = apiKeysGrant.status === 'loading' const canReadAPIKeys = apiKeysGrant.status === 'granted' const { data: projectUrl, isPending: isLoadingApiUrl } = useProjectApiUrl({ projectRef }) const { data, isLoading: isLoadingKeys } = useQuery( apiKeysQueryOptions( { projectRef, grant: apiKeysGrant.grant }, { enabled: open, select: getKeys } ) ) const { publishableKey } = data ?? {} const { data: databases, isLoading: isLoadingDatabases } = useReadReplicasQuery( { projectRef }, { enabled: IS_PLATFORM && open && !!projectRef } ) const primaryDatabase = databases?.find((db) => db.identifier === projectRef) const isHighAvailability = useIsHighAvailability() const directConnectionString = useMemo(() => { if ( !primaryDatabase?.db_host || !primaryDatabase?.db_name || !primaryDatabase?.db_user || !primaryDatabase?.db_port ) { return '' } const connectionInfo = pluckObjectFields(primaryDatabase, [...DB_FIELDS]) const uri = getConnectionStrings({ connectionInfo: { ...EMPTY_CONNECTION_INFO, ...connectionInfo }, metadata: { projectRef }, }).direct.uri return isHighAvailability ? appendHighAvailabilitySslParams(uri) : uri }, [primaryDatabase, projectRef, isHighAvailability]) const cliCommands = useMemo( () => [ 'supabase login', 'supabase init', `supabase link --project-ref ${projectRef ?? 'PROJECT_REF_UNAVAILABLE'}`, ].join('\n'), [projectRef] ) // Self-hosted projects may not have a publishable key configured. Rather // than show a permanently-disabled "Publishable key unavailable" row, hide // the entry entirely on !IS_PLATFORM when the key isn't available. Platform // behavior is unchanged. const showPublishableKey = IS_PLATFORM || !!publishableKey?.api_key const menuItems = useMemo< { label: string credentialType: CredentialType value: string displayValue: string disabled: boolean icon: typeof Link2Icon }[] >( () => [ { label: 'Project URL', credentialType: 'project_url', value: projectUrl ?? '', displayValue: isLoadingApiUrl ? 'Loading project URL...' : (projectUrl ?? 'Project URL unavailable'), disabled: isLoadingApiUrl || !projectUrl, icon: Link2Icon, }, ...(showPublishableKey ? [ { label: 'Publishable key', credentialType: 'publishable_key' as const, value: publishableKey?.api_key ?? '', displayValue: getPublishableKeyDisplay({ grantStatus: apiKeysGrant.status, isLoadingKeys, publishableKey: publishableKey?.api_key, }), disabled: isLoadingPermissions || isLoadingKeys || !canReadAPIKeys || !publishableKey?.api_key, icon: KeyRoundIcon, }, ] : []), ...(IS_PLATFORM ? [ { label: 'Direct connection string', credentialType: 'direct_connection_string' as const, value: directConnectionString, displayValue: isLoadingDatabases ? 'Loading connection string...' : directConnectionString || 'Connection string unavailable', disabled: isLoadingDatabases || !directConnectionString, icon: DatabaseIcon, }, { label: 'CLI setup commands', credentialType: 'cli_setup' as const, value: cliCommands, displayValue: cliCommands.replace(/\n/g, ' - '), disabled: !projectRef, icon: TerminalIcon, }, ] : []), ], [ apiKeysGrant.status, canReadAPIKeys, cliCommands, directConnectionString, isLoadingApiUrl, isLoadingDatabases, isLoadingKeys, isLoadingPermissions, projectRef, projectUrl, publishableKey?.api_key, showPublishableKey, ] ) useEffect(() => { if (!open) { setCopiedItem(null) } }, [open]) return (
{isLoadingApiUrl ? ( ) : ( {projectUrl ?? 'Project URL unavailable'} )} {!isLoadingApiUrl && ( {menuItems.map((item) => { const Icon = item.icon return ( { event.preventDefault() if (item.disabled) return copyToClipboard(item.value) setCopiedItem(item.label) track('home_project_credential_copied', { credentialType: item.credentialType, }) }} >
{copiedItem !== item.label ? Copy : null} {item.label} {copiedItem === item.label ? ( copied to your clipboard ) : null}
{item.displayValue}
{copiedItem === item.label ? : }
) })}
)}
) }