mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
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>
669 lines
25 KiB
TypeScript
669 lines
25 KiB
TypeScript
import '@xyflow/react/dist/style.css'
|
||
|
||
import type { PGSchema } from '@supabase/pg-meta'
|
||
import { Link } from '@tanstack/react-router'
|
||
import {
|
||
Background,
|
||
BackgroundVariant,
|
||
ColorMode,
|
||
Edge,
|
||
MiniMap,
|
||
Node,
|
||
OnSelectionChangeParams,
|
||
Panel,
|
||
ReactFlow,
|
||
useReactFlow,
|
||
} from '@xyflow/react'
|
||
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
|
||
import {
|
||
CheckIcon,
|
||
ChevronDownIcon,
|
||
CopyIcon,
|
||
DownloadIcon,
|
||
Loader2Icon,
|
||
PlusIcon,
|
||
} from 'lucide-react'
|
||
import { useTheme } from 'next-themes'
|
||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||
import { toast } from 'sonner'
|
||
import {
|
||
AlertDialog,
|
||
AlertDialogAction,
|
||
AlertDialogCancel,
|
||
AlertDialogContent,
|
||
AlertDialogDescription,
|
||
AlertDialogFooter,
|
||
AlertDialogHeader,
|
||
AlertDialogTitle,
|
||
AlertDialogTrigger,
|
||
Button,
|
||
copyToClipboard,
|
||
DropdownMenu,
|
||
DropdownMenuContent,
|
||
DropdownMenuItem,
|
||
DropdownMenuTrigger,
|
||
SplitButtonGroup,
|
||
} from 'ui'
|
||
import { Admonition } from 'ui-patterns/Admonition'
|
||
|
||
import { SidePanelEditor } from '../../TableGridEditor/SidePanelEditor/SidePanelEditor'
|
||
import { useTableActions } from '../../TableGridEditor/useTableActions'
|
||
import { DefaultEdge } from './DefaultEdge'
|
||
import { FindTableSelector } from './FindTableSelector'
|
||
import { SchemaGraphContextProvider, SchemaGraphContextType } from './SchemaGraphContext'
|
||
import { SchemaGraphLegend } from './SchemaGraphLegend'
|
||
import { EdgeData, TableNodeData } from './Schemas.constants'
|
||
import {
|
||
getEnumsAsMarkdown,
|
||
getGraphDataFromTables,
|
||
getLayoutedElementsViaDagre,
|
||
getPoliciesAsMarkdown,
|
||
getSchemaAsMarkdown,
|
||
} from './Schemas.utils'
|
||
import { TableNode } from './SchemaTableNode'
|
||
import { useExportSchemaToImage } from './useExportSchemaToImage'
|
||
import { AlertError } from '@/components/ui/AlertError'
|
||
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
||
import { SchemaSelector } from '@/components/ui/SchemaSelector'
|
||
import { Shortcut } from '@/components/ui/Shortcut'
|
||
import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
|
||
import { useSchemasQuery } from '@/data/database/schemas-query'
|
||
import { useEnumeratedTypesQuery } from '@/data/enumerated-types/enumerated-types-query'
|
||
import { useInfiniteTablesQuery } from '@/data/tables/tables-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 { tablesToSQL } from '@/lib/helpers'
|
||
import type { SafePostgresTable } from '@/lib/postgres-types'
|
||
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'
|
||
|
||
// [Joshen] Persisting logic: Only save positions to local storage WHEN a node is moved OR when explicitly clicked to reset layout
|
||
|
||
export const SchemaGraph = () => {
|
||
const { ref } = useParams()
|
||
const { resolvedTheme } = useTheme()
|
||
const { data: project } = useSelectedProjectQuery()
|
||
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
|
||
const [selectedTable, setSelectedTable] = useState<SafePostgresTable | null>(null)
|
||
const snap = useTableEditorStateSnapshot()
|
||
const { editTable } = useTableActions()
|
||
const { isDownloading, exportSchemaToImage } = useExportSchemaToImage()
|
||
const track = useTrack()
|
||
const { data: protectedSchemas } = useProtectedSchemas()
|
||
|
||
const [copied, setCopied] = useState(false)
|
||
useEffect(() => {
|
||
if (copied) {
|
||
setTimeout(() => setCopied(false), 2000)
|
||
}
|
||
}, [copied])
|
||
|
||
const miniMapNodeColor = '#111318'
|
||
const miniMapMaskColor = resolvedTheme?.includes('dark')
|
||
? 'rgb(17, 19, 24, .8)'
|
||
: 'rgb(237, 237, 237, .8)'
|
||
|
||
const reactFlowInstance = useReactFlow()
|
||
const nodeTypes = useMemo(
|
||
() => ({
|
||
table: TableNode,
|
||
}),
|
||
[]
|
||
)
|
||
const edgeTypes = useMemo(
|
||
() => ({
|
||
default: DefaultEdge,
|
||
}),
|
||
[]
|
||
)
|
||
|
||
const {
|
||
data: schemas,
|
||
error: errorSchemas,
|
||
isSuccess: isSuccessSchemas,
|
||
isPending: isLoadingSchemas,
|
||
isError: isErrorSchemas,
|
||
} = useSchemasQuery({
|
||
projectRef: project?.ref,
|
||
connectionString: project?.connectionString,
|
||
})
|
||
|
||
const {
|
||
data: tablesData,
|
||
error: errorTables,
|
||
isSuccess: isSuccessTables,
|
||
isPending: isLoadingTables,
|
||
isError: isErrorTables,
|
||
hasNextPage,
|
||
isFetchingNextPage,
|
||
fetchNextPage,
|
||
} = useInfiniteTablesQuery({
|
||
projectRef: project?.ref,
|
||
connectionString: project?.connectionString,
|
||
schema: selectedSchema,
|
||
includeColumns: true,
|
||
pageSize: 100,
|
||
})
|
||
const tables = useMemo(() => tablesData?.pages.flat() ?? [], [tablesData])
|
||
const hasNoTables = isSuccessTables && isSuccessSchemas && tables.length === 0 && !hasNextPage
|
||
|
||
const { data: enumeratedTypes = [], isPending: isLoadingEnumeratedTypes } =
|
||
useEnumeratedTypesQuery({
|
||
projectRef: project?.ref,
|
||
connectionString: project?.connectionString,
|
||
})
|
||
|
||
const { data: policies = [], isPending: isLoadingPolicies } = useDatabasePoliciesQuery({
|
||
projectRef: project?.ref,
|
||
connectionString: project?.connectionString,
|
||
schemas: [selectedSchema],
|
||
})
|
||
|
||
const isMarkdownDataLoading = isLoadingEnumeratedTypes || isLoadingPolicies
|
||
|
||
const schema = (schemas ?? []).find((s) => s.name === selectedSchema)
|
||
const [, setStoredPositions] = useLocalStorage(
|
||
LOCAL_STORAGE_KEYS.SCHEMA_VISUALIZER_POSITIONS(ref as string, schema?.id ?? 0),
|
||
{}
|
||
)
|
||
|
||
const { can: canUpdateTables } = useAsyncCheckPermissionsV2(
|
||
FGA_PERMISSIONS.PROJECT.DATABASE_WRITE
|
||
)
|
||
|
||
const { isSchemaLocked } = useIsProtectedSchema({ schema: selectedSchema })
|
||
|
||
const canAddTables = canUpdateTables && !isSchemaLocked
|
||
|
||
const resetLayout = async () => {
|
||
const nodes = reactFlowInstance.getNodes()
|
||
const edges = reactFlowInstance.getEdges()
|
||
|
||
getLayoutedElementsViaDagre(
|
||
nodes.filter((item) => item.type === 'table') as Node<TableNodeData>[],
|
||
edges
|
||
)
|
||
reactFlowInstance.setNodes(nodes)
|
||
reactFlowInstance.setEdges(edges)
|
||
track('database_schema_visualizer_auto_layout_applied')
|
||
await new Promise<void>((resolve) =>
|
||
setTimeout(async () => {
|
||
await reactFlowInstance.fitView({})
|
||
resolve()
|
||
})
|
||
)
|
||
saveNodePositions()
|
||
}
|
||
|
||
const saveNodePositions = useCallback(() => {
|
||
if (schema === undefined) return console.error('Schema is required')
|
||
|
||
const nodes = reactFlowInstance.getNodes()
|
||
if (nodes.length > 0) {
|
||
const nodesPositionData = nodes.reduce((a, b) => {
|
||
return { ...a, [b.id]: b.position }
|
||
}, {})
|
||
setStoredPositions(nodesPositionData)
|
||
}
|
||
}, [schema, reactFlowInstance, setStoredPositions])
|
||
|
||
const [selectedEdge, setSelectedEdge] = useState<Edge | undefined>(undefined)
|
||
const handleSelectionChange = useCallback(
|
||
(params: OnSelectionChangeParams<Node<TableNodeData>, Edge<EdgeData>>) => {
|
||
if (params.edges.length === 1) {
|
||
setSelectedEdge(params.edges[0])
|
||
} else {
|
||
setSelectedEdge(undefined)
|
||
}
|
||
|
||
const selectedNodeIds = new Set(params.nodes.map((n) => n.id))
|
||
const currentEdges = reactFlowInstance.getEdges()
|
||
let hasChanges = false
|
||
const nextEdges = currentEdges.map((edge) => {
|
||
const shouldAnimate =
|
||
selectedNodeIds.size > 0 &&
|
||
(selectedNodeIds.has(edge.source) || selectedNodeIds.has(edge.target))
|
||
if (edge.animated === shouldAnimate) return edge
|
||
hasChanges = true
|
||
return { ...edge, animated: shouldAnimate }
|
||
})
|
||
if (hasChanges) reactFlowInstance.setEdges(nextEdges)
|
||
},
|
||
[reactFlowInstance, setSelectedEdge]
|
||
)
|
||
|
||
const downloadImage = async (format: 'png' | 'svg') => {
|
||
const reactflowViewport = document.querySelector('.react-flow__viewport') as HTMLElement
|
||
if (!reactflowViewport) return
|
||
if (!ref) return
|
||
const { x, y, zoom } = reactFlowInstance.getViewport()
|
||
track('database_schema_visualizer_image_download_clicked', { format })
|
||
exportSchemaToImage({ element: reactflowViewport, format, x, y, zoom, projectRef: ref })
|
||
}
|
||
|
||
const copyAsSQL = () => {
|
||
if (!tables) return
|
||
copyToClipboard(tablesToSQL(tables))
|
||
track('database_schema_visualizer_copied', { content: 'schema_sql' })
|
||
setCopied(true)
|
||
toast.success('Successfully copied as SQL')
|
||
}
|
||
|
||
const copyAsMarkdown = () => {
|
||
if (isMarkdownDataLoading) return
|
||
|
||
const tableNodes = reactFlowInstance
|
||
.getNodes()
|
||
.filter((node) => node.type === 'table')
|
||
.map((node) => node.data as TableNodeData)
|
||
|
||
let markdown = getSchemaAsMarkdown(selectedSchema, tableNodes)
|
||
|
||
const enumsMarkdown = getEnumsAsMarkdown(
|
||
selectedSchema,
|
||
enumeratedTypes.map((e) => ({ name: e.name, schema: e.schema, enums: e.enums }))
|
||
)
|
||
if (enumsMarkdown) markdown += enumsMarkdown
|
||
|
||
const policiesMarkdown = getPoliciesAsMarkdown(
|
||
selectedSchema,
|
||
policies.map((p) => ({
|
||
name: p.name,
|
||
schema: p.schema,
|
||
table: p.table,
|
||
command: p.command,
|
||
roles: p.roles,
|
||
action: p.action,
|
||
definition: p.definition ? String(p.definition) : null,
|
||
check: p.check ? String(p.check) : null,
|
||
}))
|
||
)
|
||
if (policiesMarkdown) markdown += policiesMarkdown
|
||
|
||
copyToClipboard(markdown)
|
||
track('database_schema_visualizer_copied', { content: 'schema_markdown' })
|
||
setCopied(true)
|
||
toast.success('Successfully copied as Markdown')
|
||
}
|
||
|
||
const [schemaSelectorOpen, setSchemaSelectorOpen] = useState(false)
|
||
const [findTableOpen, setFindTableOpen] = useState(false)
|
||
const [autoLayoutDialogOpen, setAutoLayoutDialogOpen] = useState(false)
|
||
|
||
const handleSelectSchema = (name: string) => {
|
||
setFindTableOpen(false)
|
||
setSelectedSchema(name)
|
||
track('database_schema_selector_updated', {
|
||
schemaType: getDatabaseSchemaType(name, protectedSchemas),
|
||
})
|
||
}
|
||
|
||
const shortcutsEnabled = isSuccessSchemas && !hasNoTables
|
||
|
||
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_COPY_SQL, copyAsSQL, { enabled: shortcutsEnabled })
|
||
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_COPY_MARKDOWN, copyAsMarkdown, {
|
||
enabled: shortcutsEnabled && !isMarkdownDataLoading,
|
||
})
|
||
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_DOWNLOAD_PNG, () => downloadImage('png'), {
|
||
enabled: shortcutsEnabled,
|
||
})
|
||
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_DOWNLOAD_SVG, () => downloadImage('svg'), {
|
||
enabled: shortcutsEnabled,
|
||
})
|
||
|
||
const isFirstLoad = useRef(true)
|
||
const fitViewOnNextLayout = useRef(false)
|
||
// Schema of the nodes currently on the canvas. Switching to a schema whose tables are cached
|
||
// keeps the graph mounted, so the view must be fitted again or the new nodes can sit off-screen.
|
||
const layoutSchemaRef = useRef<string | null>(null)
|
||
const pendingFocusTableIdRef = useRef<string | null>(null)
|
||
useEffect(() => {
|
||
if (isSuccessTables && isSuccessSchemas && tables.length > 0) {
|
||
const schema = schemas.find((s) => s.name === selectedSchema) as PGSchema
|
||
getGraphDataFromTables(ref as string, schema, tables).then(({ nodes, edges }) => {
|
||
reactFlowInstance.setNodes(nodes)
|
||
reactFlowInstance.setEdges(edges)
|
||
// Prevent resetting a view after first load to avoid layout changes after editing a column
|
||
const isNewSchema = layoutSchemaRef.current !== selectedSchema
|
||
layoutSchemaRef.current = selectedSchema
|
||
if (isFirstLoad.current || fitViewOnNextLayout.current || isNewSchema) {
|
||
isFirstLoad.current = false
|
||
fitViewOnNextLayout.current = false
|
||
setTimeout(() => reactFlowInstance.fitView({})) // it needs to happen during next event tick
|
||
}
|
||
const pendingId = pendingFocusTableIdRef.current
|
||
if (pendingId !== null && nodes.some((n) => n.id === pendingId)) {
|
||
pendingFocusTableIdRef.current = null
|
||
setTimeout(() =>
|
||
reactFlowInstance.fitView({
|
||
nodes: [{ id: pendingId }],
|
||
duration: 300,
|
||
maxZoom: 1.5,
|
||
})
|
||
)
|
||
}
|
||
})
|
||
}
|
||
}, [isSuccessTables, isSuccessSchemas, tables, reactFlowInstance, ref, schemas, selectedSchema])
|
||
|
||
const handleFindTableSelect = async (table: SafePostgresTable) => {
|
||
track('database_schema_visualizer_find_table_clicked')
|
||
const targetId = String(table.id)
|
||
if (reactFlowInstance.getNode(targetId)) {
|
||
reactFlowInstance.fitView({
|
||
nodes: [{ id: targetId }],
|
||
duration: 300,
|
||
maxZoom: 1.5,
|
||
})
|
||
return
|
||
}
|
||
// Selected table isn't loaded yet — queue the fitView and pull pages until
|
||
// it shows up. The build-effect above will consume the pending id once the
|
||
// node is mounted.
|
||
pendingFocusTableIdRef.current = targetId
|
||
let result = await fetchNextPage()
|
||
while (
|
||
result.hasNextPage &&
|
||
!result.data?.pages.some((page) => page.some((t) => t.id === table.id))
|
||
) {
|
||
result = await fetchNextPage()
|
||
}
|
||
}
|
||
|
||
const schemaGraphContext = useMemo<SchemaGraphContextType>(
|
||
() => ({
|
||
selectedEdge,
|
||
isDownloading,
|
||
onEditColumn: (tableId, columnId) => {
|
||
const table = tables.find((table) => table.id === tableId)
|
||
if (!table || table.columns == null) return
|
||
|
||
const column = table.columns.find((column) => column.id === columnId)
|
||
if (!column) return
|
||
|
||
setSelectedTable(table)
|
||
snap.onEditColumn(column)
|
||
},
|
||
onEditTable: (tableId) => {
|
||
void editTable(tableId)
|
||
},
|
||
}),
|
||
[tables, snap, editTable, isDownloading, selectedEdge]
|
||
)
|
||
|
||
return (
|
||
<>
|
||
<div className="flex items-center justify-between p-4 border-b border-muted h-(--header-height)">
|
||
{isLoadingSchemas && (
|
||
<div className="h-[34px] w-[260px] bg-foreground-lighter rounded-sm shimmering-loader" />
|
||
)}
|
||
|
||
{isErrorSchemas && <AlertError error={errorSchemas} subject="Failed to retrieve schemas" />}
|
||
|
||
{isSuccessSchemas && (
|
||
<>
|
||
<div className="flex items-center gap-x-2">
|
||
<Shortcut
|
||
id={SHORTCUT_IDS.SCHEMA_VISUALIZER_FOCUS_SCHEMA}
|
||
onTrigger={() => setSchemaSelectorOpen(true)}
|
||
options={{ enabled: isSuccessSchemas }}
|
||
side="bottom"
|
||
tooltipOpen={schemaSelectorOpen ? false : undefined}
|
||
>
|
||
<SchemaSelector
|
||
data-attr="schema-selector"
|
||
className="w-[180px]"
|
||
size="tiny"
|
||
showError={false}
|
||
selectedSchemaName={selectedSchema}
|
||
onSelectSchema={handleSelectSchema}
|
||
open={schemaSelectorOpen}
|
||
onOpenChange={setSchemaSelectorOpen}
|
||
/>
|
||
</Shortcut>
|
||
{!hasNoTables && (
|
||
<Shortcut
|
||
id={SHORTCUT_IDS.SCHEMA_VISUALIZER_FIND_TABLE}
|
||
onTrigger={() => setFindTableOpen(true)}
|
||
options={{ enabled: shortcutsEnabled }}
|
||
side="bottom"
|
||
tooltipOpen={findTableOpen ? false : undefined}
|
||
>
|
||
<FindTableSelector
|
||
projectRef={project?.ref}
|
||
connectionString={project?.connectionString}
|
||
schema={selectedSchema}
|
||
open={findTableOpen}
|
||
onOpenChange={setFindTableOpen}
|
||
onSelect={handleFindTableSelect}
|
||
/>
|
||
</Shortcut>
|
||
)}
|
||
</div>
|
||
{!hasNoTables && (
|
||
<div className="flex items-center gap-x-2">
|
||
<SplitButtonGroup className="items-center gap-0">
|
||
<ButtonTooltip
|
||
data-attr="schema-visualizer-copy-sql"
|
||
icon={copied ? <CheckIcon data-testid="copy-sql-ready" /> : <CopyIcon />}
|
||
onClick={copyAsSQL}
|
||
tooltip={{
|
||
content: {
|
||
side: 'bottom',
|
||
text: (
|
||
<div className="max-w-[180px] space-y-2 text-foreground-light">
|
||
<p className="text-foreground">Note</p>
|
||
<p>
|
||
This schema is for context or debugging only. Table order and
|
||
constraints may be invalid. Not meant to be run as-is.
|
||
</p>
|
||
</div>
|
||
),
|
||
},
|
||
}}
|
||
>
|
||
Copy as SQL
|
||
</ButtonTooltip>
|
||
<DropdownMenu>
|
||
<DropdownMenuTrigger asChild>
|
||
<Button
|
||
size="tiny"
|
||
aria-label="Export options"
|
||
className="shrink-0 px-1 py-1.25"
|
||
icon={<ChevronDownIcon size={12} />}
|
||
/>
|
||
</DropdownMenuTrigger>
|
||
<DropdownMenuContent align="end" className="w-44">
|
||
<DropdownMenuItem
|
||
data-attr="schema-visualizer-copy-markdown"
|
||
className="flex items-center space-x-2 whitespace-nowrap"
|
||
disabled={isMarkdownDataLoading}
|
||
onClick={(e) => {
|
||
e.stopPropagation()
|
||
copyAsMarkdown()
|
||
}}
|
||
>
|
||
{isMarkdownDataLoading ? (
|
||
<Loader2Icon size={12} className="animate-spin" />
|
||
) : (
|
||
<CopyIcon size={12} />
|
||
)}
|
||
<span>Copy as Markdown</span>
|
||
</DropdownMenuItem>
|
||
<DropdownMenuItem
|
||
data-attr="schema-visualizer-download-image"
|
||
className="flex items-center space-x-2 whitespace-nowrap"
|
||
onClick={(e) => {
|
||
e.stopPropagation()
|
||
downloadImage('png')
|
||
}}
|
||
>
|
||
<DownloadIcon size={12} />
|
||
<span>Download as PNG</span>
|
||
</DropdownMenuItem>
|
||
<DropdownMenuItem
|
||
data-attr="schema-visualizer-download-image"
|
||
className="flex items-center space-x-2 whitespace-nowrap"
|
||
onClick={(e) => {
|
||
e.stopPropagation()
|
||
downloadImage('svg')
|
||
}}
|
||
>
|
||
<DownloadIcon size={12} />
|
||
<span>Download as SVG</span>
|
||
</DropdownMenuItem>
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>
|
||
</SplitButtonGroup>
|
||
<AlertDialog open={autoLayoutDialogOpen} onOpenChange={setAutoLayoutDialogOpen}>
|
||
<Shortcut
|
||
id={SHORTCUT_IDS.SCHEMA_VISUALIZER_AUTO_LAYOUT}
|
||
onTrigger={() => setAutoLayoutDialogOpen(true)}
|
||
options={{ enabled: shortcutsEnabled }}
|
||
side="bottom"
|
||
tooltipOpen={autoLayoutDialogOpen ? false : undefined}
|
||
>
|
||
<AlertDialogTrigger asChild>
|
||
<Button>Auto layout</Button>
|
||
</AlertDialogTrigger>
|
||
</Shortcut>
|
||
<AlertDialogContent>
|
||
<AlertDialogHeader>
|
||
<AlertDialogTitle>Confirm to rearrange all nodes</AlertDialogTitle>
|
||
<AlertDialogDescription>
|
||
Auto layout will rearrange all nodes in the graph. This cannot be undone.
|
||
</AlertDialogDescription>
|
||
</AlertDialogHeader>
|
||
<AlertDialogFooter>
|
||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||
<AlertDialogAction
|
||
data-attr="schema-visualizer-auto-layout"
|
||
onClick={resetLayout}
|
||
>
|
||
Apply
|
||
</AlertDialogAction>
|
||
</AlertDialogFooter>
|
||
</AlertDialogContent>
|
||
</AlertDialog>
|
||
</div>
|
||
)}
|
||
</>
|
||
)}
|
||
</div>
|
||
{isLoadingTables && (
|
||
<div className="w-full h-full flex items-center justify-center gap-x-2">
|
||
<Loader2Icon className="animate-spin text-foreground-light" size={16} />
|
||
<p className="text-sm text-foreground-light">Loading tables</p>
|
||
</div>
|
||
)}
|
||
{isErrorTables && (
|
||
<div className="w-full h-full flex items-center justify-center px-20">
|
||
<AlertError subject="Failed to retrieve tables" error={errorTables} />
|
||
</div>
|
||
)}
|
||
{isSuccessTables && (
|
||
<>
|
||
{hasNoTables ? (
|
||
<div className="flex items-center justify-center w-full h-full">
|
||
<Admonition
|
||
type="default"
|
||
className="max-w-md"
|
||
title="No tables in schema"
|
||
description={
|
||
isSchemaLocked
|
||
? `The “${selectedSchema}” schema is managed by Supabase and is read-only through
|
||
the dashboard.`
|
||
: !canUpdateTables
|
||
? 'You need additional permissions to create tables'
|
||
: `The “${selectedSchema}” schema doesn’t have any tables.`
|
||
}
|
||
>
|
||
{canAddTables && (
|
||
<Button
|
||
asChild
|
||
className="mt-2 w-min"
|
||
icon={<PlusIcon />}
|
||
data-attr="schema-visualizer-new-table"
|
||
>
|
||
<Link
|
||
to="/project/$ref/editor"
|
||
params={{ ref: ref ?? '_' }}
|
||
search={{ create: 'table' }}
|
||
>
|
||
New table
|
||
</Link>
|
||
</Button>
|
||
)}
|
||
</Admonition>
|
||
</div>
|
||
) : (
|
||
<SchemaGraphContextProvider value={schemaGraphContext}>
|
||
<div className="w-full h-full">
|
||
<ReactFlow<Node<TableNodeData>, Edge<EdgeData>>
|
||
// FIXME: https://github.com/xyflow/xyflow/issues/4876
|
||
colorMode={'' as unknown as ColorMode}
|
||
defaultNodes={[]}
|
||
defaultEdges={[]}
|
||
defaultEdgeOptions={{
|
||
type: 'default',
|
||
animated: false,
|
||
deletable: false,
|
||
}}
|
||
nodeTypes={nodeTypes}
|
||
edgeTypes={edgeTypes}
|
||
fitView
|
||
minZoom={0.8}
|
||
maxZoom={1.8}
|
||
onlyRenderVisibleElements
|
||
proOptions={{ hideAttribution: true }}
|
||
onNodeDragStop={saveNodePositions}
|
||
onSelectionChange={handleSelectionChange}
|
||
>
|
||
<Background
|
||
gap={16}
|
||
className="*:stroke-foreground-muted opacity-25"
|
||
variant={BackgroundVariant.Dots}
|
||
color={'inherit'}
|
||
/>
|
||
<MiniMap
|
||
pannable
|
||
zoomable
|
||
nodeColor={miniMapNodeColor}
|
||
maskColor={miniMapMaskColor}
|
||
className="border rounded-md shadow-xs mb-11!"
|
||
/>
|
||
<SchemaGraphLegend />
|
||
{hasNextPage && (
|
||
<Panel position="bottom-center" className="mb-11!">
|
||
<Button
|
||
size="tiny"
|
||
loading={isFetchingNextPage}
|
||
onClick={() => {
|
||
fitViewOnNextLayout.current = true
|
||
fetchNextPage()
|
||
}}
|
||
>
|
||
Load more tables
|
||
</Button>
|
||
</Panel>
|
||
)}
|
||
</ReactFlow>
|
||
</div>
|
||
</SchemaGraphContextProvider>
|
||
)}
|
||
</>
|
||
)}
|
||
<SidePanelEditor selectedTable={selectedTable ?? undefined} includeColumns />
|
||
</>
|
||
)
|
||
}
|