Files
supabase/apps/studio/components/interfaces/HomePageActions.tsx
Drew McLellan d4ef834d4d feat(studio): track usage on the org projects list (FE-5025) (#54417)
## Problem

We don't have visibility into how people use the org projects list
(`/org/[slug]`) or the organizations list (`/organizations`): whether
they search, filter, sort or switch views, and which project card
actions they use. Resolves FE-5025.

## Solution

Adds four events, defined in `packages/common/telemetry-constants.ts`
with org-level groups (no project group):

- `org_projects_filter_applied` with `filterType: 'search' | 'status' |
'sort'`. Search sends only the result count, status sends the saved
statuses (`active`/`paused`), and sort sends the sort value.
- `org_projects_view_mode_updated` with `viewMode`.
- `org_project_card_action_clicked` with `action: 'copy_id' |
'settings'` and `viewMode`, from the grid card menu and the table row
menu and inline ref button.
- `org_list_search_submitted` with `orgCount`.

Notes for review:

- Every event fires from its handler, not an effect, so restoring
filters from local storage doesn't fire anything.
- Search events use the same 500ms debounce as the query, skip empty
input, and never include the search text. The project search count is
read from the list query's cache entry via `fetchInfiniteQuery` on the
same key, which reuses the in-flight request.
- Status, sort and view events don't fire when the value didn't change.
- `HomePageActions` and `ProjectList` also render on the `/project`
picker, so `@page` lists both routes.
- I didn't add the `data-attr` attributes from the ticket: autocapture
is off, so they would send nothing, and the telemetry standards ask for
explicit `track()` calls.

## How to test

- `pnpm --filter studio exec vitest run
components/interfaces/HomePageActions.test.tsx` covers view mode, status
filter, search and clearing before the debounce settles.
- In the browser network tab on `/org/[slug]`, each action sends one
`telemetry/event` request with the properties above. Checking the events
in PostHog staging is still to do.
2026-12-02 11:47:18 +00:00

256 lines
9.5 KiB
TypeScript

import { keepPreviousData, useQueryClient } from '@tanstack/react-query'
import { Link, useNavigate } from '@tanstack/react-router'
import { useDebounce } from '@uidotdev/usehooks'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { GridIcon, ListIcon, Loader2Icon, PlusIcon, SearchIcon, XIcon } from 'lucide-react'
import { parseAsArrayOf, parseAsString, parseAsStringLiteral, useQueryState } from 'nuqs'
import { useEffect, useRef } from 'react'
import { Button, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import { useDebouncedCallback } from 'use-debounce'
import { FilterPopover } from '../ui/FilterPopover'
import { SortDropdown } from '../ui/SortDropdown'
import {
PROJECT_LIST_SORT_VALUES,
type ProjectListSort,
} from '@/components/interfaces/Home/ProjectList/ProjectListSort.utils'
import { Shortcut } from '@/components/ui/Shortcut'
import { projectKeys } from '@/data/projects/keys'
import {
getOrganizationProjects,
useOrgProjectsInfiniteQuery,
} from '@/data/projects/org-projects-infinite-query'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { PROJECT_STATUS } from '@/lib/constants'
import { onSearchInputEscape } from '@/lib/keyboard'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
const SEARCH_DEBOUNCE_MS = 500
const STATUS_TRACKING_VALUES: Record<string, 'active' | 'paused'> = {
[PROJECT_STATUS.ACTIVE_HEALTHY]: 'active',
[PROJECT_STATUS.INACTIVE]: 'paused',
}
interface HomePageActionsProps {
slug?: string
hideNewProject?: boolean
}
export const HomePageActions = ({ slug: _slug, hideNewProject = false }: HomePageActionsProps) => {
const { slug: urlSlug } = useParams()
const navigate = useNavigate()
const track = useTrack()
const queryClient = useQueryClient()
const projectCreationEnabled = useIsFeatureEnabled('projects:create')
const slug = _slug ?? urlSlug
const [search, setSearch] = useQueryState('search', parseAsString.withDefault(''))
const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS)
const [filterStatus, setFilterStatus] = useQueryState(
'status',
parseAsArrayOf(parseAsString, ',').withDefault([])
)
const [sort, setSort] = useQueryState(
'sort',
parseAsStringLiteral(PROJECT_LIST_SORT_VALUES).withDefault('name_asc')
)
const [viewMode, setViewMode] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.PROJECTS_VIEW, 'grid')
const [filterStatusStorage, setFilterStatusStorage, { isSuccess: isSuccessFilterStatusStorage }] =
useLocalStorageQuery<string[]>(LOCAL_STORAGE_KEYS.PROJECTS_FILTER, [])
const [sortStorage, setSortStorage, { isSuccess: isSuccessSortStorage }] =
useLocalStorageQuery<ProjectListSort>(LOCAL_STORAGE_KEYS.PROJECTS_SORT, 'name_asc')
const { isFetching: isFetchingProjects } = useOrgProjectsInfiniteQuery(
{
slug,
sort,
search: search.length === 0 ? search : debouncedSearch,
statuses: filterStatus,
},
{ placeholderData: keepPreviousData }
)
const searchInputRef = useRef<HTMLInputElement>(null)
// Filter, sort and search only take effect when there is a slug (the project picker mounts this
// without one, where saves never reach the URL), so there is nothing to track without it.
//
// Waits for the same debounce as the query, then reads the result count from that query's cache
// entry. It uses the list query's key, so it shares the list query's in-flight request, and an
// existing entry is returned as is. Skips empty searches and never sends the search text.
const trackSearch = useDebouncedCallback(async (value: string) => {
if (!slug || value.length === 0) return
try {
const statuses = filterStatus
const data = await queryClient.ensureInfiniteQueryData({
queryKey: projectKeys.infiniteListByOrg(slug, { sort, search: value, statuses, refs: [] }),
queryFn: ({ signal, pageParam }) =>
getOrganizationProjects({ slug, page: pageParam, sort, search: value, statuses }, signal),
initialPageParam: 0,
})
const projectCount = data.pages[0]?.pagination?.count
if (projectCount !== undefined) {
track('org_projects_filter_applied', { filterType: 'search', projectCount })
}
} catch {
// No result count to report when the search request failed
}
}, SEARCH_DEBOUNCE_MS)
const handleSearchChange = (value: string) => {
setSearch(value)
if (value.length === 0) trackSearch.cancel()
else trackSearch(value)
}
const handleSaveStatusFilter = (options: string[]) => {
setFilterStatusStorage(options)
if (!slug) return
const hasChanged =
options.length !== filterStatus.length || options.some((x) => !filterStatus.includes(x))
if (!hasChanged) return
track('org_projects_filter_applied', {
filterType: 'status',
statuses: options.flatMap((x) => STATUS_TRACKING_VALUES[x] ?? []),
})
}
const handleSortChange = (value: ProjectListSort) => {
setSortStorage(value)
if (slug && value !== sort)
track('org_projects_filter_applied', { filterType: 'sort', sort: value })
}
const handleViewModeChange = (value: 'grid' | 'table') => {
setViewMode(value)
if (value !== viewMode) track('org_projects_view_mode_updated', { viewMode: value })
}
useShortcut(SHORTCUT_IDS.ORG_PROJECTS_SEARCH, () => {
searchInputRef.current?.focus()
})
useEffect(() => {
if (isSuccessFilterStatusStorage && !!slug) setFilterStatus(filterStatusStorage)
}, [filterStatusStorage, isSuccessFilterStatusStorage, setFilterStatus, slug])
useEffect(() => {
if (isSuccessSortStorage && slug) setSort(sortStorage)
}, [sortStorage, isSuccessSortStorage, setSort, slug])
return (
<div className="flex flex-wrap items-center justify-between gap-2 w-full">
<div className="flex flex-col gap-2 min-w-0 flex-1 basis-full md:basis-auto sm:flex-row sm:flex-wrap sm:items-center">
<Input
ref={searchInputRef}
placeholder="Search for a project"
icon={<SearchIcon />}
size="tiny"
className="w-full sm:w-32 md:w-64"
value={search}
onChange={(event) => handleSearchChange(event.target.value)}
onKeyDown={onSearchInputEscape(search, handleSearchChange)}
actions={[
search && (
<Button
key="clear"
size="tiny"
variant="text"
icon={<XIcon />}
onClick={() => handleSearchChange('')}
className="p-0 h-5 w-5"
aria-label="Clear"
/>
),
]}
/>
<div className="flex items-center gap-2">
<FilterPopover
name="Status"
title="Filter projects by status"
options={
[
{ key: PROJECT_STATUS.ACTIVE_HEALTHY, label: 'Active' },
{ key: PROJECT_STATUS.INACTIVE, label: 'Paused' },
] as { key: string; label: string }[]
}
activeOptions={filterStatus}
valueKey="key"
labelKey="label"
onSaveFilters={handleSaveStatusFilter}
/>
<SortDropdown
options={[
{ label: 'name', value: 'name' },
{ label: 'creation date', value: 'created' },
]}
value={sort}
setValue={(val) => handleSortChange(val as ProjectListSort)}
/>
{isFetchingProjects && <Loader2Icon className="animate-spin" size={14} />}
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{viewMode && (
<ToggleGroup
type="single"
size="sm"
value={viewMode}
onValueChange={(value) => value && handleViewModeChange(value as 'grid' | 'table')}
>
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem value="grid" className="h-[26px] w-[26px] p-0">
<GridIcon size={14} strokeWidth={1.5} />
<span className="sr-only">Toggle grid view</span>
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>Toggle grid view</p>
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem value="table" className="h-[26px] w-[26px] p-0">
<ListIcon size={14} strokeWidth={1.5} />
<span className="sr-only">Toggle list view</span>
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>Toggle list view</p>
</TooltipContent>
</Tooltip>
</ToggleGroup>
)}
{projectCreationEnabled && !hideNewProject && (
<Shortcut
id={SHORTCUT_IDS.ORG_PROJECTS_NEW}
onTrigger={() => {
if (slug) navigate({ to: '/new/$slug', params: { slug } })
}}
side="bottom"
>
<Button asChild icon={<PlusIcon />} variant="primary" size="tiny">
<Link to="/new/$slug" params={{ slug: slug ?? '_' }}>
New project
</Link>
</Button>
</Shortcut>
)}
</div>
</div>
)
}