Files
supabase/apps/studio/components/interfaces/ProjectHome/ProjectConnectionPopover.tsx
supabase-vercel-tedd[bot]andIvan Vasilov 31f68587f6 feat(studio): track remaining usage on project home (#54143)
## Problem

Project home tracked most interactions, but not which credential people
copy from the "Copy" popover, or how often they use the custom report
and notebooks beyond adding blocks. Opening the Connect sheet from the
popover's "Get Connected" button also reported a stale
`connect_sheet_opened` source, because the popover never set one.

## Solution

Project home gets three new events: `home_project_credential_copied`
(with a `credentialType` enum), `home_custom_report_refresh_clicked`,
and `home_notebook_action_clicked` (`action: 'create' | 'analyze'`).
"Get Connected" in the popover now sets a new `home_popover` Connect
sheet source. The compute and GitHub stats now send
`home_activity_stat_clicked` as well, with two new `stat_type` values.
Every event fires from its click handler with a typed `track()` call,
and none sends the copied value or any user-defined name. This follows
the telemetry standards, so no `data-attr` attributes are added.

## How to verify

1. On a project's home page, open the "Copy" popover and copy each item.
Each copy sends one `home_project_credential_copied` event, with
`credentialType` set to `project_url`, `publishable_key`,
`direct_connection_string`, or `cli_setup`. No event contains the copied
value.
2. In the same popover, click "Get Connected". The Connect sheet opens
and sends `connect_sheet_opened` with `source: 'home_popover'`. Opening
it from the header button afterwards still sends `source:
'header_button'`.
3. Click the "Compute size" stat. It sends `home_activity_stat_clicked`
with `stat_type: 'compute'` and no `stat_value`.
4. Click the "GitHub" stat. It sends `home_activity_stat_clicked` with
`stat_type: 'github'`, and `stat_value` is 1 when a repository is
connected and 0 when none is.
5. With the custom report section shown, click "Refresh report". It
sends one `home_custom_report_refresh_clicked` event.
6. With the Notebooks section shown, click "New notebook" (or "Create
your first notebook" when there are none). It sends
`home_notebook_action_clicked` with `action: 'create'`. Click "Analyze"
on a notebook with cells: it sends `action: 'analyze'`.

## Checks

Ran `tsc --noEmit` in `apps/studio` and `packages/common`, `eslint` and
the type-aware `eslint.type-checks.config.cjs` lint on the changed
Studio files, `oxfmt --check` on every changed file, and `vitest run`
for `ProjectConnectionPopover.platform.test.tsx` and
`ActivityStats.test.tsx`.

## Checklist

- [x] I have read the [Contributing
Guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] I have checked that the change works in the preview deployment

## Feedback for Tedd

To ask Tedd for a change to this PR, reply in Tedd's session on
[FE-5026](https://linear.app/supabase/issue/FE-5026/track-usage-on-project-home-gaps-only).
Tedd doesn't read comments on this PR.

---------

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2026-12-01 11:54:29 +01:00

303 lines
10 KiB
TypeScript

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<string | null>(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 (
<div className="mt-3 flex items-center gap-3">
{isLoadingApiUrl ? (
<ShimmeringLoader className="w-80" />
) : (
<span className="min-w-0 max-w-[400px] truncate text-left text-foreground-light">
{projectUrl ?? 'Project URL unavailable'}
</span>
)}
{!isLoadingApiUrl && (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>
<Button
size="tiny"
iconRight={
<ChevronDownIcon
size={14}
className={cn('transition-transform', open && 'rotate-180')}
/>
}
>
Copy <span className="sr-only">project URL and API keys</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="center" className="w-80 p-1">
{menuItems.map((item) => {
const Icon = item.icon
return (
<DropdownMenuItem
key={item.label}
className="group relative items-center gap-3 pr-10"
disabled={item.disabled}
onSelect={(event) => {
event.preventDefault()
if (item.disabled) return
copyToClipboard(item.value)
setCopiedItem(item.label)
track('home_project_credential_copied', {
credentialType: item.credentialType,
})
}}
>
<Icon size={14} className="mt-0.5 shrink-0 text-foreground-light" />
<div className="min-w-0 flex-1">
<div className="text-sm text-foreground">
{copiedItem !== item.label ? <span className="sr-only">Copy</span> : null}
{item.label}
{copiedItem === item.label ? (
<span className="sr-only">copied to your clipboard</span>
) : null}
</div>
<div className="truncate text-sm text-foreground-lighter">
{item.displayValue}
</div>
</div>
<div
className={cn(
'absolute right-2 top-1/2 -translate-y-1/2 text-foreground-lighter opacity-0 transition-opacity group-hover:opacity-100',
copiedItem === item.label && 'opacity-100 text-primary'
)}
>
{copiedItem === item.label ? <CheckIcon size={14} /> : <CopyIcon size={14} />}
</div>
</DropdownMenuItem>
)
})}
<DropdownMenuSeparator />
<div className="p-1">
<Button
size="tiny"
className="w-full"
onClick={() => {
setOpen(false)
setConnectSheetSource('home_popover')
setShowConnect(true)
}}
>
Get Connected
</Button>
</div>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
)
}