Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Gildasgarcia/fe 2426 show relationship line context and highlight on hover (#44023)

Gildas Garcia06190d15b974
diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.tsx b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.tsx
index ff6b33dfad3..e1318acd1b3 100644
--- a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.tsx
@@ -1,7 +1,7 @@
import { useParams } from 'common'
import { AnalyticsBucket, BigQuery, Database } from 'icons'
import { PropsWithChildren, useMemo } from 'react'
-import { Handle, Position } from 'reactflow'
+import { Handle, Position } from '@xyflow/react'
import { AWS_REGIONS } from 'shared-data'
import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/ReplicationDiagram.utils.ts b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/ReplicationDiagram.utils.ts
index 7dbfd8cb873..bcb3ab23e4b 100644
--- a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/ReplicationDiagram.utils.ts
+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/ReplicationDiagram.utils.ts
@@ -1,5 +1,5 @@
import dagre from '@dagrejs/dagre'
-import { Edge, Node, Position } from 'reactflow'
+import { Edge, Node, Position } from '@xyflow/react'
import { NODE_WIDTH } from './Nodes'
diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/index.tsx b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/index.tsx
index 74ea990044e..edc6f7ff410 100644
--- a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/index.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/index.tsx
@@ -2,7 +2,7 @@ import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import { useTheme } from 'next-themes'
import { useEffect, useMemo } from 'react'
-import ReactFlow, { Background, ReactFlowProvider, useReactFlow } from 'reactflow'
+import { Background, ColorMode, ReactFlow, ReactFlowProvider, useReactFlow } from '@xyflow/react'
import { getStatusName } from '../Pipeline.utils'
import { PrimaryDatabaseNode, ReadReplicaNode, ReplicationNode } from './Nodes'
@@ -14,7 +14,7 @@ import { ReplicationPipelineStatusResponse } from '@/data/replication/pipeline-s
import { useReplicationPipelinesQuery } from '@/data/replication/pipelines-query'
import { timeout } from '@/lib/helpers'
-import 'reactflow/dist/style.css'
+import '@xyflow/react/dist/style.css'
export const ReplicationDiagram = () => {
return (
@@ -128,6 +128,8 @@ const ReplicationDiagramContent = () => {
return (
<div className="nowheel relative min-h-[350px]">
<ReactFlow
+ // FIXME: https://github.com/xyflow/xyflow/issues/4876
+ colorMode={'' as unknown as ColorMode}
fitView
fitViewOptions={{ minZoom: 0.8, maxZoom: 0.9 }}
className="bg"
@@ -137,7 +139,7 @@ const ReplicationDiagramContent = () => {
nodesConnectable={false}
zoomOnDoubleClick={false}
edgesFocusable={false}
- edgesUpdatable={false}
+ edgesReconnectable={false}
defaultNodes={[]}
defaultEdges={[]}
nodeTypes={nodeTypes}
diff --git a/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx b/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx
new file mode 100644
index 00000000000..dddf394a9d8
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Schemas/DefaultEdge.tsx
@@ -0,0 +1,202 @@
+import {
+ BaseEdge,
+ Edge,
+ EdgeLabelRenderer,
+ EdgeProps,
+ getSmoothStepPath,
+ Position,
+ useReactFlow,
+} from '@xyflow/react'
+import { ArrowLeft, ArrowRight } from 'lucide-react'
+import { useEffect, useRef, useState } from 'react'
+import { Badge, cn } from 'ui'
+
+import { EdgeData } from './Schemas.constants'
+import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
+import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
+
+export const DefaultEdge = ({
+ id,
+ animated,
+ data,
+ deletable,
+ selectable,
+ source,
+ sourceX,
+ sourceY,
+ sourceHandleId,
+ sourcePosition = Position.Bottom,
+ target,
+ targetX,
+ targetY,
+ targetHandleId,
+ targetPosition = Position.Top,
+ selected,
+ pathOptions,
+ ...props
+}: EdgeProps<Edge<EdgeData>>) => {
+ const [edgePath, labelX, labelY] = getSmoothStepPath({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ borderRadius: pathOptions?.borderRadius,
+ offset: pathOptions?.offset,
+ stepPosition: pathOptions?.stepPosition,
+ })
+
+ return (
+ <>
+ <BaseEdge
+ id={id}
+ path={edgePath}
+ className={cn(selected ? '!stroke-brand' : undefined)}
+ {...props}
+ />
+ {data && selected ? (
+ <EdgeRelationInfo
+ source={source}
+ target={target}
+ edgePath={edgePath}
+ labelX={labelX}
+ labelY={labelY}
+ sourceX={sourceX}
+ targetX={targetX}
+ data={data}
+ />
+ ) : null}
+ </>
+ )
+}
+
+const EdgeRelationInfo = ({
+ data,
+ edgePath,
+ source,
+ target,
+ labelX,
+ labelY,
+ targetX,
+ sourceX,
+}: {
+ data: EdgeData
+ edgePath: string
+ source: string
+ target: string
+ labelX: number
+ labelY: number
+ sourceX: number
+ targetX: number
+}) => {
+ const [show, setShow] = useState(false)
+ const reactFlowInstance = useReactFlow()
+
+ const checkIfShouldBeDisplayed = useStaticEffectEvent(
+ (relationInfoElement: HTMLDivElement | null) => {
+ if (!relationInfoElement) return
+ const sourceNode = reactFlowInstance.getNode(source)
+ const targetNode = reactFlowInstance.getNode(target)
+ if (!sourceNode || !targetNode) return
+
+ const relationInfoRect = relationInfoElement.getBoundingClientRect()
+ // Get the origin position of the relation information badge in the ReactFlow coordinates
+ const relationInfoOriginPositionInReactFlow = reactFlowInstance.screenToFlowPosition({
+ x: relationInfoRect.x,
+ y: relationInfoRect.y,
+ })
+ // Get the end position (origin + dimensions) of the relation information badge in the ReactFlow coordinates
+ const relationInfoTargetPositionInReactFlow = reactFlowInstance.screenToFlowPosition({
+ x: relationInfoRect.x + relationInfoRect.width,
+ y: relationInfoRect.y + relationInfoRect.height,
+ })
+ // Create a ReactFlow Rect from the computed position above
+ const relationInfoReactFlowRect = {
+ x: relationInfoOriginPositionInReactFlow.x,
+ y: relationInfoOriginPositionInReactFlow.y,
+ width: relationInfoTargetPositionInReactFlow.x - relationInfoOriginPositionInReactFlow.x,
+ height: relationInfoTargetPositionInReactFlow.y - relationInfoOriginPositionInReactFlow.y,
+ }
+ // Check whether the relation information badge is intersecting with either the source or target node
+ const isNodeIntersectingWithSource = reactFlowInstance.isNodeIntersecting(
+ sourceNode,
+ relationInfoReactFlowRect
+ )
+ const isNodeIntersectingWithTarget = reactFlowInstance.isNodeIntersecting(
+ targetNode,
+ relationInfoReactFlowRect
+ )
+
+ // If it is, hide it as they are too close
+ setShow(!isNodeIntersectingWithSource && !isNodeIntersectingWithTarget)
+ }
+ )
+
+ return (
+ <EdgeLabelRenderer>
+ <Badge
+ ref={checkIfShouldBeDisplayed}
+ className={cn(
+ 'absolute pointer-events-auto z-50 p-1 rounded-[4px] gap-1 outline outline-1 outline-brand',
+ show ? 'opacity-100' : 'opacity-0'
+ )}
+ style={{
+ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
+ }}
+ >
+ {
+ // Show the columns in the order of the schema instead of the Postgre relation order
+ sourceX < targetX ? (
+ <>
+ <EdgeNodeData
+ schema={data.sourceSchemaName}
+ table={data.sourceName}
+ column={data.sourceColumnName}
+ />
+ <ArrowRight size={12} />
+ <EdgeNodeData
+ schema={data.targetSchemaName}
+ table={data.targetName}
+ column={data.targetColumnName}
+ />
+ </>
+ ) : (
+ <>
+ <EdgeNodeData
+ schema={data.targetSchemaName}
+ table={data.targetName}
+ column={data.targetColumnName}
+ />
+ <ArrowLeft size={12} />
+ <EdgeNodeData
+ schema={data.sourceSchemaName}
+ table={data.sourceName}
+ column={data.sourceColumnName}
+ />
+ </>
+ )
+ }
+ </Badge>
+ </EdgeLabelRenderer>
+ )
+}
+
+const EdgeNodeData = ({
+ schema,
+ table,
+ column,
+}: {
+ schema: string
+ table: string
+ column: string
+}) => {
+ const { selectedSchema } = useQuerySchemaState()
+
+ return (
+ <Badge className="normal-case text-[8px]">
+ {selectedSchema === schema ? '' : `${schema}.`}
+ {table}.{column}
+ </Badge>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
index 16bb938e281..26233aa3ce6 100644
--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
@@ -1,13 +1,23 @@
import type { PostgresSchema, PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import {
+ Background,
+ BackgroundVariant,
+ ColorMode,
+ Edge,
+ MiniMap,
+ Node,
+ OnSelectionChangeParams,
+ ReactFlow,
+ useReactFlow,
+} from '@xyflow/react'
import { toPng, toSvg } from 'html-to-image'
import { Check, Copy, Download, Loader2, Plus } from 'lucide-react'
import { useTheme } from 'next-themes'
import Link from 'next/link'
import { useEffect, useMemo, useRef, useState } from 'react'
-import ReactFlow, { Background, BackgroundVariant, MiniMap, useReactFlow } from 'reactflow'
-import 'reactflow/dist/style.css'
+import '@xyflow/react/dist/style.css'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import AlertError from 'components/ui/AlertError'
@@ -34,10 +44,13 @@ import {
import { Admonition } from 'ui-patterns/admonition'
import { SidePanelEditor } from '../../TableGridEditor/SidePanelEditor/SidePanelEditor'
+import { DefaultEdge } from './DefaultEdge'
import { SchemaGraphContextProvider, SchemaGraphContextType } from './SchemaGraphContext'
import { SchemaGraphLegend } from './SchemaGraphLegend'
+import { EdgeData, TableNodeData } from './Schemas.constants'
import { getGraphDataFromTables, getLayoutedElementsViaDagre } from './Schemas.utils'
import { TableNode } from './SchemaTableNode'
+import { useStaticEffectEvent } from '@/hooks/useStaticEffectEvent'
// [Joshen] Persisting logic: Only save positions to local storage WHEN a node is moved OR when explicitly clicked to reset layout
@@ -70,6 +83,12 @@ export const SchemaGraph = () => {
}),
[]
)
+ const edgeTypes = useMemo(
+ () => ({
+ default: DefaultEdge,
+ }),
+ []
+ )
const {
data: schemas,
@@ -115,14 +134,17 @@ export const SchemaGraph = () => {
const nodes = reactFlowInstance.getNodes()
const edges = reactFlowInstance.getEdges()
- getLayoutedElementsViaDagre(nodes, edges)
+ getLayoutedElementsViaDagre(
+ nodes.filter((item) => item.type === 'table') as Node<TableNodeData>[],
+ edges
+ )
reactFlowInstance.setNodes(nodes)
reactFlowInstance.setEdges(edges)
setTimeout(() => reactFlowInstance.fitView({}))
saveNodePositions()
}
- const saveNodePositions = () => {
+ const saveNodePositions = useStaticEffectEvent(() => {
if (schema === undefined) return console.error('Schema is required')
const nodes = reactFlowInstance.getNodes()
@@ -132,7 +154,18 @@ export const SchemaGraph = () => {
}, {})
setStoredPositions(nodesPositionData)
}
- }
+ })
+
+ const [selectedEdge, setSelectedEdge] = useState<Edge | undefined>(undefined)
+ const handleSelectionChange = useStaticEffectEvent(
+ (params: OnSelectionChangeParams<Node<TableNodeData>, Edge<EdgeData>>) => {
+ if (params.edges.length === 1) {
+ setSelectedEdge(params.edges[0])
+ return
+ }
+ setSelectedEdge(undefined)
+ }
+ )
const downloadImage = (format: 'png' | 'svg') => {
const reactflowViewport = document.querySelector('.react-flow__viewport') as HTMLElement
@@ -223,6 +256,7 @@ export const SchemaGraph = () => {
const schemaGraphPanelEditorContext = useMemo<SchemaGraphContextType>(
() => ({
+ selectedEdge,
isDownloading,
onEditColumn: (tableId, columnId) => {
const table = tables.find((table) => table.id === tableId)
@@ -242,7 +276,7 @@ export const SchemaGraph = () => {
snap.onEditTable()
},
}),
- [tables, snap, isDownloading]
+ [tables, snap, isDownloading, selectedEdge]
)
return (
@@ -368,20 +402,24 @@ export const SchemaGraph = () => {
) : (
<SchemaGraphContextProvider value={schemaGraphPanelEditorContext}>
<div className="w-full h-full">
- <ReactFlow
+ <ReactFlow<Node<TableNodeData>, Edge<EdgeData>>
+ // FIXME: https://github.com/xyflow/xyflow/issues/4876
+ colorMode={'' as unknown as ColorMode}
defaultNodes={[]}
defaultEdges={[]}
defaultEdgeOptions={{
- type: 'smoothstep',
+ type: 'default',
animated: true,
deletable: false,
}}
nodeTypes={nodeTypes}
+ edgeTypes={edgeTypes}
fitView
minZoom={0.8}
maxZoom={1.8}
proOptions={{ hideAttribution: true }}
- onNodeDragStop={() => saveNodePositions()}
+ onNodeDragStop={saveNodePositions}
+ onSelectionChange={handleSelectionChange}
>
<Background
gap={16}
diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraphContext.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraphContext.tsx
index 514168908b8..117be7ce2c2 100644
--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraphContext.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraphContext.tsx
@@ -1,7 +1,9 @@
+import { Edge } from '@xyflow/react'
import { createContext, useContext, type ReactNode } from 'react'
export type SchemaGraphContextType = {
isDownloading: boolean
+ selectedEdge: Edge | undefined
onEditColumn: (tableId: number, columnId: string) => void
onEditTable: (tableId: number) => void
}
diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaTableNode.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaTableNode.tsx
index a771bb5829e..9d492384c14 100644
--- a/apps/studio/components/interfaces/Database/Schemas/SchemaTableNode.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaTableNode.tsx
@@ -1,4 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { Handle, Node, NodeProps } from '@xyflow/react'
import { buildTableEditorUrl } from 'components/grid/SupabaseGrid.utils'
import { TableEditor } from 'icons'
import {
@@ -13,7 +14,6 @@ import {
Table2,
} from 'lucide-react'
import { useRouter } from 'next/router'
-import { Handle, NodeProps } from 'reactflow'
import {
Button,
cn,
@@ -28,6 +28,7 @@ import {
} from 'ui'
import { useSchemaGraphContext } from './SchemaGraphContext'
+import { TableNodeData } from './Schemas.constants'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
@@ -35,30 +36,13 @@ import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
export const TABLE_NODE_WIDTH = 320
export const TABLE_NODE_ROW_HEIGHT = 40
-export type TableNodeData = {
- id: number
- schema: string
- name: string
- ref?: string
- isForeign: boolean
- description: string
- columns: {
- id: string
- isPrimary: boolean
- isNullable: boolean
- isUnique: boolean
- isIdentity: boolean
- name: string
- format: string
- }[]
-}
-
export const TableNode = ({
+ id,
data,
targetPosition,
sourcePosition,
placeholder,
-}: NodeProps<TableNodeData> & { placeholder?: boolean }) => {
+}: NodeProps<Node<TableNodeData>> & { placeholder?: boolean }) => {
// Important styles is a nasty hack to use Handles (required for edges calculations), but do not show them in the UI.
// ref: https://github.com/wbkd/react-flow/discussions/2698
const hiddenNodeConnector = '!h-px !w-px !min-w-0 !min-h-0 !cursor-grab !border-0 !opacity-0'
@@ -71,10 +55,18 @@ export const TableNode = ({
const router = useRouter()
const itemHeight = 'h-[22px]'
+ const hasEdgesSelected =
+ schemaGraphContext.selectedEdge?.source === id || schemaGraphContext.selectedEdge?.target === id
+
return (
- <>
+ <article>
{data.isForeign ? (
- <header className="text-[0.55rem] px-2 py-1 border-[0.5px] rounded-[4px] bg-alternative flex gap-1 items-center">
+ <header
+ className={cn(
+ 'text-[0.55rem] px-2 py-1 border-[0.5px] rounded-[4px] bg-alternative flex gap-1 items-center',
+ hasEdgesSelected ? 'outline outline-1 outline-brand' : undefined
+ )}
+ >
{data.name}
{targetPosition && (
<Handle
@@ -87,7 +79,10 @@ export const TableNode = ({
</header>
) : (
<div
- className="border-[0.5px] overflow-hidden rounded-[4px] shadow-sm"
+ className={cn(
+ 'border-[0.5px] overflow-hidden rounded-[4px] shadow-sm',
+ hasEdgesSelected ? 'outline outline-1 outline-brand' : undefined
+ )}
style={{ width: TABLE_NODE_WIDTH / 2 }}
>
<header
@@ -216,7 +211,13 @@ export const TableNode = ({
</div>
<div className="flex w-full justify-between min-w-0">
<span
- className="text-ellipsis overflow-hidden whitespace-nowrap min-w-0 max-w-[80%]"
+ className={cn(
+ 'text-ellipsis overflow-hidden whitespace-nowrap min-w-0 max-w-[80%]',
+ schemaGraphContext.selectedEdge?.sourceHandle === column.id ||
+ schemaGraphContext.selectedEdge?.targetHandle === column.id
+ ? 'text-brand'
+ : undefined
+ )}
title={column.name}
>
{column.name}
@@ -230,7 +231,7 @@ export const TableNode = ({
type="target"
id={column.id}
position={targetPosition}
- className={cn(hiddenNodeConnector, '!left-0')}
+ className={cn(hiddenNodeConnector)}
/>
)}
{sourcePosition && (
@@ -238,7 +239,7 @@ export const TableNode = ({
type="source"
id={column.id}
position={sourcePosition}
- className={cn(hiddenNodeConnector, '!right-0')}
+ className={cn(hiddenNodeConnector)}
/>
)}
<DropdownMenu>
@@ -289,6 +290,6 @@ export const TableNode = ({
))}
</div>
)}
- </>
+ </article>
)
}
diff --git a/apps/studio/components/interfaces/Database/Schemas/Schemas.constants.ts b/apps/studio/components/interfaces/Database/Schemas/Schemas.constants.ts
new file mode 100644
index 00000000000..3b1602e3f5f
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Schemas/Schemas.constants.ts
@@ -0,0 +1,26 @@
+export type TableNodeData = {
+ id: number
+ schema: string
+ name: string
+ ref?: string
+ isForeign: boolean
+ description: string
+ columns: {
+ id: string
+ isPrimary: boolean
+ isNullable: boolean
+ isUnique: boolean
+ isIdentity: boolean
+ name: string
+ format: string
+ }[]
+}
+
+export type EdgeData = {
+ sourceName: string
+ sourceSchemaName: string
+ sourceColumnName: string
+ targetName: string
+ targetSchemaName: string
+ targetColumnName: string
+}
diff --git a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts
index c8af180fed6..755ad5eac63 100644
--- a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts
+++ b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts
@@ -1,14 +1,15 @@
import dagre from '@dagrejs/dagre'
import type { PostgresSchema, PostgresTable } from '@supabase/postgres-meta'
+import { Edge, Node, Position } from '@xyflow/react'
import { uniqBy } from 'lodash'
-import { Edge, Node, Position } from 'reactflow'
-import 'reactflow/dist/style.css'
+import '@xyflow/react/dist/style.css'
import { LOCAL_STORAGE_KEYS } from 'common'
import { tryParseJson } from 'lib/helpers'
-import { TABLE_NODE_ROW_HEIGHT, TABLE_NODE_WIDTH, TableNodeData } from './SchemaTableNode'
+import { TableNodeData } from './Schemas.constants'
+import { TABLE_NODE_ROW_HEIGHT, TABLE_NODE_WIDTH } from './SchemaTableNode'
const NODE_SEP = 25
const RANK_SEP = 50
@@ -107,6 +108,15 @@ export async function getGraphDataFromTables(
sourceHandle,
target: targetId,
targetHandle: targetId,
+ deletable: false,
+ data: {
+ sourceName: rel.source_table_name,
+ sourceSchemaName: rel.source_schema,
+ sourceColumnName: rel.source_column_name,
+ targetName: rel.target_table_name,
+ targetSchemaName: rel.target_table_schema,
+ targetColumnName: rel.target_column_name,
+ },
})
}
@@ -132,6 +142,15 @@ export async function getGraphDataFromTables(
sourceHandle,
target,
targetHandle,
+ type: 'default',
+ data: {
+ sourceName: rel.source_table_name,
+ sourceSchemaName: rel.source_schema,
+ sourceColumnName: rel.source_column_name,
+ targetName: rel.target_table_name,
+ targetSchemaName: rel.target_table_schema,
+ targetColumnName: rel.target_column_name,
+ },
})
}
}
@@ -163,7 +182,7 @@ function findTablesHandleIds(
return []
}
-export const getLayoutedElementsViaDagre = (nodes: Node[], edges: Edge[]) => {
+export const getLayoutedElementsViaDagre = (nodes: Node<TableNodeData>[], edges: Edge[]) => {
const dagreGraph = new dagre.graphlib.Graph()
dagreGraph.setDefaultEdgeLabel(() => ({}))
dagreGraph.setGraph({
@@ -204,7 +223,7 @@ export const getLayoutedElementsViaDagre = (nodes: Node[], edges: Edge[]) => {
}
const getLayoutedElementsViaLocalStorage = (
- nodes: Node[],
+ nodes: Node<TableNodeData>[],
edges: Edge[],
positions: { [key: string]: { x: number; y: number } }
) => {
diff --git a/apps/studio/components/interfaces/ProjectHome/TopSection.tsx b/apps/studio/components/interfaces/ProjectHome/TopSection.tsx
index 659de090a63..057945eeec9 100644
--- a/apps/studio/components/interfaces/ProjectHome/TopSection.tsx
+++ b/apps/studio/components/interfaces/ProjectHome/TopSection.tsx
@@ -10,7 +10,7 @@ import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization
import { useIsOrioleDb, useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { DOCS_URL, PROJECT_STATUS } from 'lib/constants'
import Link from 'next/link'
-import { ReactFlowProvider } from 'reactflow'
+import { ReactFlowProvider } from '@xyflow/react'
import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { InstanceConfiguration } from '../Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration'
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/Edge.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/Edge.tsx
index 40759ea6c35..99a6b737dff 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/Edge.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/Edge.tsx
@@ -1,12 +1,11 @@
-import { Loader2 } from 'lucide-react'
-import type { EdgeProps } from 'reactflow'
-import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath } from 'reactflow'
-
+import { BaseEdge, Edge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from '@xyflow/react'
import { useParams } from 'common'
import { useReplicationLagQuery } from 'data/read-replicas/replica-lag-query'
import { formatDatabaseID } from 'data/read-replicas/replicas.utils'
+import { Loader2 } from 'lucide-react'
import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'
-import { REPLICA_STATUS } from './InstanceConfiguration.constants'
+
+import { EdgeData, REPLICA_STATUS } from './InstanceConfiguration.constants'
export const SmoothstepEdge = ({
id,
@@ -19,7 +18,7 @@ export const SmoothstepEdge = ({
style = {},
markerEnd,
data,
-}: EdgeProps) => {
+}: EdgeProps<Edge<EdgeData>>) => {
const { ref } = useParams()
// [Joshen] Only applicable for replicas
const { status, identifier, connectionString } = data || {}
@@ -40,11 +39,12 @@ export const SmoothstepEdge = ({
isError,
} = useReplicationLagQuery(
{
- id: identifier,
+ // Safe cast as the query isn't enable if identifier is null/undefined
+ id: identifier as string,
projectRef: ref,
connectionString,
},
- { enabled: status === REPLICA_STATUS.ACTIVE_HEALTHY }
+ { enabled: identifier != null && status === REPLICA_STATUS.ACTIVE_HEALTHY }
)
const lagValue = Number(lagDuration?.toFixed(2) ?? 0).toLocaleString()
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts
index c1945723de3..70add9f92f7 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts
@@ -12,6 +12,37 @@ export interface Region {
coordinates: [number, number]
}
+export type NodeData = {
+ id: string
+ provider: string
+ region: Region
+ computeSize?: string
+ status: string
+ inserted_at: string
+}
+
+export type PrimaryNodeData = NodeData & {
+ numReplicas: number
+ numRegions: number
+ hasLoadBalancer: boolean
+}
+
+export type LoadBalancerData = NodeData & {
+ numDatabases: number
+}
+
+export type ReplicaNodeData = NodeData & {
+ onSelectRestartReplica: () => void
+ onSelectResizeReplica: () => void
+ onSelectDropReplica: () => void
+}
+
+export type EdgeData = {
+ status: string
+ identifier: string
+ connectionString: string | null | undefined
+}
+
// ReactFlow is scaling everything by the factor of 2
export const NODE_WIDTH = 660
export const NODE_ROW_HEIGHT = 50
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
index e5376107aef..27e2f58a363 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
@@ -1,12 +1,19 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import {
+ Background,
+ ColorMode,
+ Edge,
+ ReactFlow,
+ ReactFlowProvider,
+ useReactFlow,
+} from '@xyflow/react'
import { partition } from 'lodash'
import { ChevronDown, Globe2, Loader2, Network } from 'lucide-react'
import { useTheme } from 'next-themes'
import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
-import ReactFlow, { Background, Edge, ReactFlowProvider, useReactFlow } from 'reactflow'
-import 'reactflow/dist/style.css'
+import '@xyflow/react/dist/style.css'
import { useParams } from 'common'
import AlertError from 'components/ui/AlertError'
@@ -305,6 +312,8 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationU
)}
{view === 'flow' ? (
<ReactFlow
+ // FIXME: https://github.com/xyflow/xyflow/issues/4876
+ colorMode={'' as unknown as ColorMode}
fitView
fitViewOptions={{ minZoom: 0.9, maxZoom: 0.9 }}
className="instance-configuration"
@@ -314,7 +323,7 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationU
nodesConnectable={false}
zoomOnDoubleClick={false}
edgesFocusable={false}
- edgesUpdatable={false}
+ edgesReconnectable={false}
defaultNodes={[]}
defaultEdges={[]}
nodeTypes={nodeTypes}
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
index 9845ca03f2b..2aa8c64142b 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
@@ -1,16 +1,17 @@
import dagre from '@dagrejs/dagre'
-import { groupBy } from 'lodash'
-import { Edge, Node, Position } from 'reactflow'
-
+import { Edge, Node, Position } from '@xyflow/react'
import type { LoadBalancer } from 'data/read-replicas/load-balancers-query'
import type { Database } from 'data/read-replicas/replicas-query'
+import { groupBy } from 'lodash'
import { AWS_REGIONS, AWS_REGIONS_KEYS } from 'shared-data'
+
import {
AVAILABLE_REPLICA_REGIONS,
AWS_REGIONS_COORDINATES,
NODE_ROW_HEIGHT,
NODE_SEP,
NODE_WIDTH,
+ ReplicaNodeData,
} from './InstanceConfiguration.constants'
// [Joshen] Just FYI the nodes generation assumes each project only has one load balancer
@@ -165,7 +166,9 @@ export const getDagreGraphLayout = (nodes: Node[], edges: Edge[]) => {
*/
export const addRegionNodes = (nodes: Node[], edges: Edge[]) => {
const regionNodes: Node[] = []
- const replicaNodes = nodes.filter((node) => node.type === 'READ_REPLICA')
+ const replicaNodes = nodes.filter(
+ (node) => node.type === 'READ_REPLICA'
+ ) as Node<ReplicaNodeData>[]
const nodesByRegion = groupBy(replicaNodes, (node) => node.data.region.key)
Object.entries(nodesByRegion).map(([key, value]) => {
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx
index 4e422758fdb..3055ecbb13d 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx
@@ -1,3 +1,4 @@
+import { Handle, Node, NodeProps, Position } from '@xyflow/react'
import { useParams } from 'common'
import SparkBar from 'components/ui/SparkBar'
import {
@@ -12,7 +13,6 @@ import { BASE_PATH } from 'lib/constants'
import { Database, DatabaseBackup, HelpCircle, Loader2, MoreVertical } from 'lucide-react'
import Link from 'next/link'
import { parseAsBoolean, parseAsString, useQueryStates } from 'nuqs'
-import { Handle, NodeProps, Position } from 'reactflow'
import {
Badge,
Button,
@@ -30,40 +30,17 @@ import {
import {
ERROR_STATES,
INIT_PROGRESS,
+ LoadBalancerData,
NODE_SEP,
NODE_WIDTH,
- Region,
+ PrimaryNodeData,
REPLICA_STATUS,
+ ReplicaNodeData,
} from './InstanceConfiguration.constants'
import { formatSeconds } from './InstanceConfiguration.utils'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
-interface NodeData {
- id: string
- provider: string
- region: Region
- computeSize?: string
- status: string
- inserted_at: string
-}
-
-interface PrimaryNodeData extends NodeData {
- numReplicas: number
- numRegions: number
- hasLoadBalancer: boolean
-}
-
-interface LoadBalancerData extends NodeData {
- numDatabases: number
-}
-
-interface ReplicaNodeData extends NodeData {
- onSelectRestartReplica: () => void
- onSelectResizeReplica: () => void
- onSelectDropReplica: () => void
-}
-
-export const LoadBalancerNode = ({ data }: NodeProps<LoadBalancerData>) => {
+export const LoadBalancerNode = ({ data }: NodeProps<Node<LoadBalancerData>>) => {
const { ref } = useParams()
const { numDatabases } = data
@@ -105,7 +82,7 @@ export const LoadBalancerNode = ({ data }: NodeProps<LoadBalancerData>) => {
)
}
-export const PrimaryNode = ({ data }: NodeProps<PrimaryNodeData>) => {
+export const PrimaryNode = ({ data }: NodeProps<Node<PrimaryNodeData>>) => {
// [Joshen] Just FYI Handles cannot be conditionally rendered
const { region, computeSize, numReplicas, numRegions, hasLoadBalancer } = data
@@ -176,7 +153,7 @@ export const PrimaryNode = ({ data }: NodeProps<PrimaryNodeData>) => {
)
}
-export const ReplicaNode = ({ data }: NodeProps<ReplicaNodeData>) => {
+export const ReplicaNode = ({ data }: NodeProps<Node<ReplicaNodeData>>) => {
const { ref } = useParams()
const { id, region, computeSize, status, inserted_at } = data
const { projectHomepageShowInstanceSize } = useIsFeatureEnabled([
diff --git a/apps/studio/package.json b/apps/studio/package.json
index d9ca454114d..3392821079e 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -74,6 +74,7 @@
"@uidotdev/usehooks": "^2.4.1",
"@vercel/functions": "^2.1.0",
"@vitejs/plugin-react": "^4.3.4",
+ "@xyflow/react": "^12.10.1",
"@zip.js/zip.js": "^2.7.29",
"ai": "^6.0.116",
"ai-commands": "workspace:*",
@@ -130,7 +131,6 @@
"react-resizable": "3.0.5",
"react-simple-maps": "4.0.0-beta.6",
"react-use": "^17.5.0",
- "reactflow": "^11.10.1",
"recharts": "catalog:",
"remark-gfm": "^3.0.1",
"shared-data": "workspace:*",
diff --git a/apps/studio/pages/project/[ref]/database/schemas.tsx b/apps/studio/pages/project/[ref]/database/schemas.tsx
index 7cfcb036b1f..1e5bb7db24b 100644
--- a/apps/studio/pages/project/[ref]/database/schemas.tsx
+++ b/apps/studio/pages/project/[ref]/database/schemas.tsx
@@ -1,7 +1,7 @@
import { SchemaGraph } from 'components/interfaces/Database/Schemas/SchemaGraph'
import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
-import { ReactFlowProvider } from 'reactflow'
+import { ReactFlowProvider } from '@xyflow/react'
import type { NextPageWithLayout } from 'types'
const SchemasPage: NextPageWithLayout = () => {
diff --git a/apps/studio/tsconfig.json b/apps/studio/tsconfig.json
index f6061f9781c..4a9679eca87 100644
--- a/apps/studio/tsconfig.json
+++ b/apps/studio/tsconfig.json
@@ -37,7 +37,8 @@
"**/*.jsx",
".next/types/**/*.ts",
"./../../packages/ui/src/**/*.d.ts",
- ".next/dev/types/**/*.ts"
+ ".next/dev/types/**/*.ts",
+ ".next/dev/dev/types/**/*.ts"
],
"exclude": ["node_modules", "public/deno/*.ts"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f5b27af61d1..3f3c5ffd454 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -894,6 +894,9 @@ importers:
'@vitejs/plugin-react':
specifier: ^4.3.4
+ '@xyflow/react':
+ specifier: ^12.10.1
'@zip.js/zip.js':
specifier: ^2.7.29
version: 2.7.30
@@ -1062,9 +1065,6 @@ importers:
react-use:
specifier: ^17.5.0
- reactflow:
- specifier: ^11.10.1
recharts:
specifier: 'catalog:'
@@ -7628,42 +7628,6 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
- '@reactflow/[email protected]':
- resolution: {integrity: sha512-06FPlSUOOMALEEs+2PqPAbpqmL7WDjrkbG2UsDr2d6mbcDDhHiV4tu9FYoz44SQvXo7ma9VRotlsaR4OiRcYsg==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
- '@reactflow/[email protected]':
- resolution: {integrity: sha512-4QHT92/ACVlZkvV+Hq44bAPV8WbMhkJl+/J0EbXcqQ1+an7cWJsF84eeelJw7R5J76RoaSSpKdsWsL2v7HAVlw==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
- '@reactflow/[email protected]':
- resolution: {integrity: sha512-GIh3usY1W3eVobx//OO9+Cwm+5evQBBdPGxDaeXwm25UqPMWRI240nXQA5F/5gL5Mwpf0DUC7DR2EmrKNQy+Rw==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
- '@reactflow/[email protected]':
- resolution: {integrity: sha512-kJEtyeQkTZYViLGebVWHVUJROMAGcvejvT+iX4DqKnFb5yK8E8LWlXQpRx2FrL9gDy80mJJaciy7IxnnQKE1bg==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
- '@reactflow/[email protected]':
- resolution: {integrity: sha512-1Xb6q97uP7hRBLpog9sRCNfnsHdDgFRGEiU+lQqGgPEAeYwl4nRjWa/sXwH6ajniKxBhGEvrdzOgEFn6CRMcpQ==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
- '@reactflow/[email protected]':
- resolution: {integrity: sha512-JXDEuZ0wKjZ8z7qK2bIst0eZPzNyVEsiHL0e93EyuqT4fA9icoyE0fLq2ryNOOp7MXgId1h7LusnH6ta45F0yQ==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
'@redocly/[email protected]':
resolution: {integrity: sha512-io1JpnwtIcvojV7QKDUSIuMN/ikdOUd1ReEnUnMKGfDVridQZ31J0MmIuqwuRjWDZfmvr+Q0MqCcfHM2gTivOg==}
@@ -8894,6 +8858,9 @@ packages:
resolution: {integrity: sha512-zAbCj9lTqW9J9PlF4FwnvEjXZUy75NQqPm7DMHZXuxCFTpuTrdK2NMYGQekf4hlasL78fCYOLu4EE3/tXElwow==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==}
+
resolution: {integrity: sha512-NaIeSIBiFgSC6IGUBjZWcscUJEq7vpVu7KthHN8eieTV9d9MqkSOZLH4chq1PmcKy06PNe3axLeKmRIyxJ+PZQ==}
@@ -9546,6 +9513,15 @@ packages:
resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==}
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-5eSWtIK/+rkldOuFbOOz44CRgQRjtS9v5nufk77DV+XBnfCGL9HAQ8PG00o2ZYKqkEU/Ak6wrKC95Tu+2zuK3Q==}
+ peerDependencies:
+ react: '>=17'
+ react-dom: '>=17'
+
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-iXs+AGFLi8w/VlAoc/iSxk+CxfT6o64Uw/k0CKASOPqjqz6E0rb5jFZgJtXGZCpfQI6OQpu5EnumP5fGxQheaQ==}
+
'@zip.js/[email protected]':
resolution: {integrity: sha512-nhMvQCj+TF1ATBqYzFds7v+yxPBhdDYHh8J341KtC1D2UrVBUIYcYK4Jy1/GiTsxOXEiKOXSUxvPG/XR+7jMqw==}
engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=16.5.0'}
@@ -16284,12 +16260,6 @@ packages:
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-Q616fElAc5/N37tMwjuRkkgm/VgmnLLTNNCj61z5mvJxae+/VXZQMfot1K6a5LLz9G3SVKqU97PMb9Ga1PRXew==}
- peerDependencies:
- react: '>=17'
- react-dom: '>=17'
-
resolution: {integrity: sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==}
@@ -24781,84 +24751,6 @@ snapshots:
dependencies:
react: 18.3.1
- dependencies:
- classcat: 5.0.4
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
- dependencies:
- classcat: 5.0.4
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
- dependencies:
- '@types/d3': 7.4.3
- '@types/d3-drag': 3.0.7
- '@types/d3-selection': 3.0.10
- '@types/d3-zoom': 3.0.8
- classcat: 5.0.4
- d3-drag: 3.0.0
- d3-selection: 3.0.0
- d3-zoom: 3.0.0
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
- dependencies:
- '@types/d3-selection': 3.0.10
- '@types/d3-zoom': 3.0.8
- classcat: 5.0.4
- d3-selection: 3.0.0
- d3-zoom: 3.0.0
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
- dependencies:
- classcat: 5.0.4
- d3-drag: 3.0.0
- d3-selection: 3.0.0
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
- dependencies:
- classcat: 5.0.4
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
'@redocly/[email protected]':
dependencies:
fast-deep-equal: 3.1.3
@@ -26429,6 +26321,10 @@ snapshots:
dependencies:
'@types/d3-color': 3.1.1
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-color': 3.1.1
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -26472,7 +26368,7 @@ snapshots:
dependencies:
- '@types/d3-interpolate': 3.0.2
+ '@types/d3-interpolate': 3.0.4
'@types/d3-selection': 3.0.10
@@ -27308,6 +27204,29 @@ snapshots:
'@xtuc/[email protected]': {}
+ dependencies:
+ '@xyflow/system': 0.0.75
+ classcat: 5.0.4
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - immer
+
+ '@xyflow/[email protected]':
+ dependencies:
+ '@types/d3-drag': 3.0.7
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-selection': 3.0.10
+ '@types/d3-transition': 3.0.8
+ '@types/d3-zoom': 3.0.8
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-zoom: 3.0.0
+
'@zip.js/[email protected]': {}
@@ -35448,20 +35367,6 @@ snapshots:
dependencies:
loose-envify: 1.4.0
- dependencies:
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- transitivePeerDependencies:
- - '@types/react'
- - immer
-
dependencies:
pify: 2.3.0