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): highlight lineage on click and add a node menu (#111175)

Jovan Sakovic123d468ee730
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 37fe1d556c55..53a8ad02e8ad 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6687,13 +6687,17 @@ snapshots:
products-data-modeling-lineage-graph--reset-moved-nodes--light:
hash: v1.k794b7964.58aa75c5200337a71da0b9e4eb6455df23e16c91592982406f1934d9fcab4173.uvZ46-W9atDhcT0R_h9rtD0s4Z4UItW3nnL-9DDi6Lg
products-data-modeling-lineage-graph--search-focus--dark:
- hash: v1.k794b7964.c6bbd5662f44ae3c049af510a720695e8dc4e32fc3aa62a3e46c9721cf3c8cf4.5J3A6g_ZGj4lHduTNNFde5_FR6AJF1fpMfdLwdmp77U
+ hash: v1.k794b7964.5d7be76a33e7ae6df78aefed37a4457e715de7366eac74c7fe797cc4ebb94572.QhMijLKdjHkiCM-8bYkRm8K-4h5hA1Mqu1xtEyleSqE
products-data-modeling-lineage-graph--search-focus--light:
- hash: v1.k794b7964.01b0ba3eef46ca6062549746c987d16be44d29b49a359b9d50f61b6a493f1282.XYFsMELihoJxhKSk1w5Dir9tjglJ7cuc53lrnpVO5GU
+ hash: v1.k794b7964.6d3766df17830581fe2bdb54348d733bee6587d9715b4c47960fa175ffa0c3b1.ZutGBNNBQUS3coCVsLxlreoxXzdIYrFpLCGaFM6ntxA
+ products-data-modeling-lineage-graph--selectable--dark:
+ hash: v1.k794b7964.6715d1a72146914d134deef3cc269fa35d5c1d2de75e863c43ffd4dfa13928b6.GObyY80pnRagOt_eHG5SjVjTUjGavbHm6QinFyLCoMg
+ products-data-modeling-lineage-graph--selectable--light:
+ hash: v1.k794b7964.579d47e411eb1193beb2e755ccff18fb4aa8a7fb8ed4695fc2cf7c83db9744d1.pOkDE2mWmnzAPs_sMwCSKmgYXq8XS625_wQfbNL6ZXo
products-data-modeling-lineage-graph--selector-focus--dark:
- hash: v1.k794b7964.8a4d94fd9e9218ed6d6c51add35561489602b263b639b8d3037d94c9c6c38cc5.4KGmwfgzcseL11b9Wkt3uAQ7CYcvWUhDD1ahUEcqUS0
+ hash: v1.k794b7964.413f24009c5c56513324d5b159121d68d991a467aa64598d24ff297772aefe31.Ak92fV37aEoxdElxT_kg-nBT3oiyT1UQ9DdPkK4QBu0
products-data-modeling-lineage-graph--selector-focus--light:
- hash: v1.k794b7964.ea66ffeafce86f35e88b88278d614e73b67a987603cc0fbeecc4e2fea3e0b709.g5XUGqtsw1n6fL5bbbaz8FyztTggLARgUUKsDlQ9QiI
+ hash: v1.k794b7964.25e2e198212f76604c03e486ce03cc4f025200ba48ed574c8058ca885021f4e4.Rmi_EAGJ_je1eiVwQt99dOA-sjEgiMzJX6WmhHy0RUc
products-data-modeling-lineage-graph--single-node--dark:
hash: v1.k794b7964.3a7800242792b8dd49d06a252b0ccf609de5be3bf5b077e28904ca2ef46b9150.3jN6spC1a4TJhjq6LOuaDGym92gQz9Xw2KUfy0Br-D8
products-data-modeling-lineage-graph--single-node--light:
diff --git a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
index 2e60d81d23a1..691b5e7b3eb0 100644
--- a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
+++ b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
@@ -209,6 +209,45 @@ export const Canvas: Story = {
),
}
+export const Selectable: Story = {
+ render: () => <LineageGraph nodes={GRAPH_NODES} edges={GRAPH_EDGES} variant="canvas" selectable interactive />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ const selectedNode = (await canvas.findByText('monthly_report')).closest<HTMLElement>(
+ '[data-attr="lineage-node"]'
+ )
+ const relatedNode = canvas.getByText('orders').closest<HTMLElement>('[data-attr="lineage-node"]')
+ const siblingNode = canvas
+ .getByText('weekly_active_accounts')
+ .closest<HTMLElement>('[data-attr="lineage-node"]')
+ const pane = canvasElement.querySelector<HTMLElement>('.react-flow__pane')
+
+ if (!selectedNode || !relatedNode || !siblingNode || !pane) {
+ throw new Error('The selectable graph must render its nodes and pane')
+ }
+
+ fireEvent.click(selectedNode)
+ await waitFor(() => {
+ if (!selectedNode.classList.contains('ring-4')) {
+ throw new Error('The clicked node must show the selected state')
+ }
+ if (relatedNode.classList.contains('opacity-30')) {
+ throw new Error('An upstream node must stay highlighted')
+ }
+ if (!siblingNode.classList.contains('opacity-30')) {
+ throw new Error('A node outside the selected lineage must be dimmed')
+ }
+ })
+
+ fireEvent.click(pane)
+ await waitFor(() => {
+ if (siblingNode.classList.contains('opacity-30')) {
+ throw new Error('Clicking the canvas must clear the lineage selection')
+ }
+ })
+ },
+}
+
// The minimap is gated on the canvas container instead of the viewport, so a canvas that is narrow
// inside a wide window must still hide it and leave the zoom controls room. The graph is cut to two
// nodes because fit-view scales the whole graph into 480px, and nodes that small render text the
@@ -233,17 +272,17 @@ export const NarrowCanvas: Story = {
],
}
+const modelsTabDecorator = 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 },
+ },
+})
+
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 },
- },
- }),
- ],
+ decorators: [modelsTabDecorator],
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
const openButton = await canvas.findByLabelText('Open orders in new tab')
@@ -257,8 +296,55 @@ export const DraggableNodes: Story = {
) {
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')
+ if (!nodeCard || !nodeCard.classList.contains('cursor-grab')) {
+ throw new Error('A draggable node must keep its drag affordance')
+ }
+ const selectionButton = within(nodeCard).getByRole('button', { name: /highlights its lineage/ })
+ if (selectionButton.tabIndex < 0) {
+ throw new Error('Lineage selection must be keyboard accessible')
+ }
+ if (getComputedStyle(openButton).opacity !== '0') {
+ throw new Error('The open link must stay hidden until the node has hover or focus')
+ }
+
+ selectionButton.focus()
+ await waitFor(() => {
+ if (getComputedStyle(openButton).opacity !== '1') {
+ throw new Error('Keyboard focus must reveal the open link')
+ }
+ })
+ selectionButton.blur()
+ await waitFor(() => {
+ if (getComputedStyle(openButton).opacity !== '0') {
+ throw new Error('The open link must hide after the node loses focus')
+ }
+ })
+ },
+}
+
+// The play function leaves the menu open, so this story takes no snapshot. Opening the menu in
+// DraggableNodes instead would paint it over that story's picture on every run.
+export const NodeMenu: Story = {
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.DATA_MODELING_LINEAGE_NODE_DRAGGING],
+ testOptions: { snapshotBrowsers: [] },
+ },
+ render: () => <ModelsLineageTab />,
+ decorators: [modelsTabDecorator],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ const nodeCard = (await canvas.findByText('orders')).closest<HTMLElement>('[data-attr="lineage-node"]')
+
+ if (!nodeCard) {
+ throw new Error('A node must render as a card')
+ }
+
+ fireEvent.contextMenu(nodeCard)
+ const page = within(canvasElement.ownerDocument.body)
+ await page.findByRole('menuitem', { name: 'Open in new tab' })
+ await page.findByRole('menuitem', { name: 'Copy name' })
+ if (page.queryByText(/Highlight|Show only/)) {
+ throw new Error('The node menu must not duplicate the graph lineage behavior')
}
},
}
diff --git a/products/data_modeling/frontend/lineage/LineageGraph.tsx b/products/data_modeling/frontend/lineage/LineageGraph.tsx
index 623e0a00273d..a30ae34222ca 100644
--- a/products/data_modeling/frontend/lineage/LineageGraph.tsx
+++ b/products/data_modeling/frontend/lineage/LineageGraph.tsx
@@ -16,7 +16,7 @@ import {
} from '@xyflow/react'
import clsx from 'clsx'
import { useValues } from 'kea'
-import { type KeyboardEvent, type MouseEvent, ReactNode, useEffect, useMemo, useRef } from 'react'
+import { type KeyboardEvent, type MouseEvent, ReactNode, useEffect, useMemo, useRef, useState } from 'react'
import { IconArchive, IconRefresh } from '@posthog/icons'
@@ -27,6 +27,7 @@ import { ElkDirection } from './autolayout'
import { LineageGraphLoading } from './LineageGraphLoading'
import { lineageGraphLogic } from './lineageGraphLogic'
import { LINEAGE_NODE_TYPES, LineageNodeCallbacks, LineageNodeState, LineageVariant } from './LineageNode'
+import { lineageCone } from './lineageSelection'
import { useNodesMeasured } from './useNodesMeasured'
export type { LineageVariant, LineageNodeState, LineageNodeCallbacks } from './LineageNode'
@@ -64,6 +65,8 @@ export interface LineageGraphProps {
onNodeClick?: (node: DataModelingNode) => void
/** Dedicated new-tab link shown on each node */
nodeOpenUrl?: (node: DataModelingNode) => string
+ /** Clicking a node highlights its full upstream and downstream lineage */
+ selectable?: boolean
/** Caller-specific chrome (legend, layout toggle) rendered over the canvas */
panels?: ReactNode
}
@@ -72,6 +75,7 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
const { fitView, setNodes, viewportInitialized } = useReactFlow()
const nodesMeasured = useNodesMeasured()
const { isDarkModeOn } = useValues(themeLogic)
+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null)
const { currentNodeId, nodeState, nodeCallbacks, onNodeClick, nodeOpenUrl, focusNodeIds, searchFocusRequest } =
props
const { layout } = useValues(
@@ -87,6 +91,16 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
const fittedSearchRequest = useRef<{ requestId: number; layout: typeof layout } | null>(null)
const lastNodeDrag = useRef<{ nodeId: string; stoppedAt: number } | null>(null)
const resetRequested = useRef(false)
+ const selectedLineage = useMemo(
+ () => (props.selectable && selectedNodeId ? lineageCone(props.edges, selectedNodeId) : null),
+ [props.edges, props.selectable, selectedNodeId]
+ )
+
+ useEffect(() => {
+ if (selectedNodeId && !props.nodes.some((node) => node.id === selectedNodeId)) {
+ setSelectedNodeId(null)
+ }
+ }, [props.nodes, selectedNodeId])
// 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.
@@ -94,10 +108,14 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
() =>
layout?.nodes.map((rfNode) => {
const node = rfNode.data.node as DataModelingNode
- const callbacks = nodeCallbacks?.(node) ?? {
+ const baseCallbacks = nodeCallbacks?.(node) ?? {
onClick: onNodeClick ? () => onNodeClick(node) : undefined,
}
+ const callbacks = props.selectable
+ ? { ...baseCallbacks, onClick: () => setSelectedNodeId(node.id) }
+ : baseCallbacks
const onClick = callbacks.onClick
+ const callerState = nodeState?.(node)
return {
...rfNode,
position: props.nodePositions?.[node.id] ?? rfNode.position,
@@ -105,7 +123,13 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
...rfNode.data,
draggable: props.nodesDraggable,
openUrl: nodeOpenUrl?.(node),
- state: { isCurrent: node.id === currentNodeId, ...nodeState?.(node) },
+ selectable: props.selectable,
+ state: {
+ isCurrent: node.id === currentNodeId,
+ ...callerState,
+ isSelected: callerState?.isSelected || selectedNodeId === node.id,
+ isDimmed: selectedLineage ? !selectedLineage.nodeIds.has(node.id) : callerState?.isDimmed,
+ },
callbacks: {
...callbacks,
onClick: onClick
@@ -133,9 +157,24 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
onNodeClick,
props.nodePositions,
props.nodesDraggable,
+ props.selectable,
+ selectedLineage,
+ selectedNodeId,
]
)
+ const decoratedEdges = useMemo(
+ () =>
+ selectedLineage && layout
+ ? layout.edges.map((edge) =>
+ selectedLineage.edgeIds.has(edge.id)
+ ? { ...edge, zIndex: 1, style: { ...edge.style, stroke: 'var(--link)', strokeWidth: 2 } }
+ : { ...edge, style: { ...edge.style, opacity: 0.15 } }
+ )
+ : layout?.edges,
+ [layout, selectedLineage]
+ )
+
const resetPositionsApplied = useStore(
(state) =>
!resetRequested.current ||
@@ -264,7 +303,8 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
className={clsx('@container/lineage', props.className)}
colorMode={isDarkModeOn ? 'dark' : 'light'}
defaultNodes={decoratedNodes}
- edges={layout.edges}
+ edges={decoratedEdges}
+ onPaneClick={props.selectable ? () => setSelectedNodeId(null) : undefined}
nodeTypes={LINEAGE_NODE_TYPES}
nodesDraggable={props.nodesDraggable ?? false}
onNodeDragStop={(_, node) => {
diff --git a/products/data_modeling/frontend/lineage/LineageNode.tsx b/products/data_modeling/frontend/lineage/LineageNode.tsx
index afdc0ae768a0..38186048fcf4 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,
+ IconCopy,
IconExternal,
IconPauseFilled,
IconPencil,
@@ -17,6 +18,15 @@ import { LemonButton, LemonSkeleton, Spinner, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { useCancelAnimationsOnUnmount } from 'lib/hooks/useCancelAnimationsOnUnmount'
+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuGroup,
+ ContextMenuItem,
+ ContextMenuTrigger,
+} from 'lib/ui/ContextMenu/ContextMenu'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { DataModelingNode } from '~/types'
@@ -52,6 +62,8 @@ export interface LineageNodeState {
/** Ringed when a search or type filter highlights this node */
isHighlighted?: boolean
isSelected?: boolean
+ /** Faded while another node's lineage is selected */
+ isDimmed?: boolean
loading?: 'placeholder' | 'focus'
}
@@ -71,6 +83,7 @@ export interface LineageNodeData extends Record<string, unknown> {
direction: ElkDirection
draggable?: boolean
openUrl?: string
+ selectable?: boolean
state: LineageNodeState
callbacks: LineageNodeCallbacks
handles: NodeHandle[]
@@ -195,6 +208,55 @@ function MetadataBar({ node }: { node: LineageNodeShape }): JSX.Element {
)
}
+function LineageNodeContextMenu({
+ data,
+ children,
+}: {
+ data: LineageNodeData
+ children: React.ReactElement
+}): JSX.Element {
+ const { node, openUrl } = data
+ const trigger = (
+ <Tooltip title={node.name} delayMs={500}>
+ {openUrl ? <ContextMenuTrigger asChild>{children}</ContextMenuTrigger> : children}
+ </Tooltip>
+ )
+
+ if (!openUrl) {
+ return trigger
+ }
+
+ return (
+ <ContextMenu>
+ {trigger}
+ <ContextMenuContent>
+ <ContextMenuGroup>
+ <ContextMenuItem
+ asChild
+ onClick={() => window.open(openUrl, '_blank', 'noopener')}
+ data-attr="lineage-node-menu-open"
+ >
+ <ButtonPrimitive menuItem>
+ <IconExternal />
+ Open in new tab
+ </ButtonPrimitive>
+ </ContextMenuItem>
+ <ContextMenuItem
+ asChild
+ onClick={() => void copyToClipboard(node.name, 'node name')}
+ data-attr="lineage-node-menu-copy-name"
+ >
+ <ButtonPrimitive menuItem>
+ <IconCopy />
+ Copy name
+ </ButtonPrimitive>
+ </ContextMenuItem>
+ </ContextMenuGroup>
+ </ContextMenuContent>
+ </ContextMenu>
+ )
+}
+
export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
const { node, variant, direction, state, callbacks } = data
const [isHovered, setIsHovered] = useState(false)
@@ -270,143 +332,133 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
fn?.()
}
- const handleKeyDown = (e: React.KeyboardEvent): void => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault()
- callbacks.onClick?.(e)
- }
- }
-
const destination = node.type === 'metric' ? 'the metric' : 'the model'
+ const cardAction = data.selectable ? 'highlights its lineage' : `opens ${destination}`
const ariaLabel = [
- `${node.name}, ${NODE_TYPE_TAG_SETTINGS[node.type].label.toLowerCase()}, opens ${destination}`,
+ `${node.name}, ${NODE_TYPE_TAG_SETTINGS[node.type].label.toLowerCase()}, ${cardAction}`,
node.lineage_issue && lineageIssueMessage(node.lineage_issue),
]
.filter(Boolean)
.join('. ')
- return (
- <Tooltip title={node.name} delayMs={500}>
- <div
- className={clsx(
- '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',
- !state.isRunning && !state.isSelected && state.isHighlighted && 'border-link ring-2 ring-link/30',
- !state.isRunning &&
- !state.isSelected &&
- !state.isHighlighted &&
- !state.isCurrent &&
- 'border-border',
- node.lineage_issue &&
- !state.isRunning &&
- !state.isSelected &&
- !state.isHighlighted &&
- 'border-warning',
- state.isCurrent && 'border-2'
- )}
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- borderColor: state.isCurrent ? color : undefined,
- }}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- onClick={callbacks.onClick}
- onKeyDown={callbacks.onClick ? handleKeyDown : undefined}
- 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
- key={handle.id}
- id={handle.id}
- type={handle.type}
- position={handle.position ?? (handle.type === 'target' ? Position.Left : Position.Right)}
- className="opacity-0"
- isConnectable={false}
- />
- ))}
+ const nodeCard = (
+ <div
+ className={clsx(
+ 'group/lineage-node relative pointer-events-auto rounded-lg border bg-bg-light min-w-[180px]',
+ data.draggable && 'cursor-grab active:cursor-grabbing',
+ !data.draggable && callbacks.onClick && 'cursor-pointer',
+ state.isRunning && 'animate-pulse',
+ state.isRunning && !state.isSelected && 'border-warning ring-2 ring-warning/30',
+ state.isSelected && 'border-link ring-4 ring-link/40',
+ !state.isRunning && !state.isSelected && state.isHighlighted && 'border-link ring-2 ring-link/30',
+ !state.isRunning && !state.isSelected && !state.isHighlighted && !state.isCurrent && 'border-border',
+ node.lineage_issue && !state.isRunning && !state.isSelected && !state.isHighlighted && 'border-warning',
+ state.isCurrent && 'border-2',
+ state.isDimmed && 'opacity-30'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ borderColor: state.isCurrent ? color : undefined,
+ }}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ onClick={callbacks.onClick}
+ data-attr="lineage-node"
+ >
+ {callbacks.onClick && (
+ <button
+ type="button"
+ className="absolute inset-0 pointer-events-none rounded-lg focus-visible:ring-4 focus-visible:ring-link/40"
+ onClick={(event) => {
+ event.stopPropagation()
+ callbacks.onClick?.(event)
+ }}
+ aria-label={ariaLabel}
+ />
+ )}
+ {data.handles.map((handle) => (
+ <Handle
+ key={handle.id}
+ id={handle.id}
+ type={handle.type}
+ position={handle.position ?? (handle.type === 'target' ? Position.Left : Position.Right)}
+ className="opacity-0"
+ isConnectable={false}
+ />
+ ))}
- {showRunArrows && node.upstream_count > 0 && callbacks.onRunUpstream && (
- <RunArrow
- direction="upstream"
- layoutDirection={direction}
- onClick={stop(callbacks.onRunUpstream)}
- />
- )}
- {showRunArrows && node.downstream_count > 0 && callbacks.onRunDownstream && (
- <RunArrow
- direction="downstream"
- layoutDirection={direction}
- onClick={stop(callbacks.onRunDownstream)}
- />
- )}
+ {showRunArrows && node.upstream_count > 0 && callbacks.onRunUpstream && (
+ <RunArrow direction="upstream" layoutDirection={direction} onClick={stop(callbacks.onRunUpstream)} />
+ )}
+ {showRunArrows && node.downstream_count > 0 && callbacks.onRunDownstream && (
+ <RunArrow
+ direction="downstream"
+ layoutDirection={direction}
+ onClick={stop(callbacks.onRunDownstream)}
+ />
+ )}
- <div className="px-3 pt-3">
- <div className="flex items-center justify-between gap-2">
- <div className="flex items-center gap-1 min-w-0">
- {state.isCurrent && (
- <Tooltip title="This is the currently viewed node">
- <IconTarget className="text-warning text-sm shrink-0" />
- </Tooltip>
- )}
- <NodeTypeTag type={node.type} />
- {node.lineage_issue && <LineageIssueMarker issue={node.lineage_issue} />}
- </div>
- <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 in new tab"
- aria-label={`Open ${node.name} in new tab`}
- icon={<IconExternal />}
- data-attr="lineage-node-open"
- />
- )}
- </div>
+ <div className="px-3 pt-3">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-1 min-w-0">
+ {state.isCurrent && (
+ <Tooltip title="This is the currently viewed node">
+ <IconTarget className="text-warning text-sm shrink-0" />
+ </Tooltip>
+ )}
+ <NodeTypeTag type={node.type} />
+ {node.lineage_issue && <LineageIssueMarker issue={node.lineage_issue} />}
</div>
- <div className="flex items-center justify-between gap-2 py-2">
- <span className="font-medium text-sm truncate">{node.name}</span>
- {callbacks.onEdit && (
+ <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 relative z-10 opacity-0 transition-opacity group-hover/lineage-node:opacity-100 group-focus-within/lineage-node:opacity-100"
size="xxsmall"
type="secondary"
- icon={<IconPencil />}
- onClick={stop(callbacks.onEdit)}
+ to={data.openUrl}
+ targetBlank
+ stopPropagation
+ tooltip="Open in new tab"
+ aria-label={`Open ${node.name} in new tab`}
+ icon={<IconExternal />}
+ data-attr="lineage-node-open"
/>
)}
- {callbacks.onMaterialize && MATERIALIZING_TYPES.has(node.type) && (
- <Tooltip title={state.isRunning ? null : 'Run this node'}>
- <LemonButton
- size="xsmall"
- type="secondary"
- onClick={stop(callbacks.onMaterialize)}
- disabledReason={state.isRunning && 'This node is already running...'}
- icon={state.isRunning ? <Spinner textColored /> : <IconPlay className="w-3 h-3" />}
- />
- </Tooltip>
- )}
</div>
</div>
- {showMetadata && <MetadataBar node={node} />}
+ <div className="flex items-center justify-between gap-2 py-2">
+ <span className="font-medium text-sm truncate">{node.name}</span>
+ {callbacks.onEdit && (
+ <LemonButton
+ size="xxsmall"
+ type="secondary"
+ icon={<IconPencil />}
+ onClick={stop(callbacks.onEdit)}
+ />
+ )}
+ {callbacks.onMaterialize && MATERIALIZING_TYPES.has(node.type) && (
+ <Tooltip title={state.isRunning ? null : 'Run this node'}>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={stop(callbacks.onMaterialize)}
+ disabledReason={state.isRunning && 'This node is already running...'}
+ icon={state.isRunning ? <Spinner textColored /> : <IconPlay className="w-3 h-3" />}
+ />
+ </Tooltip>
+ )}
+ </div>
</div>
- </Tooltip>
+ {showMetadata && <MetadataBar node={node} />}
+ </div>
)
+
+ return <LineageNodeContextMenu data={data}>{nodeCard}</LineageNodeContextMenu>
}
export const LINEAGE_NODE_TYPES = { lineage: LineageNode }
diff --git a/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx b/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx
index ca2de95e806e..32fec271a289 100644
--- a/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx
+++ b/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx
@@ -1,5 +1,4 @@
import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
import { useRef } from 'react'
import { IconInfo } from '@posthog/icons'
@@ -164,7 +163,8 @@ export function ModelsLineageTab(): JSX.Element {
interactive
nodesDraggable={nodesDraggable}
nodePositions={nodesDraggable ? nodePositions : undefined}
- nodeOpenUrl={nodesDraggable ? lineageNodeUrl : undefined}
+ nodeOpenUrl={lineageNodeUrl}
+ selectable
onNodeDragStop={nodesDraggable ? (node, position) => nodeDragStopped(node.id, position) : undefined}
onResetNodePositions={nodesDraggable ? resetNodePositions : undefined}
showControls
@@ -178,7 +178,6 @@ export function ModelsLineageTab(): JSX.Element {
isSelected: selectedSearchResult?.id === node.id,
isRunning: node.last_run_status === 'Running',
})}
- onNodeClick={nodesDraggable ? undefined : (node) => router.actions.push(lineageNodeUrl(node))}
panels={<NodeTypeLegend collapsed={legendCollapsed} onToggleCollapse={toggleLegendCollapsed} />}
/>
</div>
diff --git a/products/data_modeling/frontend/lineage/lineageSelection.test.ts b/products/data_modeling/frontend/lineage/lineageSelection.test.ts
new file mode 100644
index 000000000000..4cdc214be446
--- /dev/null
+++ b/products/data_modeling/frontend/lineage/lineageSelection.test.ts
@@ -0,0 +1,26 @@
+import { DataModelingEdge } from '~/types'
+
+import { lineageCone } from './lineageSelection'
+
+const edge = (source_id: string, target_id: string): DataModelingEdge =>
+ ({ id: `${source_id}>${target_id}`, source_id, target_id }) as DataModelingEdge
+
+// events -> orders -> daily -> endpoint, with users joining orders and other branching off events
+const EDGES = [
+ edge('events', 'orders'),
+ edge('users', 'orders'),
+ edge('orders', 'daily'),
+ edge('daily', 'endpoint'),
+ edge('events', 'other'),
+ // Both ends are related to orders, but this edge bypasses orders.
+ edge('events', 'daily'),
+]
+
+describe('lineageCone', () => {
+ it('selects the full lineage without siblings or bypass edges', () => {
+ const cone = lineageCone(EDGES, 'orders')
+
+ expect([...cone.nodeIds].sort()).toEqual(['daily', 'endpoint', 'events', 'orders', 'users'])
+ expect([...cone.edgeIds].sort()).toEqual(['daily>endpoint', 'events>orders', 'orders>daily', 'users>orders'])
+ })
+})
diff --git a/products/data_modeling/frontend/lineage/lineageSelection.ts b/products/data_modeling/frontend/lineage/lineageSelection.ts
new file mode 100644
index 000000000000..ff5fac972454
--- /dev/null
+++ b/products/data_modeling/frontend/lineage/lineageSelection.ts
@@ -0,0 +1,26 @@
+import { DataModelingEdge } from '~/types'
+
+import { buildAdjacencyMaps, traverseLineage } from './lineageSearch'
+
+export interface LineageCone {
+ nodeIds: Set<string>
+ edgeIds: Set<string>
+}
+
+/** The nodes and edges that pass through the selected node in either direction. */
+export function lineageCone(edges: DataModelingEdge[], nodeId: string): LineageCone {
+ const maps = buildAdjacencyMaps(edges)
+ const upstream = traverseLineage(nodeId, maps, 'upstream')
+ const downstream = traverseLineage(nodeId, maps, 'downstream')
+ const edgeIds = new Set<string>()
+
+ for (const edge of edges) {
+ const onUpstreamPath = upstream.has(edge.source_id) && upstream.has(edge.target_id)
+ const onDownstreamPath = downstream.has(edge.source_id) && downstream.has(edge.target_id)
+ if (onUpstreamPath || onDownstreamPath) {
+ edgeIds.add(edge.id)
+ }
+ }
+
+ return { nodeIds: new Set([nodeId, ...upstream, ...downstream]), edgeIds }
+}