Files
supabase/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
Alaister YoungandAlaister Young 217b9ca3f3 [FE-5024] feat(studio): track Table Editor sidebar and side panels (#53960)
Adds PostHog telemetry events across the Table Editor sidebar, new-tab
page, and column/table/row/cell side panels so we can measure schema
usage, entity-list search/filtering, entity menu actions, and panel
saves without logging schema, table, column, or search names.

**Added:**

- Event definitions in `packages/common/telemetry-constants.ts` (added
to `TelemetryEvent`):
- `table_editor_schema_selector_updated` (`schemaType: 'public' |
'protected' | 'custom'`) when switching schemas in `TableEditorMenu`. It
uses the same `schemaType` property and derivation as the existing
`database_schema_selector_updated` (now shared through
`getDatabaseSchemaType`), so the two selectors can be compared in one
insight
- `table_editor_new_item_clicked` (`itemType: 'schema'` or `itemType:
'table'` with `trigger: 'sidebar' | 'new_tab_card'`) from the sidebar
and `NewTab` card
- `table_editor_table_search_submitted` (debounced 500ms, cancelled on
clear, schema switch via selector or URL/tab change, and unmount)
- `table_editor_entity_filter_updated` (`visibleTypeCount`) on
entity-type checkbox toggle, "Select only", and filter reset
- `table_editor_entity_action_clicked` (`action`, `entityType`) across
dropdown and context menus in `useEntityActionHandlers` (excluding the
`View policies` link, which is covered by pageviews)
- `table_column_created` / `table_column_updated` (`hasForeignKey`,
`isArray`) on column side-panel saves via `SidePanelEditor.utils.tsx`,
with `hasForeignKey` scoped to the saved column and no-op saves skipped
- `table_updated` (`columnCountChanged`) on existing table edits in
`SidePanelEditor.tsx` once table, column, primary key, foreign key,
Realtime, and Data API updates succeed and at least one change was
persisted; no-op saves and saves where any step fails are skipped
- `table_editor_row_updated` (`editMethod: 'side_panel'`) when an
existing row edit from the row side panel is persisted. Saves from the
expanded cell editors and the foreign row selector don't count, and
neither do edits queued with queue operations enabled. The grid ticket
(FE-5023) can add more `editMethod` values when it tracks inline edits
- `table_editor_cell_editor_opened` (`editorType: 'json' | 'text'`) when
expanding JSON or text cell editors from the grid cell editors
(`JsonEditor` / `TextEditor`) or `RowEditor`
- Column, table and row save events are attributed to the project the
save ran against (third `track()` argument), and fire only after the
save succeeds
- Focused MSW-backed tests for non-obvious telemetry edge cases (search
debounce + cancellation on clear and selector/external schema switches,
schema switch single-fire + PII checks, column-scoped FK/array
derivation and no-op gating in `createColumn`/`updateColumn`,
change/error reporting in `updateTable` without double-firing column
events)

## To test

Watch `POST /platform/telemetry/event` in DevTools (and confirm arrival
in staging PostHog):

- Switch schemas (`public` -> `auth` -> custom schema -> `public`):
fires `table_editor_schema_selector_updated` with `schemaType`
`protected` -> `custom` -> `public` and no schema name; re-selecting the
active schema fires nothing
- On the Database > Schemas visualizer, switching schemas still fires
`database_schema_selector_updated` with the same `schemaType` values as
before
- Click **Create a new schema** and **New table** in the sidebar, plus
**Create a table** on `/project/[ref]/editor/new`: fires
`table_editor_new_item_clicked` with the expected `itemType` and
`trigger`
- Type in **Search tables...** and pause >500ms: fires one
`table_editor_table_search_submitted` with no query text; clearing or
switching schemas (via the selector or clicking a tab in another schema)
before 500ms fires nothing
- Toggle entity-type checkboxes, click **Select only**, or reset
filters: fires `table_editor_entity_filter_updated` with the new
`visibleTypeCount`
- Trigger actions from a table/view menu (both ⋮ and right-click): fires
`table_editor_entity_action_clicked` with `action` and `entityType`
(**View policies** does not fire it)
- Create and edit a column via the column panel: fires
`table_column_created` / `table_column_updated` with `hasForeignKey`
(scoped to that column) and `isArray`; clicking **Save** with no changes
fires nothing
- Edit an existing table (with and without adding/removing a column, or
toggling Realtime alone): fires `table_updated` with
`columnCountChanged`, without firing `table_column_*`; clicking **Save**
with no changes fires nothing
- Edit an existing row in the row side panel: fires
`table_editor_row_updated` with `editMethod: 'side_panel'`. Inserting a
new row, saving from an expanded JSON/text cell editor, picking a
foreign row, or saving with queue operations enabled does not fire it
- Edit an existing table so that adding a column (or updating
Realtime/Data API) fails: `table_updated` does not fire
- Expand JSON and text cell editors from both the grid and inside the
row panel: fires `table_editor_cell_editor_opened` with `editorType:
'json' | 'text'`

Notes for review:

- No `data-attr`s were added. Autocapture is off, so each tracked
interaction gets an explicit `track()` call instead.
- `table_editor_cell_editor_opened` counts the expand buttons in both
the grid cell editors and the row side panel fields. It's the same click
on both surfaces.
- `table_editor_row_updated` only has `editMethod: 'side_panel'` for
now. The grid toolbar ticket (FE-5023) can add values when it tracks
inline edits.

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-02 18:54:08 +08:00

519 lines
20 KiB
TypeScript

import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import { FilterIcon, PlusIcon } from 'lucide-react'
import { AnimatePresence, motion } from 'motion/react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Button, Checkbox, Label, Popover, PopoverContent, PopoverTrigger } from 'ui'
import {
InnerSideBarEmptyPanel,
InnerSideBarFilters,
InnerSideBarFilterSearchInput,
InnerSideBarFilterSortDropdown,
InnerSideBarFilterSortDropdownItem,
} from 'ui-patterns/InnerSideMenu'
import { useTableEditorTabsCleanUp } from '../Tabs/Tabs.utils'
import { EntityListItem } from './EntityListItem'
import { PartitionListMenu } from './PartitionListMenu'
import { TableMenuEmptyState } from './TableMenuEmptyState'
import { TableMenuFilterEmptyState } from './TableMenuFilterEmptyState'
import { ExportDialog } from '@/components/grid/components/header/ExportDialog'
import { parseSupaTable } from '@/components/grid/SupabaseGrid.utils'
import { SupaTable } from '@/components/grid/types'
import { ProtectedSchemaWarning } from '@/components/interfaces/Database/ProtectedSchemaWarning'
import { ErrorMatcher } from '@/components/interfaces/ErrorHandling/ErrorMatcher'
import { RestartTroubleshootingFallback } from '@/components/interfaces/ErrorHandling/RestartTroubleshootingFallback'
import {
LEVEL_OFFSET,
LEVEL_TRANSITION,
} from '@/components/layouts/ExplorerLayout/ExplorerLayout.constants'
import { EditorMenuListSkeleton } from '@/components/layouts/TableEditorLayout/EditorMenuListSkeleton'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { InfiniteListDefault, LoaderForIconMenuItems } from '@/components/ui/InfiniteList'
import { SchemaSelector } from '@/components/ui/SchemaSelector'
import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
import { entitiesByIdsQueryOptions } from '@/data/entity-types/entities-by-ids-query'
import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'
import { useEntityTypesQuery } from '@/data/entity-types/entity-types-infinite-query'
import { partitionInfoQueryOptions } from '@/data/entity-types/partition-info-query'
import { useTableApiAccessQuery } from '@/data/privileges/table-api-access-query'
import { getTableEditor, useTableEditorQuery } from '@/data/table-editor/table-editor-query'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import {
getDatabaseSchemaType,
useIsProtectedSchema,
useProtectedSchemas,
} from '@/hooks/useProtectedSchemas'
import { useTrack } from '@/lib/telemetry/track'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
import { useTableEditorStateSnapshot } from '@/state/table-editor'
type Sort = 'alphabetical' | 'grouped-alphabetical'
export const TABLE_SEARCH_TRACK_DEBOUNCE_MS = 500
export const TableEditorMenu = () => {
const { id: _id, ref: projectRef } = useParams()
const id = _id ? Number(_id) : undefined
const track = useTrack()
const snap = useTableEditorStateSnapshot()
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
const [searchText, setSearchText] = useState<string>('')
const searchTrackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const [isSchemaDropdownOpen, setIsSchemaDropdownOpen] = useState(false)
const [tableToExport, setTableToExport] = useState<SupaTable>()
const [visibleTypes, setVisibleTypes] = useState<string[]>(Object.values(ENTITY_TYPE))
const [sort, setSort] = useLocalStorage<Sort>('table-editor-sort', 'alphabetical')
const [partitionParentId, setPartitionParentId] = useState<number>()
const queryClient = useQueryClient()
const { data: project } = useSelectedProjectQuery()
const {
data,
isLoading,
isSuccess,
isError,
error,
hasNextPage,
isFetchingNextPage,
fetchNextPage,
} = useEntityTypesQuery(
{
projectRef: project?.ref,
connectionString: project?.connectionString,
schemas: [selectedSchema],
search: searchText.trim() || undefined,
sort,
filterTypes: visibleTypes,
excludePartitions: true,
},
{
enabled: visibleTypes.length > 0,
placeholderData: Boolean(searchText) ? keepPreviousData : undefined,
}
)
const entityTypes = useMemo(
() => data?.pages.flatMap((page) => page.data.entities),
[data?.pages]
)
const entityNames = useMemo(() => entityTypes?.map((entity) => entity.name) ?? [], [entityTypes])
const { data: apiAccessByTableName } = useTableApiAccessQuery(
{
projectRef: project?.ref,
connectionString: project?.connectionString ?? undefined,
schemaName: selectedSchema,
tableNames: entityNames,
},
{ enabled: Boolean(selectedSchema && entityNames.length > 0) }
)
const { can: canCreateTables } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.DATABASE_WRITE
)
const { isSchemaLocked } = useIsProtectedSchema({ schema: selectedSchema })
const { data: protectedSchemas } = useProtectedSchemas()
const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
const isSelectedTableLike =
selectedTable?.entity_type === ENTITY_TYPE.TABLE ||
selectedTable?.entity_type === ENTITY_TYPE.PARTITIONED_TABLE
const { data: selectedTableInfo } = useQuery({
...partitionInfoQueryOptions({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
}),
enabled: !!project?.ref && isSelectedTableLike,
})
if (selectedTable?.schema && !selectedSchema) {
setSelectedSchema(selectedTable.schema)
}
useShortcut(SHORTCUT_IDS.TABLE_EDITOR_FOCUS_SCHEMA, () => setIsSchemaDropdownOpen(true), {
registerInCommandMenu: true,
})
const tableEditorTabsCleanUp = useTableEditorTabsCleanUp()
const cancelPendingSearchTrack = useCallback(() => {
if (searchTrackTimerRef.current !== null) {
clearTimeout(searchTrackTimerRef.current)
searchTrackTimerRef.current = null
}
}, [])
const previousSchemaRef = useRef(selectedSchema)
useEffect(() => {
if (previousSchemaRef.current !== selectedSchema) {
previousSchemaRef.current = selectedSchema
cancelPendingSearchTrack()
}
}, [selectedSchema, cancelPendingSearchTrack])
useEffect(() => cancelPendingSearchTrack, [cancelPendingSearchTrack])
const handleSelectSchema = (name: string) => {
cancelPendingSearchTrack()
setSearchText('')
setPartitionParentId(undefined)
setSelectedSchema(name)
setIsSchemaDropdownOpen(false)
if (name !== selectedSchema) {
track('table_editor_schema_selector_updated', {
schemaType: getDatabaseSchemaType(name, protectedSchemas),
})
}
}
const handleSelectCreateSchema = () => {
track('table_editor_new_item_clicked', { itemType: 'schema' })
snap.onAddSchema()
setIsSchemaDropdownOpen(false)
}
const handleAddTable = () => {
track('table_editor_new_item_clicked', { itemType: 'table', trigger: 'sidebar' })
snap.onAddTable()
}
const handleSearchChange = (value: string) => {
setSearchText(value)
cancelPendingSearchTrack()
if (value.trim().length > 0) {
searchTrackTimerRef.current = setTimeout(() => {
searchTrackTimerRef.current = null
track('table_editor_table_search_submitted')
}, TABLE_SEARCH_TRACK_DEBOUNCE_MS)
}
}
const handleVisibleTypesChange = (nextVisibleTypes: string[]) => {
const isUnchanged =
nextVisibleTypes.length === visibleTypes.length &&
nextVisibleTypes.every((type) => visibleTypes.includes(type))
if (isUnchanged) return
setVisibleTypes(nextVisibleTypes)
track('table_editor_entity_filter_updated', {
visibleTypeCount: nextVisibleTypes.length,
})
}
const onSelectExportCLI = useCallback(
async (id: number) => {
const table = await getTableEditor({
id: id,
projectRef,
connectionString: project?.connectionString,
})
const supaTable = table && parseSupaTable(table)
setTableToExport(supaTable)
},
[project?.connectionString, projectRef]
)
const getItemKey = useCallback(
(index: number) => {
const item = entityTypes?.[index]
return item?.id ? String(item.id) : `table-editor-entity-${index}`
},
[entityTypes]
)
const entityProps = useMemo(
() => ({
projectRef: project?.ref!,
id: Number(id),
isLocked: isSchemaLocked,
onExportCLI: onSelectExportCLI,
apiAccessMap: apiAccessByTableName,
onViewPartitions: setPartitionParentId,
}),
[
project?.ref,
id,
isSchemaLocked,
onSelectExportCLI,
apiAccessByTableName,
setPartitionParentId,
]
)
const slideOffset = partitionParentId === undefined ? -LEVEL_OFFSET : LEVEL_OFFSET
const hasFiltersApplied = visibleTypes.length !== 5
// Sync the partition view to each newly selected table: a partition shows its parent's list,
// anything else shows the main list (unless it is the table whose partitions are open)
const syncedForIdRef = useRef<number | undefined>(undefined)
useEffect(() => {
const isSelectionResolved =
selectedTable !== undefined && (!isSelectedTableLike || selectedTableInfo !== undefined)
if (id === undefined || !isSelectionResolved || syncedForIdRef.current === id) return
syncedForIdRef.current = id
const parentId = selectedTableInfo?.parent_id
if (parentId != null) setPartitionParentId(parentId)
else if (id !== partitionParentId) setPartitionParentId(undefined)
}, [id, selectedTable, isSelectedTableLike, selectedTableInfo, partitionParentId])
useEffect(() => {
// Clean up tabs + recent items for any tables that might have been removed outside of the dashboard session
if (entityTypes && !searchText) {
tableEditorTabsCleanUp({
schemas: [selectedSchema],
entities: entityTypes,
resolveEntities: (ids) =>
queryClient.fetchQuery(
entitiesByIdsQueryOptions({
projectRef: project?.ref,
connectionString: project?.connectionString,
ids,
})
),
}).catch(() => {
// Lookup failed: keep all tabs
})
}
}, [
entityTypes,
searchText,
selectedSchema,
tableEditorTabsCleanUp,
queryClient,
project?.ref,
project?.connectionString,
])
return (
<>
<div className="flex flex-col grow gap-5 pt-5 h-full">
<div className="flex flex-col gap-y-1.5">
<ShortcutTooltip
shortcutId={SHORTCUT_IDS.TABLE_EDITOR_FOCUS_SCHEMA}
label="Switch schema"
side="bottom"
open={isSchemaDropdownOpen ? false : undefined}
>
<SchemaSelector
className="mx-4"
selectedSchemaName={selectedSchema}
onSelectSchema={handleSelectSchema}
onSelectCreateSchema={handleSelectCreateSchema}
open={isSchemaDropdownOpen}
onOpenChange={setIsSchemaDropdownOpen}
/>
</ShortcutTooltip>
<div className="grid gap-3 mx-4">
{!isSchemaLocked ? (
<ButtonTooltip
block
title="Create a new table"
name="New table"
disabled={!canCreateTables}
size="tiny"
icon={<PlusIcon size={14} strokeWidth={1.5} className="text-foreground-muted" />}
className="justify-start"
onClick={handleAddTable}
tooltip={{
content: {
side: 'bottom',
text: !canCreateTables
? 'You need additional permissions to create tables'
: undefined,
},
}}
>
New table
</ButtonTooltip>
) : (
<ProtectedSchemaWarning size="sm" schema={selectedSchema} entity="table" />
)}
</div>
</div>
<div className="relative grow min-h-0 overflow-hidden flex flex-col">
<AnimatePresence mode="wait">
<motion.div
key={partitionParentId ?? 'tables'}
initial={{ opacity: 0, x: slideOffset }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: slideOffset }}
transition={LEVEL_TRANSITION}
className="grow min-h-0 flex flex-col"
>
{partitionParentId !== undefined && (
<PartitionListMenu
parentId={partitionParentId}
schema={selectedSchema}
onViewPartitions={setPartitionParentId}
onBack={setPartitionParentId}
itemProps={entityProps}
/>
)}
{partitionParentId === undefined && (
<div className="grow min-h-0 flex flex-col gap-2 pb-4">
<InnerSideBarFilters className="mx-2">
<InnerSideBarFilterSearchInput
name="search-tables"
value={searchText}
placeholder="Search tables..."
aria-labelledby="Search tables"
onChange={(e) => handleSearchChange(e.target.value)}
>
<InnerSideBarFilterSortDropdown
value={sort}
onValueChange={(value) => setSort(value as Sort)}
>
<InnerSideBarFilterSortDropdownItem
key="alphabetical"
value="alphabetical"
className="flex gap-2"
>
Alphabetical
</InnerSideBarFilterSortDropdownItem>
<InnerSideBarFilterSortDropdownItem
key="grouped-alphabetical"
value="grouped-alphabetical"
>
Entity Type
</InnerSideBarFilterSortDropdownItem>
</InnerSideBarFilterSortDropdown>
</InnerSideBarFilterSearchInput>
<Popover>
<PopoverTrigger asChild>
<ButtonTooltip
className="h-[32px] md:h-[28px] px-1.5"
variant={hasFiltersApplied ? 'default' : 'dashed'}
icon={<FilterIcon />}
aria-label="Filter"
tooltip={{ content: { side: 'bottom', text: 'Filter' } }}
/>
</PopoverTrigger>
<PopoverContent className="p-0 w-60" side="bottom" align="center">
<div className="px-3 pt-3 pb-2 flex flex-col gap-y-2">
<p className="text-xs">Filter entity types</p>
<div className="flex flex-col">
{Object.entries(ENTITY_TYPE).map(([key, value]) => (
<div
key={key}
className="group flex items-center justify-between py-0.5"
>
<div className="flex items-center gap-x-2">
<Checkbox
id={key}
name={key}
checked={visibleTypes.includes(value)}
onCheckedChange={() => {
if (visibleTypes.includes(value)) {
handleVisibleTypesChange(
visibleTypes.filter((y) => y !== value)
)
} else {
handleVisibleTypesChange(visibleTypes.concat([value]))
}
}}
/>
<Label htmlFor={key} className="capitalize text-xs">
{key.toLowerCase().replace('_', ' ')}
</Label>
</div>
<Button
size="tiny"
onClick={() => handleVisibleTypesChange([value])}
className="transition opacity-0 group-hover:opacity-100 h-auto px-1 py-0.5"
>
Select only
</Button>
</div>
))}
</div>
</div>
</PopoverContent>
</Popover>
</InnerSideBarFilters>
{visibleTypes.length === 0 && (
<TableMenuFilterEmptyState
onResetFilters={() => handleVisibleTypesChange(Object.values(ENTITY_TYPE))}
/>
)}
{isLoading && <EditorMenuListSkeleton />}
{isError && (
<ErrorMatcher
title="Failed to load tables"
error={error ?? 'Failed to load tables'}
supportFormParams={{ projectRef: project?.ref }}
className="mx-4 mt-3"
fallback={<RestartTroubleshootingFallback />}
/>
)}
{isSuccess && (
<>
{searchText.length === 0 && (entityTypes?.length ?? 0) <= 0 && (
<TableMenuEmptyState />
)}
{searchText.length > 0 && (entityTypes?.length ?? 0) <= 0 && (
<InnerSideBarEmptyPanel
className="mx-2"
title="No results found"
description={`Your search for "${searchText}" did not return any results`}
/>
)}
{(entityTypes?.length ?? 0) > 0 && (
<div className="flex flex-1 min-h-0 w-full" data-testid="tables-list">
<InfiniteListDefault
className="h-full w-full"
items={entityTypes!}
ItemComponent={EntityListItem}
LoaderComponent={LoaderForIconMenuItems}
itemProps={entityProps}
getItemKey={getItemKey}
getItemSize={(index) =>
index !== 0 && index === entityTypes!.length ? 85 : 28
}
hasNextPage={hasNextPage}
isLoadingNextPage={isFetchingNextPage}
onLoadNextPage={fetchNextPage}
/>
</div>
)}
</>
)}
</div>
)}
</motion.div>
</AnimatePresence>
</div>
</div>
<ExportDialog
ignoreRoleImpersonation
table={tableToExport}
open={!!tableToExport}
onOpenChange={(open) => {
if (!open) setTableToExport(undefined)
}}
/>
</>
)
}