Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-modeling): add draggable lineage nodes (#110638)

Jovan Sakovic4aab31c61add
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index dbb70237ec84..3a1e63fce72e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6530,6 +6530,10 @@ snapshots:
hash: v1.k794b7964.dbaa1992239d54c653a2132b63857ca77420a178b662c000fb93e7fded648a19.XVks3zJgtqjlm24-mHsgMx3boV8KNZNtXN5dcph4LWw
products-data-modeling-lineage-graph--dark-mode--light:
hash: v1.k794b7964.bc8a6b5f4e177299e6b7ca346135a43ecbd3048405692bb1e75a8747f695c12d.Cg73TPpnrS5uZDxIKIWiV4BhszAzKFH_dSHExM_kkJM
+ products-data-modeling-lineage-graph--draggable-nodes--dark:
+ hash: v1.k794b7964.e7fa348d01185cb0caead49e88f43afcc2885992c4a4b79f59fc34da6f19bca5.WfK2u7q2UakJ496Kt9G7l76XIhBA-49hcrL2MlwGS4w
+ products-data-modeling-lineage-graph--draggable-nodes--light:
+ hash: v1.k794b7964.dfc5bc62d287ed88c8dfa9630052ea2f67037f2e3d7440d95560f7fc99824a3e.po-hGnD-1T6eHcFvVKT5ZmshWvlAiioiNIfH4z5Lw28
products-data-modeling-lineage-graph--empty-state--dark:
hash: v1.k794b7964.9870c50d45ee1583472d6a98917a350892a8c2d8e29c20d17138eb68b8b52d60.yi6jAXaHCs0dh9kUIVgf6aWiVa8Btlb2b9xUQw_q4VE
products-data-modeling-lineage-graph--empty-state--light:
@@ -6550,6 +6554,14 @@ snapshots:
hash: v1.k794b7964.6cf877fd61e23f3c5b70fdb3961c6a3de97bd8f2e4a302f89f9e758b87f27cee.rPxDLCVvyPsn_zke4mpEdJv1uTirwMtjpnhPSglInPs
products-data-modeling-lineage-graph--loading-focused--light:
hash: v1.k794b7964.ad5f3bb5a4c9a5193cf69e525d90f14a6593bcd863437ae10d7148c798720278.N7js9PPoiXJKVTgurWgbO00-kxtsO-gsKxcFaaZAhPo
+ products-data-modeling-lineage-graph--moved-node-focus--dark:
+ hash: v1.k794b7964.104d9527724d974ab4b4d6482ff8e7c9ab7865bcd0598d160e3727fd94989c7c.IoqXmWo1wJlpwX22IL_FBQKV58RLpNmvOgIzxky6qaI
+ products-data-modeling-lineage-graph--moved-node-focus--light:
+ hash: v1.k794b7964.526c6f5cc22548b7fb466ed640a7add56aaa64ac0282ae60e01b38cfc50ca7f1.Nrl9rYDuPwqzmSMwBCLldb8SBiNn031dS_cIgevFJZA
+ products-data-modeling-lineage-graph--reset-moved-nodes--dark:
+ hash: v1.k794b7964.15e5e88b4178f0347d9ebae1f83d8a236fb988fbc621204f2ed568717c9b0b08.z7W9cDpbkr85TkgQHo9H6-fXSsVQ5irrpJUU3HhU2Lg
+ products-data-modeling-lineage-graph--reset-moved-nodes--light:
+ hash: v1.k794b7964.b54ae28affd8c87b5762de3905c081e087a5d2c6ef78ab3335ffb55e12972130.W9m2cQGMi-7XuGKMEtcWkE9L5SQ8rM-UY0Ktgn7IWO8
products-data-modeling-lineage-graph--search-focus--dark:
hash: v1.k794b7964.bb7fd2d6e2a32b2ae732793749f5c3378b9ddeed90115a169515e50611fc0558.hzBxXCNRLcqtZ_OV-8RcnASe8V2kyVEPHXqAlYkrmtY
products-data-modeling-lineage-graph--search-focus--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6710c838cdad..52bbe3759108 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -302,6 +302,7 @@ export const FEATURE_FLAGS = {
DASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,new
DASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platform
DATA_MODELING_INCREMENTAL_VIEWS: 'data-modeling-incremental-views', // owner: #team-data-modeling
+ DATA_MODELING_LINEAGE_NODE_DRAGGING: 'data-modeling-lineage-node-dragging', // owner: #team-data-modeling
DATA_QUALITY_CHECKS: 'data-quality-checks', // owner: #team-data-modeling
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
diff --git a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
index 12e82ede2d41..da07ec87dd3d 100644
--- a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
+++ b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
@@ -1,5 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react'
import { fireEvent, waitFor, within } from '@testing-library/dom'
+import type { XYPosition } from '@xyflow/react'
+import { MakeLogicType, actions, kea, path, reducers, useActions, useValues } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
import { mswDecorator } from '~/mocks/browser'
import { DataModelingEdge, DataModelingNode } from '~/types'
@@ -61,6 +65,60 @@ const GRAPH_EDGES: DataModelingEdge[] = [
mockEdge('e5', '4', '6'),
]
+const MOVED_NODE_POSITIONS: Record<string, XYPosition> = { '6': { x: 1500, y: 700 } }
+
+interface DraggableLineageGraphStoryLogicValues {
+ nodePositions: Record<string, XYPosition>
+}
+
+interface DraggableLineageGraphStoryLogicActions {
+ nodeDragStopped: (nodeId: string, position: XYPosition) => { nodeId: string; position: XYPosition }
+ resetNodePositions: () => Record<string, never>
+}
+
+type DraggableLineageGraphStoryLogicType = MakeLogicType<
+ DraggableLineageGraphStoryLogicValues,
+ DraggableLineageGraphStoryLogicActions
+>
+
+const draggableLineageGraphStoryLogic = kea<DraggableLineageGraphStoryLogicType>([
+ path(['products', 'data_modeling', 'lineage', 'draggableLineageGraphStoryLogic']),
+ actions({
+ nodeDragStopped: (nodeId: string, position: XYPosition) => ({ nodeId, position }),
+ resetNodePositions: true,
+ }),
+ reducers({
+ nodePositions: [
+ MOVED_NODE_POSITIONS,
+ {
+ nodeDragStopped: (positions, { nodeId, position }) => ({ ...positions, [nodeId]: position }),
+ resetNodePositions: () => ({}),
+ },
+ ],
+ }),
+])
+
+function DraggableLineageGraphStory({ focusMovedNode = false }: { focusMovedNode?: boolean }): JSX.Element {
+ const { nodePositions } = useValues(draggableLineageGraphStoryLogic)
+ const { nodeDragStopped, resetNodePositions } = useActions(draggableLineageGraphStoryLogic)
+
+ return (
+ <LineageGraph
+ nodes={GRAPH_NODES}
+ edges={GRAPH_EDGES}
+ variant="canvas"
+ interactive
+ nodesDraggable
+ nodePositions={nodePositions}
+ onNodeDragStop={(node, position) => nodeDragStopped(node.id, position)}
+ onResetNodePositions={resetNodePositions}
+ searchFocusRequest={focusMovedNode ? { nodeId: '6', requestId: 1 } : undefined}
+ showControls
+ showMinimap
+ />
+ )
+}
+
// Pruning the graph rekeys `lineageGraphLogic`, so react-flow unmounts while ELK lays the cone
// out again. Read the canvas on every poll — a node captured before the relayout is detached,
// and a detached element reports a zero-sized rect that passes any centering check.
@@ -151,6 +209,53 @@ export const Canvas: Story = {
),
}
+export const DraggableNodes: Story = {
+ parameters: { featureFlags: [FEATURE_FLAGS.DATA_MODELING_LINEAGE_NODE_DRAGGING] },
+ render: () => <ModelsLineageTab />,
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/data_modeling_nodes/': { count: GRAPH_NODES.length, results: GRAPH_NODES },
+ '/api/environments/:team_id/data_modeling_edges/': { count: GRAPH_EDGES.length, results: GRAPH_EDGES },
+ },
+ }),
+ ],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ const openButton = await canvas.findByLabelText('Open orders in new tab')
+ const nodeCard = canvas.getByText('orders').closest<HTMLElement>('[data-attr="lineage-node"]')
+
+ if (
+ openButton.tagName !== 'A' ||
+ !openButton.getAttribute('href') ||
+ openButton.getAttribute('target') !== '_blank' ||
+ !openButton.classList.contains('nodrag')
+ ) {
+ throw new Error('The explicit node link must open in a new tab')
+ }
+ if (!nodeCard || nodeCard.getAttribute('role') === 'button' || nodeCard.tabIndex >= 0) {
+ throw new Error('A draggable node must not navigate as a card')
+ }
+ },
+}
+
+export const MovedNodeFocus: Story = {
+ render: () => <DraggableLineageGraphStory focusMovedNode />,
+ play: async ({ canvasElement }) => {
+ await expectNodeCentered(canvasElement, '6', 'Search focus must center the moved node, not its ELK position')
+ },
+}
+
+export const ResetMovedNodes: Story = {
+ render: () => <DraggableLineageGraphStory />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await canvas.findByText('monthly_recurring_revenue')
+ fireEvent.click(canvas.getByLabelText('Reset layout'))
+ await expectNodesCentered(canvasElement, 'Reset layout must restore and center the ELK positions')
+ },
+}
+
export const Loading: Story = {
parameters: LOADING_PARAMETERS,
render: () => (
@@ -232,6 +337,16 @@ export const SearchFocus: Story = {
if (graph.querySelectorAll('.react-flow__node').length !== GRAPH_NODES.length) {
throw new Error('Plain search must keep the rest of the graph visible')
}
+
+ fireEvent.change(search, { target: { value: '' } })
+ await expectNodesCentered(canvasElement, 'Clearing search must fit the whole graph')
+ fireEvent.change(search, { target: { value: 'monthly' } })
+ await canvas.findByText('2 results')
+ fireEvent.keyDown(search, { key: 'ArrowDown' })
+ await canvas.findByText('monthly_recurring_revenue, result 2 of 2')
+ fireEvent.keyDown(search, { key: 'Enter' })
+ await expectNodeCentered(canvasElement, '6', 'Repeated search focus must center the requested node')
+
const previousResult = canvas.getByLabelText('Previous result')
previousResult.focus()
fireEvent.click(previousResult)
diff --git a/products/data_modeling/frontend/lineage/LineageGraph.tsx b/products/data_modeling/frontend/lineage/LineageGraph.tsx
index c1a67a06c754..412c7a6403ca 100644
--- a/products/data_modeling/frontend/lineage/LineageGraph.tsx
+++ b/products/data_modeling/frontend/lineage/LineageGraph.tsx
@@ -3,6 +3,7 @@ import '@xyflow/react/dist/style.css'
import {
Background,
BackgroundVariant,
+ ControlButton,
Controls,
FitViewOptions,
MiniMap,
@@ -11,11 +12,12 @@ import {
ReactFlow,
ReactFlowProvider,
useReactFlow,
+ type XYPosition,
} from '@xyflow/react'
import { useValues } from 'kea'
-import { ReactNode, useEffect, useMemo, useRef } from 'react'
+import { type KeyboardEvent, type MouseEvent, ReactNode, useEffect, useMemo, useRef } from 'react'
-import { IconArchive } from '@posthog/icons'
+import { IconArchive, IconRefresh } from '@posthog/icons'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { DataModelingEdge, DataModelingNode } from '~/types'
@@ -40,6 +42,10 @@ export interface LineageGraphProps {
direction?: ElkDirection
/** Enable zoom/pan. Off by default for inline previews */
interactive?: boolean
+ nodesDraggable?: boolean
+ nodePositions?: Record<string, XYPosition>
+ onNodeDragStop?: (node: DataModelingNode, position: XYPosition) => void
+ onResetNodePositions?: () => void
fitViewOptions?: FitViewOptions
focusNodeIds?: Set<string> | null
searchFocusRequest?: { nodeId: string; requestId: number } | null
@@ -56,16 +62,19 @@ export interface LineageGraphProps {
nodeCallbacks?: (node: DataModelingNode) => LineageNodeCallbacks
/** Convenience click handler, used when nodeCallbacks is not provided */
onNodeClick?: (node: DataModelingNode) => void
+ /** Dedicated new-tab link shown on each node */
+ nodeOpenUrl?: (node: DataModelingNode) => string
/** Caller-specific chrome (legend, layout toggle) rendered over the canvas */
panels?: ReactNode
panelPosition?: PanelPosition
}
function LineageGraphContent(props: LineageGraphProps): JSX.Element {
- const { fitView, viewportInitialized } = useReactFlow()
+ const { fitView, setNodes, viewportInitialized } = useReactFlow()
const nodesMeasured = useNodesMeasured()
const { isDarkModeOn } = useValues(themeLogic)
- const { currentNodeId, nodeState, nodeCallbacks, onNodeClick, focusNodeIds, searchFocusRequest } = props
+ const { currentNodeId, nodeState, nodeCallbacks, onNodeClick, nodeOpenUrl, focusNodeIds, searchFocusRequest } =
+ props
const { layout } = useValues(
lineageGraphLogic({
nodes: props.loading ? EMPTY_NODES : props.nodes,
@@ -75,6 +84,10 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
})
)
const fittedLayout = useRef<typeof layout>(null)
+ const fittedFocus = useRef<{ focusNodeIds: Set<string>; layout: typeof layout } | null>(null)
+ const fittedSearchRequest = useRef<{ requestId: number; layout: typeof layout } | null>(null)
+ const lastNodeDrag = useRef<{ nodeId: string; stoppedAt: number } | null>(null)
+ const resetRequested = useRef(false)
// Decorating on every render would hand react-flow new node objects, which drops the sizes it
// measured — so the fit below would keep waiting and the edges would keep being redrawn.
@@ -82,20 +95,77 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
() =>
layout?.nodes.map((rfNode) => {
const node = rfNode.data.node as DataModelingNode
+ const callbacks = nodeCallbacks?.(node) ?? {
+ onClick: onNodeClick ? () => onNodeClick(node) : undefined,
+ }
+ const onClick = callbacks.onClick
return {
...rfNode,
+ position: props.nodePositions?.[node.id] ?? rfNode.position,
data: {
...rfNode.data,
+ draggable: props.nodesDraggable,
+ openUrl: nodeOpenUrl?.(node),
state: { isCurrent: node.id === currentNodeId, ...nodeState?.(node) },
- callbacks: nodeCallbacks?.(node) ?? {
- onClick: onNodeClick ? () => onNodeClick(node) : undefined,
+ callbacks: {
+ ...callbacks,
+ onClick: onClick
+ ? (event: MouseEvent | KeyboardEvent) => {
+ const lastDrag = lastNodeDrag.current
+ const isDragClick =
+ event.detail > 0 &&
+ lastDrag?.nodeId === node.id &&
+ Date.now() - lastDrag.stoppedAt <= 200
+ if (!isDragClick) {
+ onClick(event)
+ }
+ }
+ : undefined,
},
},
}
}) ?? [],
- [currentNodeId, layout, nodeCallbacks, nodeState, onNodeClick]
+ [
+ currentNodeId,
+ layout,
+ nodeCallbacks,
+ nodeOpenUrl,
+ nodeState,
+ onNodeClick,
+ props.nodePositions,
+ props.nodesDraggable,
+ ]
)
+ useEffect(() => {
+ setNodes((currentNodes) => {
+ if (currentNodes === decoratedNodes) {
+ return currentNodes
+ }
+ const currentNodesById = new Map(currentNodes.map((node) => [node.id, node]))
+ return decoratedNodes.map((node) => {
+ const currentNode = currentNodesById.get(node.id)
+ const measuredNode = currentNode?.measured ? { ...node, measured: currentNode.measured } : node
+ return currentNode?.dragging
+ ? { ...measuredNode, position: currentNode.position, dragging: true }
+ : measuredNode
+ })
+ })
+ }, [decoratedNodes, setNodes])
+
+ const resetLayout = (): void => {
+ resetRequested.current = true
+ props.onResetNodePositions?.()
+ }
+
+ useEffect(() => {
+ if (!resetRequested.current || Object.keys(props.nodePositions ?? {}).length > 0) {
+ return
+ }
+ resetRequested.current = false
+ void fitView({ nodes: decoratedNodes, padding: props.fitViewOptions?.padding ?? 0.2, duration: 400 })
+ }, [decoratedNodes, fitView, props.fitViewOptions?.padding, props.nodePositions])
+
useEffect(() => {
if (!viewportInitialized || !nodesMeasured || !layout || props.loading || fittedLayout.current === layout) {
return
@@ -106,13 +176,14 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
}
void fitView({
...props.fitViewOptions,
- nodes: layout.nodes,
+ nodes: decoratedNodes,
padding: props.fitViewOptions?.padding ?? 0.2,
duration: 400,
})
}, [
fitView,
focusNodeIds,
+ decoratedNodes,
layout,
nodesMeasured,
props.fitViewOptions,
@@ -122,13 +193,22 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
])
useEffect(() => {
- if (!viewportInitialized || !focusNodeIds || !layout || props.loading) {
+ if (!focusNodeIds) {
+ fittedFocus.current = null
+ return
+ }
+ if (!viewportInitialized || !nodesMeasured || !layout || props.loading) {
+ return
+ }
+ if (fittedFocus.current?.focusNodeIds === focusNodeIds && fittedFocus.current.layout === layout) {
return
}
// An empty focusNodeIds means the search was cleared, so fit the whole graph again rather
// than leave the viewport where the last selector zoomed it.
- const nodes = focusNodeIds.size > 0 ? layout.nodes.filter((node) => focusNodeIds.has(node.id)) : layout.nodes
+ const nodes =
+ focusNodeIds.size > 0 ? decoratedNodes.filter((node) => focusNodeIds.has(node.id)) : decoratedNodes
if (nodes.length > 0) {
+ fittedFocus.current = { focusNodeIds, layout }
void fitView({
nodes,
padding: 0.2,
@@ -136,17 +216,28 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
maxZoom: focusNodeIds.size > 0 ? 2 : undefined,
})
}
- }, [fitView, viewportInitialized, focusNodeIds, layout, props.loading])
+ }, [decoratedNodes, fitView, viewportInitialized, nodesMeasured, focusNodeIds, layout, props.loading])
useEffect(() => {
- if (!viewportInitialized || !searchFocusRequest || !layout || props.loading) {
+ if (!searchFocusRequest) {
+ fittedSearchRequest.current = null
return
}
- const node = layout.nodes.find((layoutNode) => layoutNode.id === searchFocusRequest.nodeId)
+ if (!viewportInitialized || !nodesMeasured || !layout || props.loading) {
+ return
+ }
+ if (
+ fittedSearchRequest.current?.requestId === searchFocusRequest.requestId &&
+ fittedSearchRequest.current.layout === layout
+ ) {
+ return
+ }
+ const node = decoratedNodes.find((renderedNode) => renderedNode.id === searchFocusRequest.nodeId)
if (node) {
+ fittedSearchRequest.current = { requestId: searchFocusRequest.requestId, layout }
void fitView({ nodes: [node], padding: 0.2, duration: 400, maxZoom: 2 })
}
- }, [fitView, viewportInitialized, searchFocusRequest, layout, props.loading])
+ }, [decoratedNodes, fitView, viewportInitialized, nodesMeasured, searchFocusRequest, layout, props.loading])
if (props.loading || !layout) {
const center = props.loadingCenter ?? props.nodes.find((node) => node.id === currentNodeId)
@@ -163,11 +254,16 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
return (
<ReactFlow
colorMode={isDarkModeOn ? 'dark' : 'light'}
- nodes={decoratedNodes}
+ defaultNodes={decoratedNodes}
edges={layout.edges}
nodeTypes={LINEAGE_NODE_TYPES}
- nodesDraggable={false}
+ nodesDraggable={props.nodesDraggable ?? false}
+ onNodeDragStop={(_, node) => {
+ lastNodeDrag.current = { nodeId: node.id, stoppedAt: Date.now() }
+ props.onNodeDragStop?.(node.data.node as DataModelingNode, node.position)
+ }}
nodesConnectable={false}
+ elementsSelectable={false}
// The card inside each node is the focus target and carries the key handler. A focusable
// wrapper would add a second tab stop per node that only selects and never navigates.
nodesFocusable={false}
@@ -180,7 +276,20 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
proOptions={{ hideAttribution: true }}
>
<Background variant={BackgroundVariant.Dots} gap={20} size={1} />
- {props.showControls && <Controls showInteractive={false} position="bottom-right" />}
+ {props.showControls && (
+ <Controls showInteractive={false} position="bottom-right">
+ {props.nodesDraggable && props.onResetNodePositions && (
+ <ControlButton
+ aria-label="Reset layout"
+ title="Reset layout"
+ onClick={resetLayout}
+ data-attr="models-lineage-reset-layout"
+ >
+ <IconRefresh aria-hidden="true" />
+ </ControlButton>
+ )}
+ </Controls>
+ )}
{props.showMinimap && (
<MiniMap
zoomable
diff --git a/products/data_modeling/frontend/lineage/LineageNode.tsx b/products/data_modeling/frontend/lineage/LineageNode.tsx
index aa421a0e58b3..6386c3138efe 100644
--- a/products/data_modeling/frontend/lineage/LineageNode.tsx
+++ b/products/data_modeling/frontend/lineage/LineageNode.tsx
@@ -5,6 +5,7 @@ import React, { useCallback, useState } from 'react'
import {
IconActivity,
IconClockRewind,
+ IconExternal,
IconPauseFilled,
IconPencil,
IconPlay,
@@ -55,7 +56,7 @@ export interface LineageNodeState {
}
export interface LineageNodeCallbacks {
- onClick?: () => void
+ onClick?: (event: React.MouseEvent | React.KeyboardEvent) => void
onEdit?: () => void
onMaterialize?: () => void
onRunUpstream?: () => void
@@ -68,6 +69,8 @@ export interface LineageNodeData extends Record<string, unknown> {
node: LineageNodeShape
variant: LineageVariant
direction: ElkDirection
+ draggable?: boolean
+ openUrl?: string
state: LineageNodeState
callbacks: LineageNodeCallbacks
handles: NodeHandle[]
@@ -270,7 +273,7 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
const handleKeyDown = (e: React.KeyboardEvent): void => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
- callbacks.onClick?.()
+ callbacks.onClick?.(e)
}
}
@@ -286,7 +289,9 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
<Tooltip title={node.name} delayMs={500}>
<div
className={clsx(
- 'relative rounded-lg border bg-bg-light cursor-pointer min-w-[180px]',
+ 'relative rounded-lg border bg-bg-light min-w-[180px]',
+ callbacks.onClick && 'cursor-pointer',
+ !callbacks.onClick && data.draggable && 'cursor-grab active:cursor-grabbing',
state.isRunning && 'animate-pulse',
state.isRunning && !state.isSelected && 'border-warning ring-2 ring-warning/30',
state.isSelected && 'border-link ring-4 ring-link/40',
@@ -314,6 +319,7 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
role={callbacks.onClick ? 'button' : undefined}
tabIndex={callbacks.onClick ? 0 : undefined}
aria-label={callbacks.onClick ? ariaLabel : undefined}
+ data-attr="lineage-node"
>
{data.handles.map((handle) => (
<Handle
@@ -352,11 +358,27 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
<NodeTypeTag type={node.type} />
{node.lineage_issue && <LineageIssueMarker issue={node.lineage_issue} />}
</div>
- {node.user_tag && (
- <span className="text-[10px] text-muted lowercase tracking-wide px-1 rounded bg-primary dark:bg-primary/20 border-1 border-black/20">
- #{node.user_tag}
- </span>
- )}
+ <div className="flex items-center gap-1">
+ {node.user_tag && (
+ <span className="text-[10px] text-muted lowercase tracking-wide px-1 rounded bg-primary dark:bg-primary/20 border-1 border-black/20">
+ #{node.user_tag}
+ </span>
+ )}
+ {data.openUrl && (
+ <LemonButton
+ className="nodrag nopan"
+ size="xxsmall"
+ type="secondary"
+ to={data.openUrl}
+ targetBlank
+ stopPropagation
+ tooltip={`Open ${node.name} in new tab`}
+ aria-label={`Open ${node.name} in new tab`}
+ icon={<IconExternal />}
+ data-attr="lineage-node-open"
+ />
+ )}
+ </div>
</div>
<div className="flex items-center justify-between gap-2 py-2">
<span className="font-medium text-sm truncate">{node.name}</span>
diff --git a/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx b/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx
index e4a45b5adf46..afce2529f8ed 100644
--- a/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx
+++ b/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx
@@ -5,6 +5,7 @@ import { useRef } from 'react'
import { IconInfo } from '@posthog/icons'
import { LemonButton, LemonInput, Tooltip } from '@posthog/lemon-ui'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect'
import { pluralize } from 'lib/utils/strings'
@@ -25,6 +26,7 @@ const TYPE_OPTIONS = LINEAGE_FILTER_TYPES.map((type) => ({
export function ModelsLineageTab(): JSX.Element {
const searchInputRef = useRef<HTMLInputElement>(null)
+ const nodesDraggable = useFeatureFlag('DATA_MODELING_LINEAGE_NODE_DRAGGING')
const {
nodes,
nodesLoading,
@@ -44,6 +46,7 @@ export function ModelsLineageTab(): JSX.Element {
visibleNodes,
visibleEdges,
isFiltered,
+ nodePositions,
} = useValues(modelsLineageLogic)
const {
setSearchTerm,
@@ -53,6 +56,8 @@ export function ModelsLineageTab(): JSX.Element {
focusSearchResult,
toggleLegendCollapsed,
resetFilters,
+ nodeDragStopped,
+ resetNodePositions,
} = useActions(modelsLineageLogic)
const focusSearchInput = (): void => {
@@ -157,6 +162,11 @@ export function ModelsLineageTab(): JSX.Element {
searchFocusRequest={searchFocusRequest}
variant="canvas"
interactive
+ nodesDraggable={nodesDraggable}
+ nodePositions={nodesDraggable ? nodePositions : undefined}
+ nodeOpenUrl={nodesDraggable ? lineageNodeUrl : undefined}
+ onNodeDragStop={nodesDraggable ? (node, position) => nodeDragStopped(node.id, position) : undefined}
+ onResetNodePositions={nodesDraggable ? resetNodePositions : undefined}
showControls
showMinimap
minimapPosition="top-right"
@@ -169,7 +179,7 @@ export function ModelsLineageTab(): JSX.Element {
isSelected: selectedSearchResult?.id === node.id,
isRunning: node.last_run_status === 'Running',
})}
- onNodeClick={(node) => router.actions.push(lineageNodeUrl(node))}
+ onNodeClick={nodesDraggable ? undefined : (node) => router.actions.push(lineageNodeUrl(node))}
panelPosition="bottom-left"
panels={<NodeTypeLegend collapsed={legendCollapsed} onToggleCollapse={toggleLegendCollapsed} />}
/>
diff --git a/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts b/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts
index 93540c84f610..65f3f1736326 100644
--- a/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts
+++ b/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts
@@ -1,4 +1,5 @@
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -28,6 +29,7 @@ describe('modelsLineageLogic', () => {
},
})
initKeaTests()
+ jest.mocked(posthog.capture).mockClear()
logic = modelsLineageLogic()
logic.mount()
await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess', 'loadEdgesSuccess'])
@@ -186,4 +188,24 @@ describe('modelsLineageLogic', () => {
searchFocusRequest: { nodeId: '4', requestId: 1 },
})
})
+
+ it('keeps manual node positions through filtering until the layout is reset', async () => {
+ const position = { x: 120, y: 80 }
+
+ logic.actions.nodeDragStopped('1', position)
+ logic.actions.setTypeFilter(['view'])
+
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({ nodePositions: { '1': position } })
+
+ expect(posthog.capture).toHaveBeenCalledWith('models lineage node moved', {
+ node_type: 'table',
+ is_filtered: false,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.resetNodePositions()
+ }).toMatchValues({ nodePositions: {} })
+ })
})
diff --git a/products/data_modeling/frontend/lineage/modelsLineageLogic.ts b/products/data_modeling/frontend/lineage/modelsLineageLogic.ts
index bc28967cb679..6977d6eed0a5 100644
--- a/products/data_modeling/frontend/lineage/modelsLineageLogic.ts
+++ b/products/data_modeling/frontend/lineage/modelsLineageLogic.ts
@@ -1,3 +1,4 @@
+import type { XYPosition } from '@xyflow/react'
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
@@ -17,6 +18,9 @@ export const LINEAGE_FILTER_TYPES: DataModelingNodeType[] = Object.values(NodeTy
type SearchResultFocusTrigger = 'keyboard' | 'click' | 'previous' | 'next'
+// Product analytics can depend on this event name, so keep it stable.
+const MODELS_LINEAGE_NODE_MOVED_EVENT = 'models lineage node moved'
+
export interface SearchFocusRequest {
nodeId: string
requestId: number
@@ -46,6 +50,7 @@ export interface modelsLineageLogicValues {
visibleNodes: DataModelingNode[]
visibleEdges: DataModelingEdge[]
isFiltered: boolean
+ nodePositions: Record<string, XYPosition>
}
export interface modelsLineageLogicActions {
@@ -69,6 +74,8 @@ export interface modelsLineageLogicActions {
}
toggleLegendCollapsed: () => Record<string, never>
resetFilters: () => Record<string, never>
+ nodeDragStopped: (nodeId: string, position: XYPosition) => { nodeId: string; position: XYPosition }
+ resetNodePositions: () => Record<string, never>
}
export type modelsLineageLogicType = MakeLogicType<modelsLineageLogicValues, modelsLineageLogicActions>
@@ -87,6 +94,8 @@ export const modelsLineageLogic = kea<modelsLineageLogicType>([
focusSearchResult: (nodeId: string, trigger: SearchResultFocusTrigger) => ({ nodeId, trigger }),
toggleLegendCollapsed: true,
resetFilters: true,
+ nodeDragStopped: (nodeId: string, position: XYPosition) => ({ nodeId, position }),
+ resetNodePositions: true,
}),
reducers({
searchTerm: [
@@ -136,6 +145,13 @@ export const modelsLineageLogic = kea<modelsLineageLogicType>([
resetFilters: () => null,
},
],
+ nodePositions: [
+ {} as Record<string, XYPosition>,
+ {
+ nodeDragStopped: (positions, { nodeId, position }) => ({ ...positions, [nodeId]: position }),
+ resetNodePositions: () => ({}),
+ },
+ ],
}),
listeners(({ actions, values }) => ({
// Every keystroke would otherwise prune the graph and start a fresh ELK layout.
@@ -174,6 +190,15 @@ export const modelsLineageLogic = kea<modelsLineageLogicType>([
})
}
},
+ nodeDragStopped: ({ nodeId }) => {
+ const node = values.nodes.find((candidate) => candidate.id === nodeId)
+ if (node) {
+ posthog.capture(MODELS_LINEAGE_NODE_MOVED_EVENT, {
+ node_type: node.type,
+ is_filtered: values.isFiltered,
+ })
+ }
+ },
})),
selectors({
parsedSearchTerm: [(s) => [s.searchTerm], (searchTerm: string) => parseLineageSearch(searchTerm)],