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('') const searchTrackTimerRef = useRef | null>(null) const [isSchemaDropdownOpen, setIsSchemaDropdownOpen] = useState(false) const [tableToExport, setTableToExport] = useState() const [visibleTypes, setVisibleTypes] = useState(Object.values(ENTITY_TYPE)) const [sort, setSort] = useLocalStorage('table-editor-sort', 'alphabetical') const [partitionParentId, setPartitionParentId] = useState() 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(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 ( <>
{!isSchemaLocked ? ( } className="justify-start" onClick={handleAddTable} tooltip={{ content: { side: 'bottom', text: !canCreateTables ? 'You need additional permissions to create tables' : undefined, }, }} > New table ) : ( )}
{partitionParentId !== undefined && ( )} {partitionParentId === undefined && (
handleSearchChange(e.target.value)} > setSort(value as Sort)} > Alphabetical Entity Type } aria-label="Filter" tooltip={{ content: { side: 'bottom', text: 'Filter' } }} />

Filter entity types

{Object.entries(ENTITY_TYPE).map(([key, value]) => (
{ if (visibleTypes.includes(value)) { handleVisibleTypesChange( visibleTypes.filter((y) => y !== value) ) } else { handleVisibleTypesChange(visibleTypes.concat([value])) } }} />
))}
{visibleTypes.length === 0 && ( handleVisibleTypesChange(Object.values(ENTITY_TYPE))} /> )} {isLoading && } {isError && ( } /> )} {isSuccess && ( <> {searchText.length === 0 && (entityTypes?.length ?? 0) <= 0 && ( )} {searchText.length > 0 && (entityTypes?.length ?? 0) <= 0 && ( )} {(entityTypes?.length ?? 0) > 0 && (
index !== 0 && index === entityTypes!.length ? 85 : 28 } hasNextPage={hasNextPage} isLoadingNextPage={isFetchingNextPage} onLoadNextPage={fetchNextPage} />
)} )}
)}
{ if (!open) setTableToExport(undefined) }} /> ) }