: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): add lineage search result navigator (#108501)
Jovan Sakovic0742f99db921
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 159a0cb06e89..c9a9a66083b1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6391,9 +6391,13 @@ snapshots:products-data-modeling-lineage-graph--full--light:hash: v1.k794b7964.3d2a0a0a6ff2a27f3f8d682857757695b61970b3bfdc3f50e7508c86257aa4ad.S_I2CjkAMi3HiNyo014ZRrZHZbcDaVTQwF4718lZNwsproducts-data-modeling-lineage-graph--search-focus--dark:- hash: v1.k794b7964.b4d9053ce873f58fd7242899886a9732c0daaa37eefe75fdf02b157608030db0.ZZPDrU7QcCWBEqceYc4pO5Xh6UHGMhyDXx_fN8UpsCg+ hash: v1.k794b7964.50fc53d09a95dbfa156c1bb0234cb4ae94f1edad3c531971a6d29fc6e644792b.CnYgYXb_RjjTDPN13751BGVZ03jgtmKYiwd6IWXzvoEproducts-data-modeling-lineage-graph--search-focus--light:- hash: v1.k794b7964.b740c4a0f8c1a657d2d87e3a2ba94082ccf74c65fe5a7fc52c1fa7804e3b900a.d2mXFF2Jwsu9Hjf3JVkojpMjZbV99slRc3Ol5S4418I+ hash: v1.k794b7964.3d11e7ae38507207bbe6cc4e4a2e836551851f548b320ba9e68434a7f28955e4.5xbCZPz04Wxs56vbST3OAyMzXApj7I5Mn-p1Iummm5s+ products-data-modeling-lineage-graph--selector-focus--dark:+ hash: v1.k794b7964.e44cc4197946a139484ad0c1c6accb027a2459a4479584b1dbb62113bd6d01c1.u4OtT961hGsah7VBvU4uOB6puqdbBHM04pryfC_KByQ+ products-data-modeling-lineage-graph--selector-focus--light:+ hash: v1.k794b7964.3d864c004ba10e4965d2dd21416e56c24ed0920a1947558f1637b4a4188c7f2d.Bq_kGJNOot-IwoTiPYugFocCo6kP5f8szxMmW38B4RYproducts-data-modeling-lineage-graph--single-node--dark:hash: v1.k794b7964.3a7800242792b8dd49d06a252b0ccf609de5be3bf5b077e28904ca2ef46b9150.3jN6spC1a4TJhjq6LOuaDGym92gQz9Xw2KUfy0Br-D8products-data-modeling-lineage-graph--single-node--light:diff --git a/frontend/src/lib/lemon-ui/LemonButton/LemonButton.tsx b/frontend/src/lib/lemon-ui/LemonButton/LemonButton.tsxindex 54a4ee49c128..7d432581d692 100644--- a/frontend/src/lib/lemon-ui/LemonButton/LemonButton.tsx+++ b/frontend/src/lib/lemon-ui/LemonButton/LemonButton.tsx@@ -32,6 +32,7 @@ export interface LemonButtonPropsBase| 'style'| 'role'| 'aria-haspopup'+ | 'aria-current'| 'aria-pressed'| 'aria-expanded'| 'aria-controls'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 42d6d4b95e8e..484bf05d4fde 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3170,6 +3170,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.434.14(@types/[email protected])([email protected])react:specifier: 18.3.1version: 18.3.1diff --git a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsxindex d2e1b77a6b4c..fd29030ec062 100644--- a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx+++ b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx@@ -61,6 +61,32 @@ const GRAPH_EDGES: DataModelingEdge[] = [mockEdge('e5', '4', '6'),]+// 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.+const VIEWPORT_SETTLE_MS = 10000++async function expectNodeCentered(canvasElement: HTMLElement, nodeId: string, message: string): Promise<void> {+ await waitFor(+ () => {+ const graph = canvasElement.querySelector<HTMLElement>('.react-flow')+ const node = graph?.querySelector<HTMLElement>(`.react-flow__node[data-id="${nodeId}"]`)+ if (!graph || !node) {+ throw new Error(message)+ }+ const nodeBounds = node.getBoundingClientRect()+ const graphBounds = graph.getBoundingClientRect()+ if (+ Math.abs(nodeBounds.x + nodeBounds.width / 2 - graphBounds.x - graphBounds.width / 2) > 5 ||+ Math.abs(nodeBounds.y + nodeBounds.height / 2 - graphBounds.y - graphBounds.height / 2) > 5+ ) {+ throw new Error(message)+ }+ },+ { timeout: VIEWPORT_SETTLE_MS }+ )+}+type Story = StoryObj<typeof LineageGraph>const meta: Meta<typeof LineageGraph> = {title: 'Products/Data modeling/Lineage graph',@@ -118,23 +144,64 @@ export const SearchFocus: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement)await canvas.findByText('monthly_report')- const graph = canvasElement.querySelector<HTMLElement>('.react-flow')!- const target = graph.querySelector<HTMLElement>('.react-flow__node[data-id="4"]')!const search = canvas.getByPlaceholderText('Search, or +name for upstream')- fireEvent.change(search, { target: { value: 'monthly_report' } })- await waitFor(() => {- const nodeBounds = target.getBoundingClientRect()- const graphBounds = graph.getBoundingClientRect()- if (- Math.abs(nodeBounds.x + nodeBounds.width / 2 - graphBounds.x - graphBounds.width / 2) > 5 ||- Math.abs(nodeBounds.y + nodeBounds.height / 2 - graphBounds.y - graphBounds.height / 2) > 5- ) {- throw new Error('The search match must be centered in the lineage viewport')- }- })+ fireEvent.change(search, { target: { value: 'monthly' } })+ await canvas.findByText('2 results')+ fireEvent.keyDown(search, { key: 'ArrowDown' })+ // The arrow key moves the selection through a kea listener, so the new result is only+ // selected on the next tick. Pressing Enter in the same tick would focus the old one.+ await canvas.findByText('monthly_recurring_revenue, result 2 of 2')+ fireEvent.keyDown(search, { key: 'Enter' })+ await expectNodeCentered(canvasElement, '6', 'The search match must be centered in the lineage viewport')+ const graph = canvasElement.querySelector<HTMLElement>('.react-flow')!if (graph.querySelectorAll('.react-flow__node').length !== GRAPH_NODES.length) {throw new Error('Plain search must keep the rest of the graph visible')}+ const previousResult = canvas.getByLabelText('Previous result')+ previousResult.focus()+ fireEvent.click(previousResult)+ if (document.activeElement !== search) {+ throw new Error('Cycling results must return focus to the search input')+ }+ },+}++export const SelectorFocus: Story = {+ 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)+ await canvas.findByText('revenue_summary')+ const search = canvas.getByPlaceholderText('Search, or +name for upstream')+ fireEvent.change(search, { target: { value: 'revenue_summary+' } })+ await canvas.findByText('4 models · downstream')+ fireEvent.keyDown(search, { key: 'ArrowDown' })+ await canvas.findByText('monthly_report, result 2 of 4')+ fireEvent.keyDown(search, { key: 'Enter' })+ if ((search as HTMLInputElement).selectionStart !== 'revenue_summary'.length) {+ throw new Error('A downstream selector must keep the caret before its trailing plus')+ }+ await waitFor(+ () => {+ const graph = canvasElement.querySelector<HTMLElement>('.react-flow')+ if (!graph || graph.querySelectorAll('.react-flow__node').length !== 4) {+ throw new Error('A downstream selector must keep only its lineage cone visible')+ }+ },+ { timeout: VIEWPORT_SETTLE_MS }+ )+ await expectNodeCentered(+ canvasElement,+ '4',+ 'The selected downstream model must be centered in the lineage viewport'+ )},}diff --git a/products/data_modeling/frontend/lineage/LineageGraph.tsx b/products/data_modeling/frontend/lineage/LineageGraph.tsxindex 25bbf00f707e..cee2eafb123f 100644--- a/products/data_modeling/frontend/lineage/LineageGraph.tsx+++ b/products/data_modeling/frontend/lineage/LineageGraph.tsx@@ -37,7 +37,8 @@ export interface LineageGraphProps {/** Enable zoom/pan. Off by default for inline previews */interactive?: booleanfitViewOptions?: FitViewOptions- focusNodeIds?: Set<string>+ focusNodeIds?: Set<string> | null+ searchFocusRequest?: { nodeId: string; requestId: number } | nullshowMinimap?: booleanminimapPosition?: PanelPositionshowControls?: boolean@@ -58,7 +59,7 @@ export interface LineageGraphProps {function LineageGraphContent(props: LineageGraphProps): JSX.Element {const { fitView, viewportInitialized } = useReactFlow()const { isDarkModeOn } = useValues(themeLogic)- const { currentNodeId, nodeState, nodeCallbacks, onNodeClick, focusNodeIds } = props+ const { currentNodeId, nodeState, nodeCallbacks, onNodeClick, focusNodeIds, searchFocusRequest } = propsconst { layout } = useValues(lineageGraphLogic({nodes: props.nodes,@@ -72,8 +73,8 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {if (!viewportInitialized || !focusNodeIds || !layout) {return}- // Keep the match readable when a search term identifies one or a few nodes. When the- // search is cleared, fit the whole graph again instead of leaving the viewport stranded.+ // 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.nodesif (nodes.length > 0) {void fitView({@@ -85,6 +86,16 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {}}, [fitView, viewportInitialized, focusNodeIds, layout])+ useEffect(() => {+ if (!viewportInitialized || !searchFocusRequest || !layout) {+ return+ }+ const node = layout.nodes.find((layoutNode) => layoutNode.id === searchFocusRequest.nodeId)+ if (node) {+ void fitView({ nodes: [node], padding: 0.2, duration: 400, maxZoom: 2 })+ }+ }, [fitView, viewportInitialized, searchFocusRequest, layout])+if (!layout) {return (<div className="flex items-center justify-center w-full h-full">diff --git a/products/data_modeling/frontend/lineage/LineageNode.tsx b/products/data_modeling/frontend/lineage/LineageNode.tsxindex 3c6189ff09b4..f603a77a3b2b 100644--- a/products/data_modeling/frontend/lineage/LineageNode.tsx+++ b/products/data_modeling/frontend/lineage/LineageNode.tsx@@ -49,6 +49,7 @@ export interface LineageNodeState {isRunning?: boolean/** Ringed when a search or type filter highlights this node */isHighlighted?: boolean+ isSelected?: boolean}export interface LineageNodeCallbacks {@@ -231,10 +232,20 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {<divclassName={clsx('relative rounded-lg border bg-bg-light cursor-pointer min-w-[180px]',- state.isRunning && 'border-warning ring-2 ring-warning/30 animate-pulse',- !state.isRunning && state.isHighlighted && 'border-link ring-2 ring-link/30',- !state.isRunning && !state.isHighlighted && !state.isCurrent && 'border-border',- node.lineage_issue && !state.isRunning && !state.isHighlighted && 'border-warning',+ 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-propsdiff --git a/products/data_modeling/frontend/lineage/LineageSearchResults.tsx b/products/data_modeling/frontend/lineage/LineageSearchResults.tsxnew file mode 100644index 000000000000..41e334179784--- /dev/null+++ b/products/data_modeling/frontend/lineage/LineageSearchResults.tsx@@ -0,0 +1,117 @@+import { useEffect, useRef } from 'react'++import { IconChevronRight } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { DataModelingNode } from '~/types'++import { LineageSearchMode } from './lineageSearch'+import { NodeTypeTag } from './NodeTypeTag'++const RENDERED_RESULT_LIMIT = 50++export interface LineageSearchResultsProps {+ results: DataModelingNode[]+ selectedResultId?: string+ anchorResultId?: string+ mode: LineageSearchMode+ onSelect: (nodeId: string) => void+ onPrevious: () => void+ onNext: () => void+}++export function LineageSearchResults({+ results,+ selectedResultId,+ anchorResultId,+ mode,+ onSelect,+ onPrevious,+ onNext,+}: LineageSearchResultsProps): JSX.Element {+ const selectedOptionRef = useRef<HTMLDivElement>(null)+ const selectedPosition = results.findIndex((node) => node.id === selectedResultId) + 1+ const resultCountLabel =+ mode === 'search'+ ? `${results.length} ${results.length === 1 ? 'result' : 'results'}`+ : `${results.length} ${results.length === 1 ? 'model' : 'models'} · ${+ mode === 'both' ? 'both directions' : mode+ }`++ // A one-letter term matches most of a large warehouse, and only about eight rows fit. Render a+ // window that holds the selection instead of one button per match, so arrow navigation still+ // reaches every result and the list never mounts thousands of buttons.+ const windowStart = Math.min(+ Math.max(0, selectedPosition - 1 - Math.floor(RENDERED_RESULT_LIMIT / 2)),+ Math.max(0, results.length - RENDERED_RESULT_LIMIT)+ )+ const renderedResults = results.slice(windowStart, windowStart + RENDERED_RESULT_LIMIT)++ useEffect(() => {+ selectedOptionRef.current?.scrollIntoView({ block: 'nearest' })+ }, [selectedResultId])++ return (+ <div className="absolute top-3 left-3 z-10 w-80 max-w-[calc(100%-1.5rem)] rounded border bg-bg-light shadow-lg">+ <div className="flex items-center justify-between gap-2 border-b px-2 py-1.5 text-xs text-secondary">+ <span>{resultCountLabel}</span>+ {results.length > 0 && (+ <div className="flex items-center gap-1">+ <span>+ {selectedPosition} of {results.length}+ </span>+ <LemonButton+ size="xsmall"+ noPadding+ icon={<IconChevronRight className="-rotate-90" />}+ aria-label="Previous result"+ tooltip="Previous result"+ onClick={onPrevious}+ data-attr="models-lineage-search-previous"+ />+ <LemonButton+ size="xsmall"+ noPadding+ icon={<IconChevronRight className="rotate-90" />}+ aria-label="Next result"+ tooltip="Next result"+ onClick={onNext}+ data-attr="models-lineage-search-next"+ />+ </div>+ )}+ </div>+ <div className="max-h-56 overflow-y-auto p-1">+ {results.length === 0 ? (+ <div className="px-2 py-3 text-sm text-secondary">No matching models</div>+ ) : (+ renderedResults.map((node) => (+ <div key={node.id} ref={node.id === selectedResultId ? selectedOptionRef : undefined}>+ <LemonButton+ fullWidth+ size="small"+ type="tertiary"+ active={node.id === selectedResultId}+ aria-current={node.id === selectedResultId}+ className="justify-start"+ onClick={() => onSelect(node.id)}+ data-attr="models-lineage-search-result"+ >+ <span className="flex min-w-0 items-center gap-2">+ <NodeTypeTag type={node.type} />+ <span className="truncate">{node.name}</span>+ {node.id === anchorResultId && (+ <span className="ml-auto shrink-0 text-xs text-secondary">Anchor</span>+ )}+ </span>+ </LemonButton>+ </div>+ ))+ )}+ </div>+ <div className="border-t px-2 py-1.5 text-[11px] text-secondary">+ ↑↓ to select · Enter to center · Esc to clear+ </div>+ </div>+ )+}diff --git a/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx b/products/data_modeling/frontend/lineage/ModelsLineageTab.tsxindex da72007ca929..e4a45b5adf46 100644--- a/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx+++ b/products/data_modeling/frontend/lineage/ModelsLineageTab.tsx@@ -1,5 +1,6 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'+import { useRef } from 'react'import { IconInfo } from '@posthog/icons'import { LemonButton, LemonInput, Tooltip } from '@posthog/lemon-ui'@@ -11,6 +12,7 @@ import { DataModelingNodeType } from '~/types'import { LineageGraph } from './LineageGraph'import { lineageNodeUrl } from './lineageNodeUrl'+import { LineageSearchResults } from './LineageSearchResults'import { LINEAGE_FILTER_TYPES, modelsLineageLogic } from './modelsLineageLogic'import { NODE_TYPE_TAG_SETTINGS } from './nodeStyles'import { NodeTypeLegend } from './NodeTypeLegend'@@ -22,6 +24,7 @@ const TYPE_OPTIONS = LINEAGE_FILTER_TYPES.map((type) => ({}))export function ModelsLineageTab(): JSX.Element {+ const searchInputRef = useRef<HTMLInputElement>(null)const {nodes,nodesLoading,@@ -30,12 +33,37 @@ export function ModelsLineageTab(): JSX.Element {typeFilter,legendCollapsed,highlightedNodeIds,+ parsedSearchTerm,+ lineageSearchAnchor,+ searchResults,+ showSearchResults,+ selectedSearchResult,+ searchResultAnnouncement,+ searchFocusRequest,focusNodeIds,visibleNodes,visibleEdges,isFiltered,} = useValues(modelsLineageLogic)- const { setSearchTerm, setTypeFilter, toggleLegendCollapsed, resetFilters } = useActions(modelsLineageLogic)+ const {+ setSearchTerm,+ setDebouncedSearchTerm,+ setTypeFilter,+ moveSearchResult,+ focusSearchResult,+ toggleLegendCollapsed,+ resetFilters,+ } = useActions(modelsLineageLogic)++ const focusSearchInput = (): void => {+ const input = searchInputRef.current+ input?.focus()+ const trimmedSearchTerm = searchTerm.trimEnd()+ if (input && trimmedSearchTerm.length > 1 && trimmedSearchTerm.endsWith('+')) {+ const trailingSelectorPosition = trimmedSearchTerm.length - 1+ input.setSelectionRange(trailingSelectorPosition, trailingSelectorPosition)+ }+ }return (<div className="flex flex-col gap-2">@@ -44,8 +72,30 @@ export function ModelsLineageTab(): JSX.Element {type="search"size="small"placeholder="Search, or +name for upstream"+ aria-label="Search models"+ inputRef={searchInputRef}value={searchTerm}onChange={setSearchTerm}+ onKeyDown={(event) => {+ if (+ showSearchResults &&+ searchResults.length > 0 &&+ (event.key === 'ArrowUp' || event.key === 'ArrowDown')+ ) {+ event.preventDefault()+ // Focus stays in the input here, so there is nothing to restore. Calling+ // focusSearchInput would move the caret away from where the user put it.+ moveSearchResult(event.key === 'ArrowUp' ? 'previous' : 'next', false)+ } else if (event.key === 'Enter' && selectedSearchResult) {+ event.preventDefault()+ focusSearchResult(selectedSearchResult.id, 'keyboard')+ focusSearchInput()+ } else if (event.key === 'Escape' && searchTerm) {+ event.preventDefault()+ setSearchTerm('')+ setDebouncedSearchTerm('')+ }+ }}className="w-72"data-attr="models-lineage-search"/>@@ -76,11 +126,35 @@ export function ModelsLineageTab(): JSX.Element {</>)}</div>- <div className="h-[calc(100vh-20rem)] min-h-[400px] w-full border rounded bg-bg-light overflow-hidden">+ <div className="relative h-[calc(100vh-20rem)] min-h-[400px] w-full border rounded bg-bg-light overflow-hidden">+ <span className="sr-only" aria-live="polite">+ {searchResultAnnouncement}+ </span>+ {showSearchResults && (+ <LineageSearchResults+ results={searchResults}+ selectedResultId={selectedSearchResult?.id}+ anchorResultId={lineageSearchAnchor?.id}+ mode={parsedSearchTerm.mode}+ onSelect={(nodeId) => {+ focusSearchResult(nodeId, 'click')+ focusSearchInput()+ }}+ onPrevious={() => {+ moveSearchResult('previous', true)+ focusSearchInput()+ }}+ onNext={() => {+ moveSearchResult('next', true)+ focusSearchInput()+ }}+ />+ )}<LineageGraphnodes={visibleNodes}edges={visibleEdges}focusNodeIds={focusNodeIds}+ searchFocusRequest={searchFocusRequest}variant="canvas"interactiveshowControls@@ -92,6 +166,7 @@ export function ModelsLineageTab(): JSX.Element {}nodeState={(node) => ({isHighlighted: highlightedNodeIds.has(node.id),+ isSelected: selectedSearchResult?.id === node.id,isRunning: node.last_run_status === 'Running',})}onNodeClick={(node) => router.actions.push(lineageNodeUrl(node))}diff --git a/products/data_modeling/frontend/lineage/lineageSearch.test.ts b/products/data_modeling/frontend/lineage/lineageSearch.test.tsindex 28d8a4667187..a5a6cd53fdd3 100644--- a/products/data_modeling/frontend/lineage/lineageSearch.test.ts+++ b/products/data_modeling/frontend/lineage/lineageSearch.test.ts@@ -6,6 +6,7 @@ import {edgesWithinNodes,matchNodesByName,nodeIdsForLineageSearch,+ orderedNodesForLineageSearch,parseLineageSearch,traverseLineage,} from './lineageSearch'@@ -50,6 +51,26 @@ describe('lineageSearch', () => {expect(matchNodesByName(nodes, 'orders')[0].name).toEqual('orders')})+ describe('orderedNodesForLineageSearch', () => {+ it('orders the anchor first, then models by distance and name', () => {+ const nodes = [node('root', 'root'), node('zeta', 'zeta'), node('alpha', 'alpha'), node('leaf', 'leaf')]+ const edges = [edge('root', 'zeta'), edge('root', 'alpha'), edge('alpha', 'leaf')]++ expect(+ orderedNodesForLineageSearch(nodes, edges, parseLineageSearch('root+'))?.map(({ name }) => name)+ ).toEqual(['root', 'alpha', 'zeta', 'leaf'])+ })++ it('keeps bidirectional walks from reaching siblings', () => {+ const nodes = ['events', 'orders', 'sessions'].map((name) => node(name, name))+ const edges = [edge('events', 'orders'), edge('events', 'sessions')]++ expect(+ orderedNodesForLineageSearch(nodes, edges, parseLineageSearch('+orders+'))?.map(({ name }) => name)+ ).toEqual(['orders', 'events'])+ })+ })+describe('nodeIdsForLineageSearch', () => {// EDGES is keyed by name, so the fixture names each node after its id.const nodes = ['events', 'orders', 'orders_daily', 'revenue_endpoint'].map((name) => node(name, name))diff --git a/products/data_modeling/frontend/lineage/lineageSearch.ts b/products/data_modeling/frontend/lineage/lineageSearch.tsindex c5c62dc312ae..7e98b7c87b89 100644--- a/products/data_modeling/frontend/lineage/lineageSearch.ts+++ b/products/data_modeling/frontend/lineage/lineageSearch.ts@@ -60,6 +60,22 @@ function walk(startId: string, adjacency: Map<string, string[]>, reached: Set<st}}+function walkDistances(startId: string, adjacency: Map<string, string[]>, distances: Map<string, number>): void {+ const queue = [startId]+ while (queue.length > 0) {+ const current = queue.shift() as string+ const distance = distances.get(current) ?? 0+ for (const neighbor of adjacency.get(current) ?? []) {+ const nextDistance = distance + 1+ const knownDistance = distances.get(neighbor)+ if (knownDistance === undefined || nextDistance < knownDistance) {+ distances.set(neighbor, nextDistance)+ queue.push(neighbor)+ }+ }+ }+}+/*** The nodes a selector reaches from an anchor.*@@ -83,30 +99,66 @@ export function matchNodesByName(nodes: DataModelingNode[], term: string): DataMif (!needle) {return []}- return nodes- .filter((node) => node.name.toLowerCase().includes(needle))- .sort((a, b) => {- const exact = Number(b.name.toLowerCase() === needle) - Number(a.name.toLowerCase() === needle)- return exact !== 0 ? exact : a.name.length - b.name.length- })+ // Lowercase each name once. The comparator runs O(n log n) times, so lowercasing inside it+ // allocates two strings per comparison, and a plain search matches on every keystroke.+ const matches: { node: DataModelingNode; lowerName: string }[] = []+ for (const node of nodes) {+ const lowerName = node.name.toLowerCase()+ if (lowerName.includes(needle)) {+ matches.push({ node, lowerName })+ }+ }+ matches.sort((a, b) => {+ const exact = Number(b.lowerName === needle) - Number(a.lowerName === needle)+ return exact !== 0 ? exact : a.node.name.length - b.node.name.length+ })+ return matches.map((match) => match.node)}/**- * The node ids a lineage selector keeps, or null when the term prunes nothing.+ * The ordered nodes for a lineage selector, or null when the term is a plain name search.*- * Null means "no lineage restriction" — a plain term matches names in place, so a single letter- * never empties the result. An unmatched anchor returns an empty set, since the term names nothing.+ * The anchor comes first. Related nodes follow by graph distance and then name. Upstream and+ * downstream walks stay separate, so a bidirectional selector does not reach sibling nodes.*/-export function nodeIdsForLineageSearch(+export function orderedNodesForLineageSearch(nodes: DataModelingNode[],edges: DataModelingEdge[],parsed: ParsedLineageSearch-): Set<string> | null {+): DataModelingNode[] | null {if (parsed.mode === 'search' || !parsed.term) {return null}const anchor = matchNodesByName(nodes, parsed.term)[0]- return anchor ? traverseLineage(anchor.id, buildAdjacencyMaps(edges), parsed.mode) : new Set<string>()+ if (!anchor) {+ return []+ }++ const maps = buildAdjacencyMaps(edges)+ const distances = new Map<string, number>([[anchor.id, 0]])+ if (parsed.mode === 'upstream' || parsed.mode === 'both') {+ walkDistances(anchor.id, maps.upstream, distances)+ }+ if (parsed.mode === 'downstream' || parsed.mode === 'both') {+ walkDistances(anchor.id, maps.downstream, distances)+ }++ return nodes+ .filter((node) => distances.has(node.id))+ .sort((a, b) => {+ const distanceDifference = (distances.get(a.id) ?? 0) - (distances.get(b.id) ?? 0)+ return distanceDifference || a.name.localeCompare(b.name)+ })+}++/** The node ids a lineage selector keeps, or null when a plain search does not prune the graph. */+export function nodeIdsForLineageSearch(+ nodes: DataModelingNode[],+ edges: DataModelingEdge[],+ parsed: ParsedLineageSearch+): Set<string> | null {+ const orderedNodes = orderedNodesForLineageSearch(nodes, edges, parsed)+ return orderedNodes === null ? null : new Set(orderedNodes.map((node) => node.id))}/** Keeps only edges whose endpoints both survived filtering, so no edge dangles. */diff --git a/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts b/products/data_modeling/frontend/lineage/modelsLineageLogic.test.tsindex 2e75d1703b24..93540c84f610 100644--- a/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts+++ b/products/data_modeling/frontend/lineage/modelsLineageLogic.test.ts@@ -37,35 +37,153 @@ describe('modelsLineageLogic', () => {logic.unmount()})- // A big DAG has many substring hits for a term; flying to all of them zooms back out to the- // unreadable overview. Every hit keeps its ring, but the viewport lands on the closest name only.- it.each([- ['leads', new Set(['1', '2', '3']), new Set(['1'])],- ['website_leads', new Set(['1', '2']), new Set(['1'])],- ])('rings every %p match but focuses the single closest name', async (term, highlighted, focused) => {+ it('ranks plain search results without moving the graph', async () => {await expectLogic(logic, () => {- logic.actions.setDebouncedSearchTerm(term)+ logic.actions.setSearchTerm('leads')+ logic.actions.setDebouncedSearchTerm('leads')}).toMatchValues({- highlightedNodeIds: highlighted,- focusNodeIds: focused,+ searchResults: [NODES[0], NODES[1], NODES[2]],+ showSearchResults: true,+ selectedSearchResult: NODES[0],+ highlightedNodeIds: new Set(['1', '2', '3']),+ focusNodeIds: null,+ searchFocusRequest: null,})})- it('skips a closest match the type filter hid, so the viewport still moves', async () => {+ it('filters search results by type and resets an explicit selection', async () => {+ logic.actions.setSearchTerm('leads')+ logic.actions.setDebouncedSearchTerm('leads')+ logic.actions.focusSearchResult('1', 'keyboard')+await expectLogic(logic, () => {logic.actions.setTypeFilter(['view'])- logic.actions.setDebouncedSearchTerm('website_leads')}).toMatchValues({- focusNodeIds: new Set(['2']),+ searchResults: [NODES[1], NODES[2]],+ selectedSearchResultId: null,+ selectedSearchResult: NODES[1],+ searchFocusRequest: null,+ })+ })++ it('changes and wraps the selected result without creating a focus request', async () => {+ logic.actions.setSearchTerm('leads')+ logic.actions.setDebouncedSearchTerm('leads')++ await expectLogic(logic, () => {+ logic.actions.moveSearchResult('previous', false)+ })+ .toFinishAllListeners()+ .toMatchValues({+ selectedSearchResultId: '3',+ selectedSearchResult: NODES[2],+ searchFocusRequest: null,+ })++ await expectLogic(logic, () => {+ logic.actions.moveSearchResult('next', false)+ })+ .toFinishAllListeners()+ .toMatchValues({+ selectedSearchResultId: '1',+ selectedSearchResult: NODES[0],+ searchFocusRequest: null,+ })+ })++ it('increments focus requests for selected results', async () => {+ logic.actions.setSearchTerm('leads')+ logic.actions.setDebouncedSearchTerm('leads')+ logic.actions.focusSearchResult('1', 'keyboard')++ await expectLogic(logic).toMatchValues({+ selectedSearchResultId: '1',+ searchFocusRequest: { nodeId: '1', requestId: 1 },+ })++ await expectLogic(logic, () => {+ logic.actions.focusSearchResult('2', 'click')+ }).toMatchValues({+ selectedSearchResultId: '2',+ searchFocusRequest: { nodeId: '2', requestId: 2 },+ })++ await expectLogic(logic, () => {+ logic.actions.selectSearchResult('3')+ }).toMatchValues({+ selectedSearchResultId: '3',+ searchFocusRequest: null,+ })+ })++ it('keeps filters cleared when a search debounce is pending', async () => {+ logic.actions.setSearchTerm('+website_leads')+ logic.actions.resetFilters()++ await expectLogic(logic).delay(300).toMatchValues({+ searchTerm: '',+ debouncedSearchTerm: '',+ })+ })++ it('shows an empty result panel for an unmatched plain search', async () => {+ await expectLogic(logic, () => {+ logic.actions.setSearchTerm('missing')+ logic.actions.setDebouncedSearchTerm('missing')+ }).toMatchValues({+ searchResults: [],+ showSearchResults: true,+ selectedSearchResult: null,+ focusNodeIds: null,})})- it('fits the whole surviving cone for a lineage selector instead of one node', async () => {+ it('lists a lineage selector by graph distance and keeps the full cone behavior', async () => {+ logic.actions.setSearchTerm('+website_leads')++ await expectLogic(logic).toMatchValues({+ searchResults: [],+ showSearchResults: false,+ })+await expectLogic(logic, () => {logic.actions.setDebouncedSearchTerm('+website_leads')}).toMatchValues({+ searchResults: [NODES[0], NODES[3]],+ showSearchResults: true,+ lineageSearchAnchor: NODES[0],+ selectedSearchResult: NODES[0],highlightedNodeIds: new Set(),focusNodeIds: new Set(['1', '4']),})})++ it('hides the result panel while the edges it needs are still loading', async () => {+ logic.actions.setSearchTerm('+website_leads')+ logic.actions.setDebouncedSearchTerm('+website_leads')++ await expectLogic(logic).toMatchValues({ showSearchResults: true })++ lineageDataLogic.actions.loadEdges()++ expectLogic(logic).toMatchValues({+ edgesLoading: true,+ showSearchResults: false,+ searchResultAnnouncement: '',+ })+ })++ it('cycles through and focuses models in a lineage selector', async () => {+ logic.actions.setSearchTerm('+website_leads')+ logic.actions.setDebouncedSearchTerm('+website_leads')++ await expectLogic(logic, () => {+ logic.actions.moveSearchResult('next', true)+ })+ .toFinishAllListeners()+ .toMatchValues({+ selectedSearchResult: NODES[3],+ searchFocusRequest: { nodeId: '4', requestId: 1 },+ })+ })})diff --git a/products/data_modeling/frontend/lineage/modelsLineageLogic.ts b/products/data_modeling/frontend/lineage/modelsLineageLogic.tsindex 245edc5201ea..bc28967cb679 100644--- a/products/data_modeling/frontend/lineage/modelsLineageLogic.ts+++ b/products/data_modeling/frontend/lineage/modelsLineageLogic.ts@@ -1,4 +1,5 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'import { DataModelingEdge, DataModelingNode, DataModelingNodeType } from '~/types'@@ -8,12 +9,19 @@ import {ParsedLineageSearch,edgesWithinNodes,matchNodesByName,- nodeIdsForLineageSearch,+ orderedNodesForLineageSearch,parseLineageSearch,} from './lineageSearch'export const LINEAGE_FILTER_TYPES: DataModelingNodeType[] = Object.values(NodeTypeEnumApi)+type SearchResultFocusTrigger = 'keyboard' | 'click' | 'previous' | 'next'++export interface SearchFocusRequest {+ nodeId: string+ requestId: number+}+export interface modelsLineageLogicValues {nodes: DataModelingNode[] // lineageDataLogicnodesLoading: boolean // lineageDataLogic@@ -23,9 +31,18 @@ export interface modelsLineageLogicValues {debouncedSearchTerm: stringtypeFilter: DataModelingNodeType[]legendCollapsed: boolean+ selectedSearchResultId: string | null+ searchFocusRequest: SearchFocusRequest | null+ parsedSearchTerm: ParsedLineageSearchparsedSearch: ParsedLineageSearch+ lineageSearchAnchor: DataModelingNode | null+ orderedLineageNodes: DataModelingNode[] | null+ searchResults: DataModelingNode[]+ showSearchResults: boolean+ selectedSearchResult: DataModelingNode | null+ searchResultAnnouncement: stringhighlightedNodeIds: Set<string>- focusNodeIds: Set<string>+ focusNodeIds: Set<string> | nullvisibleNodes: DataModelingNode[]visibleEdges: DataModelingEdge[]isFiltered: boolean@@ -35,6 +52,21 @@ export interface modelsLineageLogicActions {setSearchTerm: (searchTerm: string) => { searchTerm: string }setDebouncedSearchTerm: (searchTerm: string) => { searchTerm: string }setTypeFilter: (typeFilter: DataModelingNodeType[]) => { typeFilter: DataModelingNodeType[] }+ selectSearchResult: (nodeId: string) => { nodeId: string }+ moveSearchResult: (+ direction: 'previous' | 'next',+ focus: boolean+ ) => {+ direction: 'previous' | 'next'+ focus: boolean+ }+ focusSearchResult: (+ nodeId: string,+ trigger: SearchResultFocusTrigger+ ) => {+ nodeId: string+ trigger: SearchResultFocusTrigger+ }toggleLegendCollapsed: () => Record<string, never>resetFilters: () => Record<string, never>}@@ -50,6 +82,9 @@ export const modelsLineageLogic = kea<modelsLineageLogicType>([setSearchTerm: (searchTerm: string) => ({ searchTerm }),setDebouncedSearchTerm: (searchTerm: string) => ({ searchTerm }),setTypeFilter: (typeFilter: DataModelingNodeType[]) => ({ typeFilter }),+ selectSearchResult: (nodeId: string) => ({ nodeId }),+ moveSearchResult: (direction: 'previous' | 'next', focus: boolean) => ({ direction, focus }),+ focusSearchResult: (nodeId: string, trigger: SearchResultFocusTrigger) => ({ nodeId, trigger }),toggleLegendCollapsed: true,resetFilters: true,}),@@ -81,41 +116,184 @@ export const modelsLineageLogic = kea<modelsLineageLogicType>([toggleLegendCollapsed: (collapsed) => !collapsed,},],+ selectedSearchResultId: [+ null as string | null,+ {+ selectSearchResult: (_, { nodeId }) => nodeId,+ focusSearchResult: (_, { nodeId }) => nodeId,+ setSearchTerm: () => null,+ setTypeFilter: () => null,+ resetFilters: () => null,+ },+ ],+ searchFocusRequest: [+ null as SearchFocusRequest | null,+ {+ focusSearchResult: (request, { nodeId }) => ({ nodeId, requestId: (request?.requestId ?? 0) + 1 }),+ selectSearchResult: () => null,+ setSearchTerm: () => null,+ setTypeFilter: () => null,+ resetFilters: () => null,+ },+ ],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({// Every keystroke would otherwise prune the graph and start a fresh ELK layout.setSearchTerm: async ({ searchTerm }, breakpoint) => {await breakpoint(250)actions.setDebouncedSearchTerm(searchTerm)},+ resetFilters: () => {+ // Cancel a pending search debounce before it can restore the cleared term.+ actions.setSearchTerm('')+ actions.setDebouncedSearchTerm('')+ },+ moveSearchResult: ({ direction, focus }) => {+ const results = values.searchResults+ if (results.length === 0) {+ return+ }+ const currentIndex = results.findIndex((node) => node.id === values.selectedSearchResult?.id)+ const offset = direction === 'next' ? 1 : -1+ const nextIndex = (currentIndex + offset + results.length) % results.length+ const nodeId = results[nextIndex].id+ if (focus) {+ actions.focusSearchResult(nodeId, direction)+ } else {+ actions.selectSearchResult(nodeId)+ }+ },+ focusSearchResult: ({ nodeId, trigger }) => {+ const resultPosition = values.searchResults.findIndex((node) => node.id === nodeId)+ if (resultPosition !== -1) {+ posthog.capture('models lineage search result focused', {+ result_count: values.searchResults.length,+ result_position: resultPosition + 1,+ search_mode: values.parsedSearchTerm.mode,+ trigger,+ })+ }+ },})),selectors({+ parsedSearchTerm: [(s) => [s.searchTerm], (searchTerm: string) => parseLineageSearch(searchTerm)],parsedSearch: [(s) => [s.debouncedSearchTerm], (searchTerm: string) => parseLineageSearch(searchTerm)],- // A plain term highlights matches in place. Only the `+` lineage selectors prune the canvas,- // so typing a single letter never empties the graph.- highlightedNodeIds: [- (s) => [s.nodes, s.parsedSearch],- (nodes: DataModelingNode[], parsedSearch: ParsedLineageSearch): Set<string> => {- if (parsedSearch.mode !== 'search') {- return new Set()+ lineageSearchAnchor: [+ (s) => [s.nodes, s.parsedSearchTerm],+ (nodes: DataModelingNode[], parsedSearchTerm: ParsedLineageSearch): DataModelingNode | null =>+ parsedSearchTerm.mode === 'search' ? null : (matchNodesByName(nodes, parsedSearchTerm.term)[0] ?? null),+ ],++ // Both the result list and the graph need the lineage cone. Walking it once here keeps the+ // adjacency maps and the BFS from being built twice for every settled selector search.+ orderedLineageNodes: [+ (s) => [s.nodes, s.edges, s.parsedSearch],+ (+ nodes: DataModelingNode[],+ edges: DataModelingEdge[],+ parsedSearch: ParsedLineageSearch+ ): DataModelingNode[] | null => orderedNodesForLineageSearch(nodes, edges, parsedSearch),+ ],++ // Plain name matching is cheap, so keep its results in step with typing. Lineage selectors+ // wait for the debounce because they prune and lay out the graph again.+ searchResults: [+ (s) => [+ s.nodes,+ s.typeFilter,+ s.parsedSearchTerm,+ s.searchTerm,+ s.debouncedSearchTerm,+ s.orderedLineageNodes,+ s.visibleNodes,+ ],+ (+ nodes: DataModelingNode[],+ typeFilter: DataModelingNodeType[],+ parsedSearchTerm: ParsedLineageSearch,+ searchTerm: string,+ debouncedSearchTerm: string,+ orderedLineageNodes: DataModelingNode[] | null,+ visibleNodes: DataModelingNode[]+ ): DataModelingNode[] => {+ if (parsedSearchTerm.mode === 'search') {+ const searchableNodes =+ typeFilter.length === LINEAGE_FILTER_TYPES.length+ ? nodes+ : nodes.filter((node) => typeFilter.includes(node.type))+ return matchNodesByName(searchableNodes, parsedSearchTerm.term)+ }+ if (searchTerm !== debouncedSearchTerm) {+ return []+ }+ const visibleNodeIds = new Set(visibleNodes.map((node) => node.id))+ return (orderedLineageNodes ?? []).filter((node) => visibleNodeIds.has(node.id))+ },+ ],++ showSearchResults: [+ (s) => [s.parsedSearchTerm, s.searchTerm, s.debouncedSearchTerm, s.nodesLoading, s.edgesLoading],+ (+ parsedSearchTerm: ParsedLineageSearch,+ searchTerm: string,+ debouncedSearchTerm: string,+ nodesLoading: boolean,+ edgesLoading: boolean+ ): boolean => {+ if (parsedSearchTerm.term.length === 0 || nodesLoading) {+ return false+ }+ // Nodes and edges load in parallel. Only the lineage selectors walk edges, so a+ // plain name search can list results while the edge pages are still arriving. A+ // selector that ran now would report an empty cone as a real answer.+ return parsedSearchTerm.mode === 'search' || (searchTerm === debouncedSearchTerm && !edgesLoading)+ },+ ],++ selectedSearchResult: [+ (s) => [s.searchResults, s.selectedSearchResultId],+ (searchResults: DataModelingNode[], selectedSearchResultId: string | null): DataModelingNode | null =>+ searchResults.find((node) => node.id === selectedSearchResultId) ?? searchResults[0] ?? null,+ ],++ // Read by a live region that stays mounted, so a screen reader announces the first search+ // too. A region inserted with its text already set is not announced.+ searchResultAnnouncement: [+ (s) => [s.showSearchResults, s.searchResults, s.selectedSearchResult],+ (+ showSearchResults: boolean,+ searchResults: DataModelingNode[],+ selectedSearchResult: DataModelingNode | null+ ): string => {+ if (!showSearchResults) {+ return ''}- return new Set(matchNodesByName(nodes, parsedSearch.term).map((node) => node.id))+ if (!selectedSearchResult) {+ return 'No matching models'+ }+ const position = searchResults.findIndex((node) => node.id === selectedSearchResult.id) + 1+ return `${selectedSearchResult.name}, result ${position} of ${searchResults.length}`},],+ highlightedNodeIds: [+ (s) => [s.searchResults, s.parsedSearchTerm],+ (searchResults: DataModelingNode[], parsedSearchTerm: ParsedLineageSearch): Set<string> =>+ parsedSearchTerm.mode === 'search' ? new Set(searchResults.map((node) => node.id)) : new Set(),+ ],+visibleNodes: [- (s) => [s.nodes, s.edges, s.parsedSearch, s.typeFilter],+ (s) => [s.nodes, s.orderedLineageNodes, s.typeFilter],(nodes: DataModelingNode[],- edges: DataModelingEdge[],- parsedSearch: ParsedLineageSearch,+ orderedLineageNodes: DataModelingNode[] | null,typeFilter: DataModelingNodeType[]): DataModelingNode[] => {let kept = nodes- const reached = nodeIdsForLineageSearch(nodes, edges, parsedSearch)- if (reached) {+ if (orderedLineageNodes) {+ const reached = new Set(orderedLineageNodes.map((node) => node.id))kept = kept.filter((node) => reached.has(node.id))}@@ -127,18 +305,11 @@ export const modelsLineageLogic = kea<modelsLineageLogicType>([},],- // The viewport flies here. A plain term matches by substring, so on a big DAG it hits many- // scattered nodes, and fitting all of them zooms back out to the unreadable overview. Fly to- // the single closest match instead, because the rest keep their ring and show in the minimap.- // Match within the visible nodes, since the canvas only lays out those: a closest name that- // the type filter hides would leave the graph nothing to fit and the viewport would not move.- // Lineage selectors have already pruned the graph, so there we fit the whole surviving cone.focusNodeIds: [(s) => [s.parsedSearch, s.visibleNodes],- (parsedSearch: ParsedLineageSearch, visibleNodes: DataModelingNode[]): Set<string> => {+ (parsedSearch: ParsedLineageSearch, visibleNodes: DataModelingNode[]): Set<string> | null => {if (parsedSearch.mode === 'search') {- const best = matchNodesByName(visibleNodes, parsedSearch.term)[0]- return best ? new Set([best.id]) : new Set()+ return parsedSearch.term ? null : new Set()}return new Set(visibleNodes.map((node) => node.id))},diff --git a/products/data_modeling/package.json b/products/data_modeling/package.jsonindex 75b95362ea65..300851762dbc 100644--- a/products/data_modeling/package.json+++ b/products/data_modeling/package.json@@ -8,7 +8,8 @@"kea": "catalog:","kea-forms": "catalog:","kea-loaders": "catalog:",- "kea-router": "catalog:"+ "kea-router": "catalog:",+ "posthog-js": "catalog:"},"devDependencies": {"@storybook/react": "catalog:",