Files
supabase/apps/studio/lib/telemetry/track.ts
Gildas Garcia c6fc456910 chore: cleanup duplicate exports studio (#47387)
## Problem

Knip reports many duplicate exports (both named and default). Besides,
we're moving away from default exports and even have an eslint rule to
enforce it on new code.

## Solution

- Cleanup those exports
- Update imports when necessary

No functional changes. If it builds, it's fine
2026-06-29 15:46:16 +02:00

71 lines
2.0 KiB
TypeScript

import { sendTelemetryEvent } from 'common'
import { TelemetryEvent, TelemetryGroups } from 'common/telemetry-constants'
import { useRouter } from 'next/router'
import { useCallback } from 'react'
import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { API_URL } from '@/lib/constants'
type EventMap = {
[E in TelemetryEvent as E['action']]: E
}
type PropertiesForAction<A extends keyof EventMap> = EventMap[A] extends { properties: infer P }
? P
: never
type HasProperties<A extends keyof EventMap> = EventMap[A] extends { properties: any }
? true
: false
/**
* Hook for type-safe telemetry event tracking with automatic project/org context injection.
*
* @example
* const track = useTrack()
* track('table_created', { method: 'sql_editor', schema_name: 'public' })
* track('help_button_clicked')
*/
export const useTrack = () => {
const { data: project } = useSelectedProjectQuery()
const { data: org } = useSelectedOrganizationQuery()
const router = useRouter()
const latest = useLatest({
projectRef: project?.ref,
orgSlug: org?.slug,
pathname: router.pathname,
})
const track = useCallback(
<A extends keyof EventMap>(
action: A,
...args: HasProperties<A> extends true
? [properties: PropertiesForAction<A>, groupOverrides?: Partial<TelemetryGroups>]
: [properties?: undefined, groupOverrides?: Partial<TelemetryGroups>]
) => {
const { projectRef, orgSlug, pathname } = latest.current
const [properties, groupOverrides] = args
const groups = {
...(projectRef && { project: projectRef }),
...(orgSlug && { organization: orgSlug }),
...groupOverrides,
}
const event = {
action,
...(properties && { properties }),
...(groups && { groups }),
} as EventMap[A]
sendTelemetryEvent(API_URL, event, pathname)
},
[]
)
return track
}