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(mcp): render paths query results as a sankey in the mcp ui app (#104832)

Paul D'Ambra4b924ff1609a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b009ba5c2e1f..7e581d06e0ef 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -217,9 +217,9 @@ snapshots:
charts-sankeychart--left-aligned-with-values--light:
hash: v1.k794b7964.71b32f628496dd8801855184c3ea3d3f0b47312041f148137107b7a48632b21d.3AfY_JFLCbBv12AAbc_xFpoqjxTK4XIZoKQJD1nc-Gw
charts-sankeychart--narrow--dark:
- hash: v1.k794b7964.c0a92bc5346237079d7aa76591ef95866a0027554600de68d00488ec576ab34e.rae6pJ76-lo4OAFw2I21f4RwAfpkvPMce_DdY9MKzwQ
+ hash: v1.k794b7964.b2f0193be7c51e6f55e7971cd382edaa2aa2791e504e030a0158279767764f03.A48fC6kABWYb5bH8hKPUi-5GYX2I8zYoeyKzNS__FXE
charts-sankeychart--narrow--light:
- hash: v1.k794b7964.1f36bc77ab15bef2f717ba801cb66cb03cfe83d0deedffc0e69b0448302bb56c.1uAAAcF-jsEeS7JkUg0VbDHHQ1YZAdpwXiMG_8X9TRM
+ hash: v1.k794b7964.7b456eb24ee839014b47a23a7fc05b317e93e5d13d8fc2f88bbb61f47a94fb5e.w53BwKHfejMxdOlnCqXv_NxY4KDAzPjKliLhvMQ4LEc
charts-sankeychart--tool-call-journeys--dark:
hash: v1.k794b7964.e50f64b0a2556e240047944407ec800fb78ffc2ad3eca93219f235d64883327d.9_vvmCGYMQ1aMSvgEOizcAf1tRGe7r0-FwNnrD3cHMo
charts-sankeychart--tool-call-journeys--light:
@@ -6306,6 +6306,12 @@ snapshots:
hash: v1.k794b7964.f6b81da6dbf0a63ddb55f3fc72b96ac5f72716698f914d73edb124e8ea17b0d1.2FXYB8hKUiO_FXveQuHw5J4O8WTK5bzOeiwCE9MUT4Q
mcp-apps-lifecycle--stacked--light:
hash: v1.k794b7964.e1057e251338bfbf9c5d6931d0f1a826064ab0c29843b716cf517ed7e8ff7d4e.y37bYZBa7mXiNTF6Xi_o7FtpVTdWgQa-xkc2koc_YRE
+ mcp-apps-paths--empty--light:
+ hash: v1.k794b7964.77b9d91893c5eb208216101495bb726906a1ebd04d17d5dbe24d24f0f23db822.DiRsE3sG-mQA5IpcZUhKFbZbDZ7xlblqQ5AQWlcm1VA
+ mcp-apps-paths--single-transition--light:
+ hash: v1.k794b7964.1c39a0bd2e56c6ad3c840cb2f2c7ac82b7fede3695fb7e9c699cf2b8b5af46c1.C8mutFhNrCTIQqpcRgICk-DmD4T4ldKtT70DJJ6iGkI
+ mcp-apps-paths--store-journeys--light:
+ hash: v1.k794b7964.d1a80e7a42dbfba333e75311b06e72992c611130708899769647558c2f661887.2p7Ut-EFMO8QR2OcwN_evJC-e-NBfFbaU7PzlBOr-SE
mcp-apps-query-results--single-number--light:
hash: v1.k794b7964.b53e77f7c428fe5d86903e3bee082eb7c752f67fb3225c043229e4b713debe69.hhBuSmExHBpDioDG9Ij-4qfvVhG77IC5FNYierdlZq8
mcp-apps-query-results--table--light:
@@ -12456,6 +12462,10 @@ snapshots:
hash: v1.k794b7964.9549b853f80d754b9d6ccf17ab144d24218143200c90df7af687e184e7de5329.Er1_HM8avmrqmulj2hCLnkp98-HeuRvF5ed3j-_jS2A
scenes-app-mcp-analytics--intent-clustering--light:
hash: v1.k794b7964.82fd6a9108a34ff8808b23b9c1e9255dcbe4f38562bb9e99333877dd303c08b2.qjDLxTHFZT3vcTHmPeG35-orU88GSS277RR2DdXxBdw
+ scenes-app-mcp-analytics--intent-clustering-journey--dark:
+ hash: v1.k794b7964.dca69b2edf84d19bb67ce3e2cc1a216fe6a63e9a1a36d8edb233b1f8ca60fd47.DJ-_pBzuUihpltpNAimi3dx_FewI6FzyLNKdoMZAMH4
+ scenes-app-mcp-analytics--intent-clustering-journey--light:
+ hash: v1.k794b7964.ac0eec4da423308decb9fbbd3f220e099b0a0a54dec45784b68c3bea89e7ec4d.vT3XHi6hXU4CIW6_dGDW6ShwhxyN5i1G-w00_qLnx3k
scenes-app-mcp-analytics--sessions--dark:
hash: v1.k794b7964.b9da0424c439b93ca4cfee035f623db248bf270c2f35d67fb149913d51357021.MHRBg5VvUtimcxoRkdmXRQmmxfzUts7dkMN-IIoczzI
scenes-app-mcp-analytics--sessions--light:
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
index 9b5e96ea4c95..152438a4b5ab 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
@@ -3,8 +3,10 @@ import { fireEvent, render, waitFor } from '@testing-library/react'
import type { ChartTheme } from '../../core/types'
import { getHogChartTooltip, renderHogChart } from '../../testing'
import { computeSankeyLayout } from './sankey-data'
-import type { SankeyLinkInput, SankeyNodeInput } from './sankey-data'
+import type { SankeyLinkInput, SankeyNodeDatum, SankeyNodeInput } from './sankey-data'
+import { labelsSharingLastGap, outsideLabelWidth, sankeyLabelBoxes } from './sankey-labels'
import { SankeyChart } from './SankeyChart'
+import { fitHeader } from './SankeyColumnLabels'
const THEME: ChartTheme = { colors: ['#1f77b4', '#ff7f0e', '#2ca02c'], backgroundColor: '#ffffff' }
@@ -50,6 +52,29 @@ describe('SankeyChart', () => {
expect(chart.canvas.getAttribute('aria-label')).toBe('Sankey chart with 3 nodes and 2 links')
})
+ it('drops the label of a thin node that would print over its larger neighbor', () => {
+ // Two thin nodes stacked in one column: their boxes are a pixel or two tall, so their label
+ // centers sit closer than a line of text. The larger flow keeps its label.
+ const { chart } = renderHogChart(
+ <SankeyChart
+ nodes={[
+ { id: 'start', label: 'Start' },
+ { id: 'a', label: 'Big' },
+ { id: 'b', label: 'Thin' },
+ { id: 'c', label: 'Thinner' },
+ ]}
+ links={[
+ { source: 'start', target: 'a', value: 400 },
+ { source: 'start', target: 'b', value: 2 },
+ { source: 'start', target: 'c', value: 1 },
+ ]}
+ theme={THEME}
+ config={{ nodePadding: 0 }}
+ />
+ )
+ expect(chart.sankeyNodeLabels()).toEqual(['Start', 'Big', 'Thin'])
+ })
+
it('shows the hovered node in the tooltip, reports it once, and fires onNodeClick for it', async () => {
const onNodeClick = jest.fn()
const onHoverChange = jest.fn()
@@ -210,7 +235,13 @@ describe('SankeyChart', () => {
broken: { links: [LINKS[0], { source: 'a', target: 'missing', value: 12 }] },
},
{ name: 'the node padding', broken: { config: { nodePadding: -1 } } },
- ])('recovers from an invalid graph when only $name is corrected', ({ broken }) => {
+ { name: 'a NaN pin', broken: { nodes: [{ ...NODES[0], column: NaN }, ...NODES.slice(1)] } },
+ {
+ name: 'a numeric-string pin',
+ broken: { nodes: [{ ...NODES[0], column: '0' as unknown as number }, ...NODES.slice(1)] },
+ corrected: { nodes: [{ ...NODES[0], column: 0 }, ...NODES.slice(1)] },
+ },
+ ])('recovers from an invalid graph when only $name is corrected', ({ broken, corrected }) => {
jest.spyOn(console, 'error').mockImplementation(() => {})
const onError = jest.fn()
const { container, rerender } = render(
@@ -219,7 +250,131 @@ describe('SankeyChart', () => {
expect(onError).toHaveBeenCalled()
expect(container.textContent).toContain('Something went wrong')
- rerender(<SankeyChart nodes={NODES} links={LINKS} theme={THEME} onError={onError} />)
+ rerender(<SankeyChart nodes={NODES} links={LINKS} theme={THEME} onError={onError} {...corrected} />)
expect(container.textContent).not.toContain('Something went wrong')
})
+
+ it('finds labels that face each other across the gap the last two columns share', () => {
+ const node = (id: string, column: number, y0: number): SankeyNodeDatum => ({
+ id,
+ label: id,
+ color: '#000',
+ index: 0,
+ column,
+ value: 1,
+ x0: 0,
+ x1: 0,
+ y0,
+ y1: y0 + 4,
+ })
+ const first = node('first', 0, 100)
+ const penultimate = node('penultimate', 1, 100)
+ const last = node('last', 2, 102)
+ const lastFarAway = node('lastFarAway', 2, 200)
+ expect(labelsSharingLastGap(new Set([first, penultimate, last, lastFarAway]), 3)).toEqual(
+ new Set([penultimate, last])
+ )
+ })
+
+ it('shows the node tooltip when the pointer is over its label, not the ribbon under it', async () => {
+ const { chart } = renderHogChart(<SankeyChart nodes={NODES} links={LINKS} theme={THEME} />, {
+ nativeTooltip: true,
+ })
+ // Right of the Start node, inside its label and over the Start -> Tool A ribbon.
+ const start = nodeCenter('start')
+ await waitFor(() => {
+ fireEvent.mouseMove(chart.element, { clientX: start.clientX + 17, clientY: start.clientY })
+ expect(getHogChartTooltip()?.textContent).toContain('Start')
+ })
+ expect(getHogChartTooltip()?.textContent).not.toContain('→')
+ })
+
+ it('places last-column labels outside the nodes when asked, and truncates headers to their span', () => {
+ const layout = computeSankeyLayout({
+ nodes: NODES,
+ links: LINKS,
+ plot: { plotLeft: 8, plotTop: 8, plotWidth: 600, plotHeight: 300 },
+ nodeWidth: 12,
+ nodePadding: 8,
+ nodeAlign: 'justify',
+ preserveNodeOrder: false,
+ colorForLabel: () => '#000',
+ resolveColor: (c) => c,
+ })
+ const options = { showValues: false, valueFormatter: String, outsideWidth: 120 }
+ const sideOfLast = (lastColumnLabels: 'inside' | 'outside'): string | undefined =>
+ sankeyLabelBoxes(layout, { ...options, lastColumnLabels }).find((box) => box.text === 'Completed')?.side
+ expect([sideOfLast('inside'), sideOfLast('outside')]).toEqual(['left', 'right'])
+
+ expect(fitHeader('Outcome', 1000)).toBe('Outcome')
+ expect(fitHeader('4th tool', 8)).toBe('4th…')
+ })
+
+ it('draws no label where a narrow chart leaves it no room', () => {
+ const layout = computeSankeyLayout({
+ nodes: NODES,
+ links: LINKS,
+ plot: { plotLeft: 8, plotTop: 8, plotWidth: 40, plotHeight: 300 },
+ nodeWidth: 12,
+ nodePadding: 8,
+ nodeAlign: 'justify',
+ preserveNodeOrder: false,
+ colorForLabel: () => '#000',
+ resolveColor: (c) => c,
+ })
+ const boxes = sankeyLabelBoxes(layout, {
+ showValues: false,
+ valueFormatter: String,
+ lastColumnLabels: 'inside',
+ outsideWidth: 0,
+ })
+ expect(boxes).toEqual([])
+ })
+
+ it.each([
+ { nodeAlign: 'left' as const, sizedBy: 'Completed' },
+ { nodeAlign: 'justify' as const, sizedBy: 'Left after the first tool' },
+ ])('sizes the outside margin by the sinks in the last column under $nodeAlign', ({ nodeAlign, sizedBy }) => {
+ const nodes: SankeyNodeInput[] = [...NODES, { id: 'early', label: 'Left after the first tool' }]
+ const links: SankeyLinkInput[] = [...LINKS, { source: 'start', target: 'early', value: 3 }]
+ const onlySink = outsideLabelWidth([{ id: 'only', label: sizedBy }], [], nodeAlign, false, String)
+ expect(outsideLabelWidth(nodes, links, nodeAlign, false, String)).toBe(onlySink)
+ })
+
+ it('keeps nodes and labels when the outside label room is wider than half the plot', () => {
+ const nodes: SankeyNodeInput[] = [
+ { id: 'start', label: 'Start' },
+ { id: 'done', label: 'Completed after a very long outcome name that needs the full margin' },
+ ]
+ // An 800px wrapper with a 700px left margin leaves a 92px plot, under the 160px label cap.
+ const { chart } = renderHogChart(
+ <SankeyChart
+ nodes={nodes}
+ links={[{ source: 'start', target: 'done', value: 5 }]}
+ theme={THEME}
+ config={{ lastColumnLabels: 'outside', margins: { left: 700 } }}
+ />
+ )
+ const labels = Array.from(
+ chart.element.querySelectorAll<HTMLElement>('[data-attr="hog-chart-sankey-node-label"]')
+ ).map((label) => label.textContent)
+ expect(labels).toEqual([expect.stringMatching(/^Start/), expect.stringMatching(/^Comp.*…/)])
+ })
+
+ it('keeps room for column headers when a consumer overrides the top margin', () => {
+ const { chart } = renderHogChart(
+ <SankeyChart
+ nodes={NODES}
+ links={LINKS}
+ theme={THEME}
+ config={{ columnLabels: ['Init', 'Tool', 'Outcome'], margins: { top: 0 } }}
+ />
+ )
+ // Start fills the plot height, so its label sits at the plot's vertical center: 18px of
+ // header room above a 400px wrapper with an 8px bottom margin.
+ const start = Array.from(
+ chart.element.querySelectorAll<HTMLElement>('[data-attr="hog-chart-sankey-node-label"]')
+ ).find((label) => label.textContent?.startsWith('Start'))
+ expect(start?.style.top).toBe(`${18 + (400 - 18 - 8) / 2}px`)
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
index 0de1b0df744c..4c449ad82f48 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
@@ -18,6 +18,8 @@ import { SankeyLayoutContext } from './sankey-context'
import type { SankeyLayoutContextValue } from './sankey-context'
import { computeSankeyLayout, defaultValueFormatter, hoverIndexToHit } from './sankey-data'
import type { SankeyChartLayout, SankeyLinkInput, SankeyNodeInput } from './sankey-data'
+import { outsideLabelWidth, sankeyLabelBoxes } from './sankey-labels'
+import type { SankeyLabelBox } from './sankey-labels'
import { SankeyColumnLabels } from './SankeyColumnLabels'
import { SankeyNodeLabels } from './SankeyNodeLabels'
import type { SankeyChartProps, SankeyTooltipContext } from './types'
@@ -41,8 +43,10 @@ function graphKey(
config: SankeyChartProps['config']
): string {
// Structured serialization: ids are free-form strings, so a delimiter inside one must not collide.
+ // JSON writes both NaN and a missing pin as null, so pins go in as strings to keep them apart.
+ // The type goes in too, so a rejected '1' and a corrected 1 do not share a key.
return JSON.stringify([
- nodes.map((node) => node.id),
+ nodes.map((node) => [node.id, typeof node.column, String(node.column)]),
links.map(({ source, target, value }) => [source, target, value]),
[config?.nodeWidth, config?.nodePadding, config?.nodeAlign, config?.preserveNodeOrder],
])
@@ -83,6 +87,7 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
preserveNodeOrder = false,
columnLabels,
showNodeLabels = true,
+ lastColumnLabels = 'inside',
showNodeValues = false,
linkOpacity: configuredLinkOpacity = DEFAULT_LINK_OPACITY,
valueFormatter = defaultValueFormatter,
@@ -95,15 +100,38 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
const showTooltip = tooltipConfig?.enabled !== false
const hasColumnLabels = !!columnLabels && columnLabels.length > 0
+ const outsideWidth = useMemo(
+ () =>
+ showNodeLabels && lastColumnLabels === 'outside'
+ ? outsideLabelWidth(nodes, links, nodeAlign, showNodeValues, valueFormatter)
+ : 0,
+ [showNodeLabels, lastColumnLabels, nodes, links, nodeAlign, showNodeValues, valueFormatter]
+ )
+
const margins = useMemo<ChartMargins>(() => {
- const computed = hasColumnLabels
- ? { ...BASE_MARGINS, top: BASE_MARGINS.top + COLUMN_LABEL_HEIGHT }
- : BASE_MARGINS
- return marginsOverride ? applyMarginOverride(computed, marginsOverride) : computed
+ const applied = marginsOverride ? applyMarginOverride(BASE_MARGINS, marginsOverride) : BASE_MARGINS
+ // Column headers are sized for their room, so an override cannot take it away.
+ return { ...applied, top: applied.top + (hasColumnLabels ? COLUMN_LABEL_HEIGHT : 0) }
}, [hasColumnLabels, marginsOverride])
const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({ margins })
+ // `outside` labels take their room from the plot, capped at half of it, so a chart narrower
+ // than the labels still has nodes to draw and the labels truncate instead.
+ const outsideRoom = dimensions ? Math.min(outsideWidth, Math.floor(dimensions.plotWidth / 2)) : 0
+ const plot = useMemo(
+ () =>
+ dimensions
+ ? {
+ plotLeft: dimensions.plotLeft,
+ plotTop: dimensions.plotTop,
+ plotWidth: dimensions.plotWidth - outsideRoom,
+ plotHeight: dimensions.plotHeight,
+ }
+ : { plotLeft: 0, plotTop: 0, plotWidth: 0, plotHeight: 0 },
+ [dimensions, outsideRoom]
+ )
+
// `useChartTheme` rereads the CSS variables on any class change on <html> or <body>, and returns
// an equal palette in a new array. Keying on the values keeps that from rebuilding the layout,
// because a new layout clears the hover and its tooltip.
@@ -130,7 +158,7 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
computeSankeyLayout<NodeMeta, LinkMeta>({
nodes,
links,
- plot: dimensions ?? { plotLeft: 0, plotTop: 0, plotWidth: 0, plotHeight: 0 },
+ plot,
nodeWidth,
nodePadding,
nodeAlign,
@@ -138,7 +166,7 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
colorForLabel,
resolveColor: resolveCssColor,
}),
- [nodes, links, dimensions, nodeWidth, nodePadding, nodeAlign, preserveNodeOrder, colorForLabel]
+ [nodes, links, plot, nodeWidth, nodePadding, nodeAlign, preserveNodeOrder, colorForLabel]
)
// A controlled highlight paints on the static layer, so a change to it is a full repaint
@@ -158,8 +186,22 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
[dimensions, layout, linkOpacity, hasEmphasis]
)
+ const labelBoxes = useMemo<SankeyLabelBox[]>(
+ () =>
+ showNodeLabels
+ ? sankeyLabelBoxes(layout as SankeyChartLayout<unknown, unknown>, {
+ showValues: showNodeValues,
+ valueFormatter,
+ lastColumnLabels,
+ outsideWidth: outsideRoom,
+ })
+ : [],
+ [showNodeLabels, layout, showNodeValues, valueFormatter, lastColumnLabels, outsideRoom]
+ )
+
const { hoverIndex, hoverPosition, tooltipCtx, handlers } = useSankeyInteraction<NodeMeta, LinkMeta>({
layout,
+ labelBoxes,
canvasRef,
wrapperRef,
showTooltip,
@@ -231,7 +273,7 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
}
return {
scales,
- dimensions,
+ dimensions: { ...dimensions, plotWidth: plot.plotWidth },
labels: [],
series: [],
theme,
@@ -240,7 +282,7 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },
yGutters: [],
}
- }, [scales, dimensions, theme, canvasBounds])
+ }, [scales, dimensions, plot.plotWidth, theme, canvasBounds])
const sankeyValue = useMemo<SankeyLayoutContextValue<NodeMeta, LinkMeta>>(
() => ({ layout, canvasBounds }),
[layout, canvasBounds]
@@ -266,14 +308,10 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
handlers={handlers}
showOverlay={!!dimensions}
>
- {hasColumnLabels ? <SankeyColumnLabels labels={columnLabels} color={labelColor} /> : null}
- {showNodeLabels ? (
- <SankeyNodeLabels
- color={labelColor}
- showValues={showNodeValues}
- valueFormatter={valueFormatter}
- />
+ {hasColumnLabels ? (
+ <SankeyColumnLabels labels={columnLabels} color={labelColor} trailingRoom={outsideRoom} />
) : null}
+ {showNodeLabels ? <SankeyNodeLabels boxes={labelBoxes} color={labelColor} /> : null}
{children}
{tooltipCtx && showTooltip ? (
<Tooltip
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsx
index 5d3474ea6662..3cc73d9f3891 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsx
@@ -1,12 +1,42 @@
import React from 'react'
+import { FONT_FAMILY, ELLIPSIS, measureLabelWidth } from '../../utils/text-measure'
import { useSankeyLayout } from './sankey-context'
+import { TruncatedText } from './SankeyNodeLabels'
+
+const HEADER_FONT_SIZE = 10
+const HEADER_FONT = `${HEADER_FONT_SIZE}px ${FONT_FAMILY}`
+const HEADER_LETTER_SPACING = 0.04 * HEADER_FONT_SIZE
+/** Space kept between two neighboring headers. */
+const HEADER_GAP = 8
+
+function headerWidth(text: string): number {
+ return measureLabelWidth(text.toUpperCase(), HEADER_FONT) + text.length * HEADER_LETTER_SPACING
+}
+
+/** `label` shortened with an ellipsis to fit `maxWidth` as an uppercase, letter-spaced header. */
+export function fitHeader(label: string, maxWidth: number): string {
+ if (headerWidth(label) <= maxWidth) {
+ return label
+ }
+ let low = 0
+ let high = label.length - 1
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2)
+ if (headerWidth(label.slice(0, mid).trimEnd() + ELLIPSIS) <= maxWidth) {
+ low = mid
+ } else {
+ high = mid - 1
+ }
+ }
+ return low > 0 ? label.slice(0, low).trimEnd() + ELLIPSIS : ''
+}
const LABEL_STYLE_BASE: React.CSSProperties = {
position: 'absolute',
pointerEvents: 'none',
top: 0,
- fontSize: 10,
+ fontSize: HEADER_FONT_SIZE,
lineHeight: 1.2,
textTransform: 'uppercase',
letterSpacing: '0.04em',
@@ -16,14 +46,20 @@ const LABEL_STYLE_BASE: React.CSSProperties = {
export interface SankeyColumnLabelsProps {
labels: string[]
color: string
+ /** Free space right of the last column, such as the margin reserved for `outside` labels. */
+ trailingRoom?: number
}
/** Column headers over each node column. The first and last headers align to the outer node edge
* instead of centering, so they stay inside the chart. Extra labels beyond the column count are
* dropped, so a fixed stage list stays valid when the data has fewer stages. */
-export function SankeyColumnLabels({ labels, color }: SankeyColumnLabelsProps): React.ReactElement {
+export function SankeyColumnLabels({ labels, color, trailingRoom = 0 }: SankeyColumnLabelsProps): React.ReactElement {
const { layout } = useSankeyLayout()
const lastColumn = layout.columnCount - 1
+ // Each header owns the span halfway to its neighbors' node centers, so neighbors cannot run together.
+ const step = layout.columnCount > 1 ? layout.columnX[1] - layout.columnX[0] : Infinity
+ const middleWidth = step - HEADER_GAP
+ const edgeWidth = layout.nodeWidth / 2 + step / 2 - HEADER_GAP / 2
return (
<>
{Array.from({ length: layout.columnCount }, (_, column) => {
@@ -32,21 +68,31 @@ export function SankeyColumnLabels({ labels, color }: SankeyColumnLabelsProps):
if (!label || x === undefined) {
return null
}
+ let room = column === 0 || column === lastColumn ? edgeWidth : middleWidth
let placement: React.CSSProperties
- if (column === 0) {
+ if (column === lastColumn && trailingRoom > 0) {
+ // With room past the last column, the header starts over the nodes and runs into
+ // that room. A header too long for it ends at the room's far edge instead, so it
+ // also gets the free span left of the nodes.
+ const rightOfNodes = layout.nodeWidth + trailingRoom
+ const fitsRight = headerWidth(label) <= rightOfNodes
+ room = fitsRight ? rightOfNodes : edgeWidth + trailingRoom
+ placement = fitsRight ? { left: x } : { right: `calc(100% - ${x + rightOfNodes}px)` }
+ } else if (column === 0) {
placement = { left: x }
} else if (column === lastColumn) {
placement = { right: `calc(100% - ${x + layout.nodeWidth}px)` }
} else {
placement = { left: x + layout.nodeWidth / 2, transform: 'translateX(-50%)' }
}
+ const shown = isFinite(room) ? fitHeader(label, room) : label
return (
<div
key={column}
data-attr="hog-chart-sankey-column-label"
style={{ ...LABEL_STYLE_BASE, ...placement, color }}
>
- {label}
+ <TruncatedText text={label} shown={shown} />
</div>
)
})}
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsx
index c6a59502d4ba..12d496b935c1 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsx
@@ -1,11 +1,7 @@
import React from 'react'
-import { FONT_FAMILY, truncateToWidth } from '../../utils/text-measure'
-import { useSankeyLayout } from './sankey-context'
-
-const LABEL_FONT_SIZE = 11
-const LABEL_FONT = `${LABEL_FONT_SIZE}px ${FONT_FAMILY}`
-const LABEL_GAP = 6
+import { LABEL_FONT_SIZE } from './sankey-labels'
+import type { SankeyLabelBox } from './sankey-labels'
const LABEL_STYLE_BASE: React.CSSProperties = {
position: 'absolute',
@@ -16,38 +12,42 @@ const LABEL_STYLE_BASE: React.CSSProperties = {
transform: 'translateY(-50%)',
}
+export function TruncatedText({ text, shown }: { text: string; shown: string }): React.ReactElement {
+ if (shown === text) {
+ return <>{text}</>
+ }
+ return (
+ <>
+ <span aria-hidden="true">{shown}</span>
+ <span className="sr-only">{text}</span>
+ </>
+ )
+}
+
export interface SankeyNodeLabelsProps {
+ boxes: SankeyLabelBox[]
color: string
- showValues: boolean
- valueFormatter: (value: number) => string
}
-/** One label per node, to the right of it; the last column's labels sit to its left so they stay
- * inside the plot. Labels truncate to the free space before the next column. */
-export function SankeyNodeLabels({ color, showValues, valueFormatter }: SankeyNodeLabelsProps): React.ReactElement {
- const { layout } = useSankeyLayout()
- const occupiedColumns = layout.columnX.filter((x): x is number => Number.isFinite(x))
- const gap = occupiedColumns.length > 1 ? occupiedColumns[1] - occupiedColumns[0] - layout.nodeWidth : Infinity
- const maxWidth = Math.max(0, gap - LABEL_GAP * 2)
-
+/** Draws the labels `sankeyLabelBoxes` placed. The chart's hit test reads the same boxes, so the
+ * pointer passes through a label to the chart and hovering it shows its node's tooltip. */
+export function SankeyNodeLabels({ boxes, color }: SankeyNodeLabelsProps): React.ReactElement {
return (
<>
- {layout.nodes.map((node) => {
- const text = showValues ? `${node.label} ${valueFormatter(node.value)}` : node.label
- const last = node.column === layout.columnCount - 1 && layout.columnCount > 1
- const shown = truncateToWidth(text, maxWidth, LABEL_FONT)
- const style: React.CSSProperties = {
- ...LABEL_STYLE_BASE,
- color,
- top: (node.y0 + node.y1) / 2,
- ...(last ? { right: `calc(100% - ${node.x0 - LABEL_GAP}px)` } : { left: node.x1 + LABEL_GAP }),
- }
- return (
- <div key={node.id} data-attr="hog-chart-sankey-node-label" title={text} style={style}>
- {shown}
- </div>
- )
- })}
+ {boxes.map((box) => (
+ <div
+ key={box.index}
+ data-attr="hog-chart-sankey-node-label"
+ style={{
+ ...LABEL_STYLE_BASE,
+ color,
+ top: (box.y0 + box.y1) / 2,
+ ...(box.side === 'right' ? { left: box.x0 } : { right: `calc(100% - ${box.x1}px)` }),
+ }}
+ >
+ <TruncatedText text={box.text} shown={box.shown} />
+ </div>
+ ))}
</>
)
}
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.test.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.test.ts
index d02402262a7a..5cdae24fd194 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.test.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.test.ts
@@ -1,4 +1,4 @@
-import { bezierX, bezierY, computeSankeyLayout, sankeyHitAt } from './sankey-data'
+import { MAX_SANKEY_COLUMN, bezierX, bezierY, computeSankeyLayout, sankeyHitAt } from './sankey-data'
import type { ComputeSankeyLayoutOptions, SankeyLinkInput, SankeyNodeInput } from './sankey-data'
const PLOT = { plotLeft: 0, plotTop: 0, plotWidth: 600, plotHeight: 300 }
@@ -61,6 +61,65 @@ describe('computeSankeyLayout', () => {
expect([columnOf('right', 'start'), columnOf('right', 'a'), columnOf('right', 'ended')]).toEqual([0, 1, 2])
})
+ it('pins a node to its own column and widens the graph to fit it', () => {
+ // A late stage with no link from the earlier stages: depth alone would put `late` in the
+ // first column, and the graph would have three columns instead of five.
+ const nodes: SankeyNodeInput[] = [...NODES, { id: 'late', column: 3 }, { id: 'last', column: 4 }]
+ const links: SankeyLinkInput[] = [...LINKS, { source: 'late', target: 'last', value: 2 }]
+ const layout = layoutOf({ nodes, links, nodeAlign: 'left' })
+ const columnOf = (id: string): number | undefined => layout.nodes.find((n) => n.id === id)?.column
+ expect([columnOf('start'), columnOf('done'), columnOf('late'), columnOf('last')]).toEqual([0, 2, 3, 4])
+ expect(layout.columnCount).toBe(5)
+ })
+
+ it('lays out a pinned graph with an empty column between the pins', () => {
+ // Only two nodes, pinned three columns apart with nothing to naturally fill the columns
+ // between them: the graph must not crash spacing out a column with zero nodes in it.
+ const nodes: SankeyNodeInput[] = [
+ { id: 'x', column: 0 },
+ { id: 'y', column: 3 },
+ ]
+ const links: SankeyLinkInput[] = [{ source: 'x', target: 'y', value: 5 }]
+ expect(() => layoutOf({ nodes, links, nodeAlign: 'left' })).not.toThrow()
+ const layout = layoutOf({ nodes, links, nodeAlign: 'left' })
+ const columnOf = (id: string): number | undefined => layout.nodes.find((n) => n.id === id)?.column
+ expect([columnOf('x'), columnOf('y')]).toEqual([0, 3])
+ expect(layout.columnCount).toBe(4)
+ // Headers over the empty columns need an x too, evenly spaced between the pinned ones.
+ expect(layout.columnX).toEqual([0, 590 / 3, (2 * 590) / 3, 590])
+ })
+
+ it('spaces column headers like the nodes when the last column the engine allots is empty', () => {
+ // The unpinned chain is five deep, but `b` is pinned back to column 2, so column 4 holds no node.
+ const nodes: SankeyNodeInput[] = [
+ { id: 'a', column: 0 },
+ { id: 'u1' },
+ { id: 'u2' },
+ { id: 'u3' },
+ { id: 'b', column: 2 },
+ ]
+ const links: SankeyLinkInput[] = [
+ { source: 'a', target: 'u1', value: 5 },
+ { source: 'u1', target: 'u2', value: 5 },
+ { source: 'u2', target: 'u3', value: 5 },
+ { source: 'u3', target: 'b', value: 5 },
+ ]
+ const layout = layoutOf({ nodes, links, nodeAlign: 'left' })
+ expect(layout.columnCount).toBe(5)
+ expect(layout.nodes.map((node) => layout.columnX[node.column])).toEqual(layout.nodes.map((node) => node.x0))
+ })
+
+ it.each([MAX_SANKEY_COLUMN + 1, -1, 1.5, NaN])('rejects a pin of %p instead of moving the node', (column) => {
+ const nodes: SankeyNodeInput[] = [
+ { id: 'x', column: 0 },
+ { id: 'y', column },
+ ]
+ const links: SankeyLinkInput[] = [{ source: 'x', target: 'y', value: 5 }]
+ expect(() => layoutOf({ nodes, links, nodeAlign: 'left' })).toThrow('needs a whole column')
+ const unsized = { plotLeft: 0, plotTop: 0, plotWidth: 0, plotHeight: 0 }
+ expect(() => layoutOf({ nodes, links, nodeAlign: 'left', plot: unsized })).toThrow('needs a whole column')
+ })
+
it('resolves node colors by label and defaults link color to the source node', () => {
const layout = layoutOf({
nodes: [...NODES.slice(0, 3), { id: 'done', label: 'Completed', color: 'var(--success)' }],
@@ -84,6 +143,19 @@ describe('computeSankeyLayout', () => {
expect(dense.nodeWidth).toBe(10)
})
+ it('caps node width by the furthest pin when pins add columns past the longest path', () => {
+ const pinned = layoutOf({
+ nodes: [
+ { id: 'x', column: 0 },
+ { id: 'y', column: 99 },
+ ],
+ links: [{ source: 'x', target: 'y', value: 1 }],
+ nodeAlign: 'left',
+ })
+ expect(pinned.columnCount).toBe(100)
+ expect(pinned.nodeWidth).toBeCloseTo(600 / 100)
+ })
+
it('returns an empty layout without links and throws on a link to a missing node', () => {
expect(layoutOf({ links: [] }).nodes).toHaveLength(0)
expect(() => layoutOf({ links: [{ source: 'start', target: 'nope', value: 1 }] })).toThrow(
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts
index 5477b70e8aac..a381d5822d1a 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts
@@ -13,6 +13,8 @@ export interface SankeyNodeInput<Meta = unknown> {
color?: string
/** Consumer data handed back through tooltips and click handlers. */
meta?: Meta
+ /** Pin the node to this zero-based column. See `column` in docs/chart-types.md for the rules. */
+ column?: number
}
/** A directed flow from `source` to `target` (both node ids). The graph must be acyclic. */
@@ -97,6 +99,7 @@ interface LayoutNodeProps {
label: string
color: string
meta?: unknown
+ pinnedColumn?: number
[key: string]: unknown
}
@@ -109,6 +112,9 @@ interface LayoutLinkProps {
[key: string]: unknown
}
+/** The layout allocates every column up to the highest pin, so one stray pin must not size it. */
+export const MAX_SANKEY_COLUMN = 1000
+
const ALIGNMENTS = {
left: sankeyLeft,
right: sankeyRight,
@@ -129,12 +135,27 @@ export const EMPTY_SANKEY_LAYOUT: SankeyChartLayout<never> = {
nodeWidth: 0,
}
+/** Columns the layout will use: the longest path, or more when a pin reaches further right. */
+function columnCountOf(nodes: readonly SankeyNodeInput<unknown>[], links: readonly SankeyLinkInput<unknown>[]): number {
+ const pinned = nodes.reduce((max, node) => (node.column === undefined ? max : Math.max(max, node.column + 1)), 0)
+ return Math.max(longestPathLength(nodes, links), pinned)
+}
+
/** Nodes on the longest path through the graph, which is the column count the layout engine
- * gives it. A cycle stops the count early; the engine reports the cycle itself. */
+ * gives it. */
function longestPathLength(
nodes: readonly SankeyNodeInput<unknown>[],
links: readonly SankeyLinkInput<unknown>[]
): number {
+ return Math.max(1, ...nodeDepths(nodes, links).values())
+}
+
+/** Each node's 1-based depth: the nodes on the longest path that ends at it. A cycle stops the
+ * count early; the engine reports the cycle itself. */
+function nodeDepths(
+ nodes: readonly SankeyNodeInput<unknown>[],
+ links: readonly SankeyLinkInput<unknown>[]
+): Map<string, number> {
const incoming = new Map<string, number>(nodes.map((node) => [node.id, 0]))
const outgoing = new Map<string, string[]>()
for (const link of links) {
@@ -146,14 +167,12 @@ function longestPathLength(
outgoing.set(link.source, [link.target])
}
}
- const depth = new Map<string, number>()
+ const depth = new Map<string, number>(nodes.map((node) => [node.id, 1]))
const ready = nodes.filter((node) => incoming.get(node.id) === 0).map((node) => node.id)
- let longest = 1
for (let id = ready.pop(); id !== undefined; id = ready.pop()) {
const next = (depth.get(id) ?? 1) + 1
for (const target of outgoing.get(id) ?? []) {
depth.set(target, Math.max(depth.get(target) ?? 1, next))
- longest = Math.max(longest, next)
const remaining = (incoming.get(target) ?? 0) - 1
incoming.set(target, remaining)
if (remaining === 0) {
@@ -161,7 +180,33 @@ function longestPathLength(
}
}
}
- return longest
+ return depth
+}
+
+/** Ids of the flow-ending nodes the layout puts in its last column. Known before the layout runs,
+ * so the chart can size the right margin for their labels first. */
+export function lastColumnSinkIds(
+ nodes: readonly SankeyNodeInput<unknown>[],
+ links: readonly SankeyLinkInput<unknown>[],
+ nodeAlign: SankeyNodeAlign
+): Set<string> {
+ const hasOutgoing = new Set(links.map((link) => link.source))
+ const lastColumn = columnCountOf(nodes, links) - 1
+ const depths = nodeDepths(nodes, links)
+ // `justify` and `right` move every sink to the last column; `left` and `center` keep it at its depth.
+ const sinksMoveLast = nodeAlign === 'justify' || nodeAlign === 'right'
+ const ids = new Set<string>()
+ for (const node of nodes) {
+ // A pin can hold a node with outgoing links in the last column, and its label sits there too.
+ if (node.column === undefined && hasOutgoing.has(node.id)) {
+ continue
+ }
+ const column = node.column ?? (sinksMoveLast ? lastColumn : (depths.get(node.id) ?? 1) - 1)
+ if (column === lastColumn) {
+ ids.add(node.id)
+ }
+ }
+ return ids
}
/** Lays the graph out inside `plot`. Pure: safe to call from a memo or a test. Throws when a link
@@ -179,15 +224,20 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
colorForLabel,
resolveColor,
}: ComputeSankeyLayoutOptions<NodeMeta, LinkMeta>): SankeyChartLayout<NodeMeta, LinkMeta> {
- if (nodes.length === 0 || links.length === 0 || plot.plotWidth <= 0 || plot.plotHeight <= 0) {
- return EMPTY_SANKEY_LAYOUT as SankeyChartLayout<NodeMeta, LinkMeta>
- }
-
+ // Validate before the empty-layout return, so a bad graph fails before the chart has a size.
const nodeIds = new Set<string>()
for (const node of nodes) {
if (nodeIds.has(node.id)) {
throw new Error(`duplicate Sankey node id: ${node.id}`)
}
+ if (
+ node.column !== undefined &&
+ !(Number.isInteger(node.column) && node.column >= 0 && node.column <= MAX_SANKEY_COLUMN)
+ ) {
+ throw new Error(
+ `Sankey node ${node.id} needs a whole column from 0 to ${MAX_SANKEY_COLUMN}, got ${node.column}`
+ )
+ }
nodeIds.add(node.id)
}
for (const link of links) {
@@ -204,13 +254,25 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
if (!Number.isFinite(nodePadding) || nodePadding < 0) {
throw new Error(`Sankey nodePadding must be a finite number of 0 or more: ${nodePadding}`)
}
- const effectiveNodeWidth = Math.min(nodeWidth, plot.plotWidth / Math.max(1, longestPathLength(nodes, links) - 1))
+ if (nodes.length === 0 || links.length === 0 || plot.plotWidth <= 0 || plot.plotHeight <= 0) {
+ return EMPTY_SANKEY_LAYOUT as SankeyChartLayout<NodeMeta, LinkMeta>
+ }
+
+ const columnCount = columnCountOf(nodes, links)
+ const effectiveNodeWidth = Math.min(nodeWidth, plot.plotWidth / Math.max(1, columnCount))
// The engine mutates its inputs, so hand it fresh objects.
const engineNodes: LayoutNodeProps[] = nodes.map((node) => {
const label = node.label ?? node.id
- return { id: node.id, label, color: resolveColor(node.color || colorForLabel(label)), meta: node.meta }
+ return {
+ id: node.id,
+ label,
+ color: resolveColor(node.color || colorForLabel(label)),
+ meta: node.meta,
+ pinnedColumn: node.column,
+ }
})
+ const hasPinnedColumns = nodes.some((node) => node.column !== undefined)
const engineLinks: LayoutLinkProps[] = links.map((link) => ({
source: link.source,
target: link.target,
@@ -222,6 +284,7 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
const graph = sankeyLayout<LayoutNodeProps, LayoutLinkProps>()
.nodeId((node) => node.id)
.nodeAlign(ALIGNMENTS[nodeAlign])
+ .nodeColumn(hasPinnedColumns ? (node) => node.pinnedColumn : null)
.nodeSort(preserveNodeOrder ? null : undefined)
.nodeWidth(effectiveNodeWidth)
.nodePadding(nodePadding)
@@ -265,9 +328,9 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
}
})
- const columnCount = graph.nodes.reduce((max, node) => Math.max(max, node.layer + 1), 0)
- // Mirrors the engine's column spacing, so a column with no node still gets a position.
- const columnStep = columnCount <= 1 ? 0 : (plot.plotWidth - effectiveNodeWidth) / (columnCount - 1)
+ // A pinned column can hold no node, so derive every column's x from the engine's spacing
+ // rather than from the nodes that happen to land in it, and headers never read a hole.
+ const columnStep = columnCount > 1 ? (plot.plotWidth - effectiveNodeWidth) / (columnCount - 1) : 0
const columnX = Array.from({ length: columnCount }, (_, column) => plot.plotLeft + column * columnStep)
// Zero-value links do not feed a node, so a node fed only by them still counts as a source.
@@ -283,6 +346,15 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
return { nodes: outNodes, links: outLinks, columnCount, columnX, total, nodeWidth: effectiveNodeWidth }
}
+/** The part of a drawn node label the hit test needs: its node's index and its box. */
+export interface SankeyLabelHitBox {
+ index: number
+ x0: number
+ x1: number
+ y0: number
+ y1: number
+}
+
export type SankeyHit = { kind: 'node'; index: number } | { kind: 'link'; index: number }
/** Resolves what sits under the cursor: a node box first, then the nearest ribbon whose thickness
@@ -290,7 +362,8 @@ export type SankeyHit = { kind: 'node'; index: number } | { kind: 'link'; index:
* at the horizontal midpoint), so the test follows the painted shape exactly. */
export function sankeyHitAt(
layout: SankeyChartLayout<unknown, unknown>,
- cursor: { x: number; y: number }
+ cursor: { x: number; y: number },
+ labels: readonly SankeyLabelHitBox[] = []
): SankeyHit | null {
for (let i = 0; i < layout.nodes.length; i++) {
const node = layout.nodes[i]
@@ -301,6 +374,12 @@ export function sankeyHitAt(
return { kind: 'node', index: i }
}
}
+ // A label stands for its node, so pointing at a truncated name shows the node's full tooltip.
+ for (const label of labels) {
+ if (cursor.x >= label.x0 && cursor.x <= label.x1 && cursor.y >= label.y0 && cursor.y <= label.y1) {
+ return { kind: 'node', index: label.index }
+ }
+ }
let best: { index: number; distance: number } | null = null
for (let i = 0; i < layout.links.length; i++) {
const link = layout.links[i]
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-labels.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-labels.ts
new file mode 100644
index 000000000000..835b8e7e2162
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-labels.ts
@@ -0,0 +1,172 @@
+import { FONT_FAMILY, measureLabelWidth, truncateToWidth } from '../../utils/text-measure'
+import { lastColumnSinkIds } from './sankey-data'
+import type {
+ SankeyChartLayout,
+ SankeyLinkInput,
+ SankeyNodeAlign,
+ SankeyNodeDatum,
+ SankeyNodeInput,
+} from './sankey-data'
+
+export const LABEL_FONT_SIZE = 11
+export const LABEL_FONT = `${LABEL_FONT_SIZE}px ${FONT_FAMILY}`
+export const LABEL_GAP = 6
+/** Vertical room one label needs; two label centers closer than this overlap. */
+export const LABEL_LINE_HEIGHT = LABEL_FONT_SIZE * 1.2
+/** Widest margin `lastColumnLabels: 'outside'` reserves, so long outcome names cannot squeeze the plot. */
+const MAX_OUTSIDE_LABEL_WIDTH = 160
+
+/** Where the last column's labels go: `inside` sits them left of the nodes, over the ribbons;
+ * `outside` sits them right of the nodes in a margin reserved for them. */
+export type SankeyLastColumnLabels = 'inside' | 'outside'
+
+/** A node label as drawn: its full and truncated text and the box it occupies, in chart pixels. */
+export interface SankeyLabelBox {
+ /** Index of the node in `layout.nodes`. */
+ index: number
+ text: string
+ shown: string
+ side: 'left' | 'right'
+ x0: number
+ x1: number
+ y0: number
+ y1: number
+}
+
+export interface SankeyLabelOptions {
+ showValues: boolean
+ valueFormatter: (value: number) => string
+ lastColumnLabels: SankeyLastColumnLabels
+ /** Room right of the last column for `outside` labels. */
+ outsideWidth: number
+}
+
+const centerY = (node: SankeyNodeDatum): number => (node.y0 + node.y1) / 2
+
+/** Nodes whose label fits without covering a neighbor's. Thin nodes stacked in one column would
+ * print on top of each other, so the larger flow keeps its label and the tooltip still names the
+ * rest. */
+export function labeledNodes(nodes: SankeyNodeDatum[]): Set<SankeyNodeDatum> {
+ const kept = new Set<SankeyNodeDatum>()
+ const byColumn = new Map<number, SankeyNodeDatum[]>()
+ for (const node of nodes) {
+ const column = byColumn.get(node.column)
+ if (column) {
+ column.push(node)
+ } else {
+ byColumn.set(node.column, [node])
+ }
+ }
+ for (const column of byColumn.values()) {
+ const placed: number[] = []
+ for (const node of [...column].sort((a, b) => b.value - a.value)) {
+ const y = centerY(node)
+ if (placed.every((other) => Math.abs(other - y) >= LABEL_LINE_HEIGHT)) {
+ placed.push(y)
+ kept.add(node)
+ }
+ }
+ }
+ return kept
+}
+
+/** Labels in the last two columns that share the gap between those columns at about the same
+ * height. The penultimate column's labels run right and the last column's run left, so each of
+ * these gets half the gap. */
+export function labelsSharingLastGap(shown: Set<SankeyNodeDatum>, columnCount: number): Set<SankeyNodeDatum> {
+ const crowded = new Set<SankeyNodeDatum>()
+ if (columnCount < 2) {
+ return crowded
+ }
+ const nodes = [...shown]
+ const left = nodes.filter((node) => node.column === columnCount - 2)
+ const right = nodes.filter((node) => node.column === columnCount - 1)
+ for (const a of left) {
+ for (const b of right) {
+ if (Math.abs(centerY(a) - centerY(b)) < LABEL_LINE_HEIGHT) {
+ crowded.add(a)
+ crowded.add(b)
+ }
+ }
+ }
+ return crowded
+}
+
+/** The box of every label the chart draws. Labels sit right of their node and truncate to the free
+ * space before the next column; the last column's labels sit inside, left of the nodes, or
+ * outside in the reserved margin. Rendering and hit testing both read these boxes, so hovering a
+ * label hovers its node. */
+export function sankeyLabelBoxes(
+ layout: SankeyChartLayout<unknown, unknown>,
+ { showValues, valueFormatter, lastColumnLabels, outsideWidth }: SankeyLabelOptions
+): SankeyLabelBox[] {
+ const columnGap = layout.columnX.length > 1 ? layout.columnX[1] - layout.columnX[0] - layout.nodeWidth : Infinity
+ const maxWidth = Math.max(0, columnGap - LABEL_GAP * 2)
+ const sharedMaxWidth = Math.max(0, (columnGap - LABEL_GAP * 3) / 2)
+ const shownNodes = labeledNodes(layout.nodes)
+ const crowded = lastColumnLabels === 'inside' ? labelsSharingLastGap(shownNodes, layout.columnCount) : new Set()
+ const lastColumn = layout.columnCount > 1 ? layout.columnCount - 1 : -1
+
+ const boxes: SankeyLabelBox[] = []
+ layout.nodes.forEach((node, index) => {
+ if (!shownNodes.has(node)) {
+ return
+ }
+ const text = showValues ? `${node.label} ${valueFormatter(node.value)}` : node.label
+ const inLastColumn = node.column === lastColumn
+ let room = crowded.has(node) ? sharedMaxWidth : maxWidth
+ if (inLastColumn && lastColumnLabels === 'outside') {
+ room = Math.max(0, outsideWidth - LABEL_GAP)
+ }
+ // A narrow chart can leave a label no room at all; drawing it would cover the next column.
+ if (room <= 0) {
+ return
+ }
+ const shown = isFinite(room) ? truncateToWidth(text, room, LABEL_FONT) : text
+ const width = measureLabelWidth(shown, LABEL_FONT)
+ const side = inLastColumn && lastColumnLabels === 'inside' ? 'left' : 'right'
+ const x0 = side === 'right' ? node.x1 + LABEL_GAP : node.x0 - LABEL_GAP - width
+ const y = centerY(node)
+ boxes.push({
+ index,
+ text,
+ shown,
+ side,
+ x0,
+ x1: x0 + width,
+ y0: y - LABEL_LINE_HEIGHT / 2,
+ y1: y + LABEL_LINE_HEIGHT / 2,
+ })
+ })
+ return boxes
+}
+
+/** Width to reserve right of the plot for `outside` labels: the widest last-column label, capped.
+ * Measured from the inputs because the margin must be known before the layout runs. */
+export function outsideLabelWidth(
+ nodes: readonly SankeyNodeInput<unknown>[],
+ links: readonly SankeyLinkInput<unknown>[],
+ nodeAlign: SankeyNodeAlign,
+ showValues: boolean,
+ valueFormatter: (value: number) => string
+): number {
+ const lastColumn = lastColumnSinkIds(nodes, links, nodeAlign)
+ const inflow = new Map<string, number>()
+ const outflow = new Map<string, number>()
+ for (const link of links) {
+ inflow.set(link.target, (inflow.get(link.target) ?? 0) + link.value)
+ outflow.set(link.source, (outflow.get(link.source) ?? 0) + link.value)
+ }
+ let widest = 0
+ for (const node of nodes) {
+ if (!lastColumn.has(node.id)) {
+ continue
+ }
+ const label = node.label ?? node.id
+ // The layout gives a node the larger of its inflow and outflow, and the label shows that value.
+ const value = Math.max(inflow.get(node.id) ?? 0, outflow.get(node.id) ?? 0)
+ const text = showValues ? `${label} ${valueFormatter(value)}` : label
+ widest = Math.max(widest, measureLabelWidth(text, LABEL_FONT))
+ }
+ return widest === 0 ? 0 : Math.min(MAX_OUTSIDE_LABEL_WIDTH, Math.ceil(widest) + LABEL_GAP)
+}
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.ts
index a1ab2335eee0..a041e185775c 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.ts
@@ -70,6 +70,11 @@ export interface SankeyLayout<N extends SankeyExtraProperties, L extends SankeyE
nodeAlign(): (node: SankeyNode<N, L>, n: number) => number
nodeAlign(nodeAlign: (node: SankeyNode<N, L>, n: number) => number): this
+ /** Pins a node to a column whatever its depth; `undefined` falls back to `nodeAlign`. A fractional
+ * pin rounds down. */
+ nodeColumn(): ((node: SankeyNode<N, L>) => number | undefined) | null
+ nodeColumn(nodeColumn: ((node: SankeyNode<N, L>) => number | undefined) | null): this
+
nodeWidth(): number
nodeWidth(width: number): this
@@ -206,6 +211,7 @@ export function sankeyLayout<
let id: (d: SankeyNode<N, L>) => string | number = (d) => d.index
let align: (node: SankeyNode<N, L>, n: number) => number = sankeyJustify
+ let column: ((node: SankeyNode<N, L>) => number | undefined) | null = null
let sort: ((a: SankeyNode<N, L>, b: SankeyNode<N, L>) => number) | null | undefined
let nodesFn: (graph: SankeyInputGraph) => SankeyNode<N, L>[] = (graph) => graph.nodes as SankeyNode<N, L>[]
let linksFn: (graph: SankeyInputGraph) => SankeyLink<N, L>[] = (graph) => graph.links as SankeyLink<N, L>[]
@@ -266,6 +272,18 @@ export function sankeyLayout<
return id
}
+ function nodeColumnAccessor(): ((node: SankeyNode<N, L>) => number | undefined) | null
+ function nodeColumnAccessor(fn: ((node: SankeyNode<N, L>) => number | undefined) | null): SankeyLayout<N, L>
+ function nodeColumnAccessor(
+ fn?: ((node: SankeyNode<N, L>) => number | undefined) | null
+ ): ((node: SankeyNode<N, L>) => number | undefined) | null | SankeyLayout<N, L> {
+ if (fn !== undefined) {
+ column = fn
+ return self
+ }
+ return column
+ }
+
function nodeAlignAccessor(): (node: SankeyNode<N, L>, n: number) => number
function nodeAlignAccessor(fn: (node: SankeyNode<N, L>, n: number) => number): SankeyLayout<N, L>
function nodeAlignAccessor(
@@ -348,6 +366,7 @@ export function sankeyLayout<
links: linksAccessor,
nodeId: nodeIdAccessor,
nodeAlign: nodeAlignAccessor,
+ nodeColumn: nodeColumnAccessor,
nodeSort: nodeSortAccessor,
nodeWidth: nodeWidthAccessor,
nodePadding: nodePaddingAccessor,
@@ -431,11 +450,17 @@ export function sankeyLayout<
}
function computeNodeLayers({ nodes: nodeList }: { nodes: SankeyNode<N, L>[] }): SankeyNode<N, L>[][] {
- const x = max(nodeList, (d) => d.depth)! + 1
+ // A non-finite pin (e.g. NaN from a caller's bad parse) would otherwise flow into `layer`/`x0`
+ // and silently drop the node from the render; treat it as unpinned instead.
+ const pinned = (node: SankeyNode<N, L>): number | undefined => {
+ const value = column?.(node)
+ return value !== undefined && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : undefined
+ }
+ const x = Math.max(max(nodeList, (d) => d.depth)!, max(nodeList, (d) => pinned(d) ?? 0)!) + 1
const kx = x <= 1 ? 0 : (x1 - x0 - dx) / (x - 1)
const columns = Array.from({ length: x }, () => [] as SankeyNode<N, L>[])
for (const node of nodeList) {
- const i = Math.max(0, Math.min(x - 1, Math.floor(align(node, x))))
+ const i = Math.max(0, Math.min(x - 1, Math.floor(pinned(node) ?? align(node, x))))
node.layer = i
node.x0 = x0 + i * kx
node.x1 = node.x0 + dx
@@ -540,6 +565,11 @@ export function sankeyLayout<
}
function resolveCollisions(nodeList: SankeyNode<N, L>[], alpha: number): void {
+ // A pinned column can sit between two others with nothing naturally landing in it, leaving
+ // it empty; there's nothing to space out.
+ if (nodeList.length === 0) {
+ return
+ }
const i = nodeList.length >> 1
const subject = nodeList[i]
resolveCollisionsBottomToTop(nodeList, subject.y0 - py, i - 1, alpha)
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
index 6a1497df1ef0..0de68c3fc491 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
@@ -2,6 +2,7 @@ import type React from 'react'
import type { ChartMargins, ChartTheme, TooltipContext } from '../../core/types'
import type { SankeyLinkDatum, SankeyLinkInput, SankeyNodeAlign, SankeyNodeDatum, SankeyNodeInput } from './sankey-data'
+import type { SankeyLastColumnLabels } from './sankey-labels'
export type SankeyTooltipHit<NodeMeta = unknown, LinkMeta = NodeMeta> =
| { kind: 'node'; node: SankeyNodeDatum<NodeMeta> }
@@ -36,6 +37,10 @@ export interface SankeyChartConfig {
columnLabels?: string[]
/** Defaults to true. */
showNodeLabels?: boolean
+ /** Where the last column's labels sit. `inside` (default) puts them left of the nodes, over the
+ * ribbons; `outside` puts them right of the nodes in a reserved margin, so names in the last
+ * column read in full on a narrow chart. */
+ lastColumnLabels?: SankeyLastColumnLabels
/** Append the node's value to its label. Defaults to false. */
showNodeValues?: boolean
/** Resting ribbon opacity, 0..1. Defaults to 0.4. */
@@ -49,7 +54,8 @@ export interface SankeyChartConfig {
* anchors it to the hovered node's right edge or the ribbon's midpoint. */
placement?: 'follow-data' | 'top' | 'cursor'
}
- /** Per-side margin overrides. Should be referentially stable. */
+ /** Per-side margin overrides. Should be referentially stable. Column headers add their room to
+ * the top margin, and `outside` labels to the right margin, on top of an override. */
margins?: Partial<ChartMargins>
}
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts b/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts
index e623b8320145..e849bccb6b24 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts
@@ -6,7 +6,7 @@ import { useTapTracking } from '../../core/hooks/useTapTracking'
import { useTooltipLifecycle } from '../../core/hooks/useTooltipLifecycle'
import type { Series, TooltipContext } from '../../core/types'
import { hitToHoverIndex, hoverIndexToHit, sankeyHitAt } from './sankey-data'
-import type { SankeyChartLayout, SankeyHit, SankeyLinkDatum, SankeyNodeDatum } from './sankey-data'
+import type { SankeyChartLayout, SankeyHit, SankeyLabelHitBox, SankeyLinkDatum, SankeyNodeDatum } from './sankey-data'
import type { SankeyTooltipContext, SankeyTooltipHit } from './types'
interface UseSankeyInteractionOptions<NodeMeta, LinkMeta> {
@@ -17,6 +17,8 @@ interface UseSankeyInteractionOptions<NodeMeta, LinkMeta> {
onNodeClick?: (node: SankeyNodeDatum<NodeMeta>) => void
onLinkClick?: (link: SankeyLinkDatum<NodeMeta, LinkMeta>) => void
onHoverChange?: (hit: SankeyTooltipHit<NodeMeta, LinkMeta> | null) => void
+ /** Drawn node labels; the pointer over one counts as over its node. */
+ labelBoxes?: readonly SankeyLabelHitBox[]
}
function hitKey(hit: SankeyHit | null): string | null {
@@ -88,9 +90,11 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
onNodeClick,
onLinkClick,
onHoverChange,
+ labelBoxes,
}: UseSankeyInteractionOptions<NodeMeta, LinkMeta>): UseSankeyInteractionResult<NodeMeta, LinkMeta> {
type Ctx = SankeyTooltipContext<NodeMeta, LinkMeta>
const layoutRef = useLatest(layout)
+ const labelBoxesRef = useLatest(labelBoxes)
const onHoverChangeRef = useLatest(onHoverChange)
// The last hit reported to the host, so a cursor sweep inside one ribbon reports it once.
const reportedHitRef = useRef<string | null>(null)
@@ -181,7 +185,7 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
}
const rect = e.currentTarget.getBoundingClientRect()
const cursor = { x: e.clientX - rect.left, y: e.clientY - rect.top }
- const hit = sankeyHitAt(current, cursor)
+ const hit = sankeyHitAt(current, cursor, labelBoxesRef.current)
if (!hit) {
clearTooltip()
reportHover(null)
@@ -189,7 +193,7 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
}
showHit(hit, cursor)
},
- [layoutRef, showHit, clearTooltip]
+ [layoutRef, labelBoxesRef, showHit, clearTooltip, reportHover]
)
const onMouseLeave = useCallback(() => {
@@ -214,9 +218,10 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
const current = layoutRef.current
const rect = e.currentTarget.getBoundingClientRect()
const cursor = { x: e.clientX - rect.left, y: e.clientY - rect.top }
- let hit = sankeyHitAt(current, cursor) ?? hoverIndexToHit(current, hoverIndexRef.current)
+ let hit =
+ sankeyHitAt(current, cursor, labelBoxesRef.current) ?? hoverIndexToHit(current, hoverIndexRef.current)
if (lastPointerTypeRef.current === 'touch') {
- hit = sankeyHitAt(current, cursor)
+ hit = sankeyHitAt(current, cursor, labelBoxesRef.current)
if (!hit) {
clearTooltip()
reportHover(null)
@@ -241,6 +246,7 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
},
[
layoutRef,
+ labelBoxesRef,
hoverIndexRef,
lastPointerTypeRef,
tapDownTooltipIndexRef,
diff --git a/packages/quill/packages/charts/src/docs/TESTING.md b/packages/quill/packages/charts/src/docs/TESTING.md
index 8d544337af93..0971b3ada92d 100644
--- a/packages/quill/packages/charts/src/docs/TESTING.md
+++ b/packages/quill/packages/charts/src/docs/TESTING.md
@@ -52,6 +52,8 @@ chart.anomalyPoints() // [{ element, color }, …] (TimeSeriesLineChart)
chart.annotationBadges() // HTMLElement[]
chart.legendItems() // [{ label, secondaryLabel }, …] legend rows in the render scope, empty when hidden
chart.clickLegendItem('A', { additive: true }) // click a legend row, additive toggles instead of isolating
+chart.sankeyNodeLabels() // ['/home', '/pricing', …] Sankey node labels in layout order, after overlap hiding
+chart.sankeyColumnLabels() // ['Step 1', 'Step 2', …] Sankey column headers, left to right
```
For interactions, use the module-level helpers:
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
index d4c7f7fd52f1..d9f0528c7d5e 100644
--- a/packages/quill/packages/charts/src/docs/chart-types.md
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -99,8 +99,15 @@ There is no `series` or `labels`.
`var(--…)` colors resolve inside the chart.
- `nodeAlign` decides where a flow that ends early sits: `justify` (default) moves terminal nodes to the last column; `left` keeps each node at its own depth, which reads right when columns are stages.
`preserveNodeOrder` keeps input order within a column instead of untangling ribbons.
-- `columnLabels` renders headers above each column and reserves room for them.
+ A node with `column` set is pinned there whatever its depth, and the graph grows to fit the highest pin; use it when the data names its own stage, so `columnLabels` stay truthful for flows that end early or start late.
+ Pin every node or none, because an unpinned node is placed by depth and ignores its neighbors' pins.
+ Pins must run forward along the links: a link whose target column is at or before its source's draws backwards, with no error.
+ A pin that is not a whole number from 0 to `MAX_SANKEY_COLUMN` throws.
+- `columnLabels` renders headers above each column and reserves room for them, added to any consumer `margins.top`; a header too wide for its column truncates.
Node labels are DOM overlays beside each node, truncated to the free space before the next column; the last column's labels sit to its left.
+ `lastColumnLabels: 'outside'` moves the last column's labels to the right of the nodes and reserves a margin for them (capped at 160px and at half the plot width), so names in that column read in full on a narrow chart. The margin counts only the nodes that land in the last column under `nodeAlign`, and it adds to a consumer `margins.right` rather than being replaced by it.
+ Hovering a label counts as hovering its node, so a truncated name shows in full in the tooltip.
+ A label that would print over a larger neighbor's label in the same column is dropped; the tooltip still names that node.
`showNodeValues` appends the node value.
- Hovering a node lifts its ribbons and dims the rest of the graph; hovering a ribbon lifts just that ribbon.
The default tooltip shows the node label or `source → target`, the value, and its share of `layout.total` (the summed value of source nodes with no incoming link).
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index d2c82a38475d..4d3de7377cbe 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -134,8 +134,10 @@ export type {
SankeyNodeDatum,
SankeyNodeInput,
} from './charts/SankeyChart/sankey-data'
+export { MAX_SANKEY_COLUMN } from './charts/SankeyChart/sankey-data'
export { useSankeyLayout } from './charts/SankeyChart/sankey-context'
export type { SankeyLayoutContextValue } from './charts/SankeyChart/sankey-context'
+export type { SankeyLastColumnLabels } from './charts/SankeyChart/sankey-labels'
// The layout engine on its own, for hosts that draw their own SVG (user paths).
export {
sankeyCenter,
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index cd876a12700d..3822ec975d1a 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -1015,3 +1015,16 @@ export const IntentClustering: Story = {
featureFlags: [FEATURE_FLAGS.MCP_ANALYTICS_INTENT_ROUTING],
},
}
+
+// The journey chart is the last section of a pane sized to the viewport, so the default 720px
+// snapshot ends above it. A taller viewport brings it into the snapshot.
+export const IntentClusteringJourney: Story = {
+ parameters: {
+ pageUrl: urls.mcpAnalyticsIntentClustering(),
+ featureFlags: [FEATURE_FLAGS.MCP_ANALYTICS_INTENT_ROUTING],
+ testOptions: {
+ viewport: { width: 1280, height: 1800 },
+ waitForSelector: '[data-attr=mcp-cluster-journey-sankey] [data-attr=hog-chart-sankey-node-label]',
+ },
+ },
+}
diff --git a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
index d1468a47a0dd..65b7c3381b8d 100644
--- a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
+++ b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx
@@ -29,6 +29,8 @@ const CHART_CONFIG: SankeyChartConfig = {
nodeAlign: 'left',
preserveNodeOrder: true,
linkOpacity: 0.45,
+ // Outcome names sit in their own margin, so Completed and Error read in full on a narrow panel.
+ lastColumnLabels: 'outside',
}
function nodeFill(kind: JourneyNodeKind, theme: ChartTheme): string {
diff --git a/products/product_analytics/frontend/insights/paths/pathUtils.ts b/products/product_analytics/frontend/insights/paths/pathUtils.ts
index 80541c1e027f..048ec84ccf51 100644
--- a/products/product_analytics/frontend/insights/paths/pathUtils.ts
+++ b/products/product_analytics/frontend/insights/paths/pathUtils.ts
@@ -11,6 +11,7 @@ import {
PATH_NODE_CARD_OVERLAP_GAP,
PATH_NODE_CARD_TOP_OFFSET,
} from './constants'
+import { parsePathNodeKey, pathOrigins, pathUrlLabel } from './pathsChartTransforms'
const PATH_NODE_CARD_TOP_ADJUSTMENTS = 33
@@ -48,7 +49,7 @@ export interface PathNodeData {
}
/** Path result keys carry the step as a `N_` prefix; the rest is the event or URL. */
-export const stripStepPrefix = (name: string): string => name.replace(/(^[0-9]+_)/, '')
+export const stripStepPrefix = (name: string): string => parsePathNodeKey(name).name
export function getForwardConnectedIndices(startNode: PathNodeData): {
nodeIndices: Set<number>
@@ -216,18 +217,7 @@ export function roundedRect(
}
export function pageUrl(d: PathNodeData, display?: boolean, showFullUrls?: boolean): string {
- const incomingUrls = d.targetLinks
- .map((l) => stripStepPrefix(l?.source?.name ?? ''))
- .filter((a) => {
- try {
- new URL(a)
- } catch {
- return false
- }
- return a
- })
- .map((a) => new URL(a))
- const incomingDomains = Array.from(new Set(incomingUrls.map((url) => url.origin)))
+ const incomingOrigins = pathOrigins(d.targetLinks.map((l) => stripStepPrefix(l?.source?.name ?? '')))
let name = stripStepPrefix(d.name)
@@ -235,16 +225,10 @@ export function pageUrl(d: PathNodeData, display?: boolean, showFullUrls?: boole
return name
}
- try {
- const url = new URL(name)
- name = incomingDomains.length !== 1 ? url.href.replace(/(^\w+:|^)\/\//, '') : url.pathname + url.search
- if (url.hash?.includes('/')) {
- name += url.hash
- }
+ const label = pathUrlLabel(name, incomingOrigins.size === 1)
+ if (label !== name) {
// Decode URL-encoded characters (e.g., %3C becomes <) to display path cleaning aliases correctly
- name = tryDecodeURIComponent(name)
- } catch {
- // discard if invalid url
+ name = tryDecodeURIComponent(label)
}
if (showFullUrls) {
diff --git a/products/product_analytics/frontend/insights/paths/pathsChartData.ts b/products/product_analytics/frontend/insights/paths/pathsChartData.ts
index ebc9975307be..8a51f48e2d3a 100644
--- a/products/product_analytics/frontend/insights/paths/pathsChartData.ts
+++ b/products/product_analytics/frontend/insights/paths/pathsChartData.ts
@@ -3,6 +3,7 @@ import type { SankeyChartLayout, SankeyLinkInput, SankeyNodeInput } from '@posth
import { FunnelPathsFilter, PathsFilter, PathsLink } from '~/queries/schema/schema-general'
import { FALLBACK_CANVAS_WIDTH } from './constants'
+import { buildPathsSankeyGraph } from './pathsChartTransforms'
import { PathNodeData, PathTargetLink, isSelectedPathEndpoint, stripStepPrefix } from './pathUtils'
import { Paths } from './types'
@@ -18,8 +19,8 @@ export interface PathsGraph {
links: SankeyLinkInput<PathsLink>[]
}
-/** Chart inputs for a paths result. Node ids are the result's `N_name` keys, which are unique per
- * step, so the same page at two steps is two nodes. */
+/** Chart inputs for a paths result, with the start or end point the filter selected in the accent
+ * color. */
export function buildPathsGraph(
paths: Paths,
pathsFilter: PathsFilter,
@@ -32,23 +33,17 @@ export function buildPathsGraph(
hasOutgoing.add(link.source)
hasIncoming.add(link.target)
}
- const nodes = paths.nodes.map((node): SankeyNodeInput => {
- const selected = isSelectedPathEndpoint(pathsFilter, funnelPathsFilter, {
- name: stripStepPrefix(node.name),
- isPathStart: !hasIncoming.has(node.name),
- isPathEnd: !hasOutgoing.has(node.name),
- })
- return { id: node.name, color: selected ? colors.selectedNode : colors.node }
+ const { nodes, links } = buildPathsSankeyGraph(paths.links, {
+ linkColor: colors.link,
+ nodeColor: (key) =>
+ isSelectedPathEndpoint(pathsFilter, funnelPathsFilter, {
+ name: stripStepPrefix(key),
+ isPathStart: !hasIncoming.has(key),
+ isPathEnd: !hasOutgoing.has(key),
+ })
+ ? colors.selectedNode
+ : colors.node,
})
- const links = paths.links.map(
- (link): SankeyLinkInput<PathsLink> => ({
- source: link.source,
- target: link.target,
- value: link.value,
- color: colors.link,
- meta: link,
- })
- )
return { nodes, links }
}
diff --git a/products/product_analytics/frontend/insights/paths/pathsChartTransforms.test.ts b/products/product_analytics/frontend/insights/paths/pathsChartTransforms.test.ts
new file mode 100644
index 000000000000..b947d4d6fcc4
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/pathsChartTransforms.test.ts
@@ -0,0 +1,35 @@
+import { buildPathsSankeyGraph, pathStartCount } from './pathsChartTransforms'
+
+describe('pathsChartTransforms', () => {
+ it('counts path starts from step 1 only, even when a later step has lost its incoming edge', () => {
+ // A truncated result can keep `2_/pricing -> 3_/signup` without the edge into `2_/pricing`.
+ const edges = [
+ { source: '1_/home', target: '2_/docs', value: 10 },
+ { source: '2_/pricing', target: '3_/signup', value: 12 },
+ ]
+ expect(pathStartCount(edges)).toBe(10)
+ })
+
+ it.each([
+ { pinStepsUpTo: 3, columns: [0, 2, 1], stepsPinned: true },
+ { pinStepsUpTo: 2, columns: [undefined, undefined, undefined], stepsPinned: false },
+ ])(
+ 'pins nodes to their steps only within $pinStepsUpTo steps, labels URLs by path on a single origin, and keeps event names whole',
+ ({ pinStepsUpTo, columns, stepsPinned }) => {
+ const graph = buildPathsSankeyGraph(
+ [
+ { source: '1_https://example.com/home', target: '3_https://example.com/#/app/settings', value: 4 },
+ { source: '1_https://example.com/home', target: '2_clicked: signup button', value: 2 },
+ ],
+ { labelUrls: true, pinStepsUpTo }
+ )
+ expect(graph.nodes.map(({ label }) => label)).toEqual([
+ '/home',
+ '/#/app/settings',
+ 'clicked: signup button',
+ ])
+ expect(graph.nodes.map(({ column }) => column)).toEqual(columns)
+ expect(graph).toMatchObject({ stepCount: 3, stepsPinned })
+ }
+ )
+})
diff --git a/products/product_analytics/frontend/insights/paths/pathsChartTransforms.ts b/products/product_analytics/frontend/insights/paths/pathsChartTransforms.ts
new file mode 100644
index 000000000000..1130d0a46a25
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/pathsChartTransforms.ts
@@ -0,0 +1,132 @@
+import { MAX_SANKEY_COLUMN } from '@posthog/quill-charts'
+import type { SankeyLinkInput, SankeyNodeInput } from '@posthog/quill-charts'
+
+// This module imports nothing from `~/` or `lib/`, so the MCP UI app bundle, which only resolves
+// `products/*` and `@posthog/*`, shares it with the paths insight.
+
+/** The fields of a paths result row that the insight and the MCP app both read. */
+export interface PathsEdge {
+ source: string
+ target: string
+ value?: number | null
+ average_conversion_time?: number | null
+}
+
+const STEP_PREFIX = /^(\d+)_/
+
+/** Node keys are `<step>_<name>` with the step counted from 1. A key without a step prefix is
+ * step 0 and keeps its whole text as the name. */
+export function parsePathNodeKey(key: string): { step: number; name: string } {
+ const match = key.match(STEP_PREFIX)
+ if (!match) {
+ return { step: 0, name: key }
+ }
+ return { step: Number(match[1]), name: key.slice(match[0].length) }
+}
+
+/** Every node key once, in the order the result first names it. */
+export function pathNodeKeys(edges: PathsEdge[]): string[] {
+ const keys = new Set<string>()
+ for (const edge of edges) {
+ keys.add(edge.source)
+ keys.add(edge.target)
+ }
+ return [...keys]
+}
+
+/** A page URL, or null. `new URL` also accepts any `word:` prefix, so an event named
+ * `clicked: signup` would otherwise lose its prefix as a pathless URL. */
+function parseUrl(value: string): URL | null {
+ try {
+ const url = new URL(value)
+ return url.protocol === 'http:' || url.protocol === 'https:' ? url : null
+ } catch {
+ return null
+ }
+}
+
+/** The origin of every URL among the node names, so a caller can tell if the paths leave one site. */
+export function pathOrigins(names: string[]): Set<string> {
+ const origins = new Set<string>()
+ for (const name of names) {
+ const url = parseUrl(name)
+ if (url) {
+ origins.add(url.origin)
+ }
+ }
+ return origins
+}
+
+/** A page URL as a short label: its path on a single origin, else its host and path. A hash stays
+ * when it looks like a route, so two steps that differ only there keep distinct labels. A name
+ * that is not a URL (an event name) comes back unchanged. */
+export function pathUrlLabel(name: string, singleOrigin: boolean): string {
+ const url = parseUrl(name)
+ if (!url) {
+ return name
+ }
+ const route = url.hash.includes('/') ? url.hash : ''
+ const path = `${url.pathname}${url.search}${route}`
+ return singleOrigin ? path || name : `${url.host}${path}`
+}
+
+/** Paths that begin at step 1: the flow out of that step. The query counts one path per person
+ * and session, so this is not a count of distinct people. Count it on the full result, because a
+ * truncated one drops the edges that show a later step is not a start. */
+export function pathStartCount(edges: PathsEdge[]): number {
+ return edges
+ .filter((edge) => parsePathNodeKey(edge.source).step === 1)
+ .reduce((sum, edge) => sum + (edge.value ?? 0), 0)
+}
+
+export interface PathsSankeyGraph<Edge extends PathsEdge> {
+ nodes: SankeyNodeInput<string>[]
+ links: SankeyLinkInput<Edge>[]
+ /** The highest step in the result. */
+ stepCount: number
+ /** Whether nodes sit in their step's column, so the caller can label columns by step. False
+ * when pinning was off or the result has more steps than `pinStepsUpTo` allows. */
+ stepsPinned: boolean
+}
+
+export interface PathsSankeyGraphOptions {
+ /** Short labels for page URLs. Off for a host that draws its own labels. */
+ labelUrls?: boolean
+ /** Pin each node to its step's column when the result has at most this many steps. Omit to never pin. */
+ pinStepsUpTo?: number
+ nodeColor?: (key: string) => string | undefined
+ linkColor?: string
+}
+
+/** Chart inputs for a paths result: one node per `<step>_<name>` key, so a page seen at two steps
+ * is two nodes. Node `meta` is the name without its step; link `meta` is the result row. */
+export function buildPathsSankeyGraph<Edge extends PathsEdge>(
+ edges: Edge[],
+ { labelUrls = false, pinStepsUpTo, nodeColor, linkColor }: PathsSankeyGraphOptions = {}
+): PathsSankeyGraph<Edge> {
+ const keys = pathNodeKeys(edges)
+ const parsed = keys.map((key) => ({ key, ...parsePathNodeKey(key) }))
+ const singleOrigin = labelUrls && pathOrigins(parsed.map(({ name }) => name)).size <= 1
+ const stepCount = parsed.reduce((max, { step }) => Math.max(max, step), 0)
+ const stepsPinned = pinStepsUpTo !== undefined && stepCount <= Math.min(pinStepsUpTo, MAX_SANKEY_COLUMN + 1)
+
+ const nodes = parsed.map(
+ ({ key, step, name }): SankeyNodeInput<string> => ({
+ id: key,
+ label: labelUrls ? pathUrlLabel(name, singleOrigin) : undefined,
+ color: nodeColor?.(key),
+ meta: name,
+ column: stepsPinned ? Math.max(0, step - 1) : undefined,
+ })
+ )
+ const links = edges.map(
+ (edge): SankeyLinkInput<Edge> => ({
+ source: edge.source,
+ target: edge.target,
+ value: edge.value ?? 0,
+ color: linkColor,
+ meta: edge,
+ })
+ )
+ return { nodes, links, stepCount, stepsPinned }
+}
diff --git a/products/product_analytics/frontend/insights/paths/pathsDataLogic.ts b/products/product_analytics/frontend/insights/paths/pathsDataLogic.ts
index 78aec890342a..7871b13cdc78 100644
--- a/products/product_analytics/frontend/insights/paths/pathsDataLogic.ts
+++ b/products/product_analytics/frontend/insights/paths/pathsDataLogic.ts
@@ -32,6 +32,7 @@ import type { PathsV2Query } from '~/queries/schema/schema-general'
import { isPathsQuery } from '~/queries/utils'
import { FunnelVizType, InsightLogicProps, PathType, PropertyFilterType, PropertyOperator } from '~/types'
+import { pathNodeKeys } from './pathsChartTransforms'
import { PathNodeData } from './pathUtils'
import { Paths, PathsNode } from './types'
@@ -171,22 +172,10 @@ export const pathsDataLogic = kea<pathsDataLogicType>([
],
paths: [
(s) => [s.results],
- (results: PathsLink[]): Paths => {
- const nodes: Record<string, PathsNode> = {}
- for (const path of results) {
- if (!nodes[path.source]) {
- nodes[path.source] = { name: path.source }
- }
- if (!nodes[path.target]) {
- nodes[path.target] = { name: path.target }
- }
- }
-
- return {
- nodes: Object.values(nodes),
- links: results,
- }
- },
+ (results: PathsLink[]): Paths => ({
+ nodes: pathNodeKeys(results).map((name): PathsNode => ({ name })),
+ links: results,
+ }),
],
taxonomicGroupTypes: [
(s) => [s.pathsFilter],
diff --git a/services/mcp/src/ui-apps/components/Paths.stories.tsx b/services/mcp/src/ui-apps/components/Paths.stories.tsx
new file mode 100644
index 000000000000..a161a44dbc43
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/Paths.stories.tsx
@@ -0,0 +1,110 @@
+import type { Meta, StoryFn, StoryObj } from '@storybook/react'
+import type { ReactElement } from 'react'
+
+import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
+
+import { PathsVisualizer } from './PathsVisualizer'
+import type { PathsResult } from './types'
+
+// The visualizer sizes its canvas off a ResizeObserver, so give it a definite width — a `w-full` box
+// can measure 0 at mount in the headless snapshot runner and paint nothing.
+const FixedWidth = (Story: StoryFn): ReactElement => (
+ <div className="w-[680px]">
+ <Story />
+ </div>
+)
+
+const meta: Meta = {
+ title: 'MCP Apps/Paths',
+ decorators: [McpThemeDecorator, FixedWidth],
+ parameters: {
+ testOptions: {
+ skipDarkMode: true,
+ },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+const STORE_PATHS: PathsResult = [
+ {
+ source: '1_https://example.com/',
+ target: '2_https://example.com/product',
+ value: 3705,
+ average_conversion_time: 42000,
+ },
+ {
+ source: '1_https://example.com/',
+ target: '2_https://example.com/cart',
+ value: 1240,
+ average_conversion_time: 18000,
+ },
+ {
+ source: '1_https://example.com/',
+ target: '2_https://example.com/checkout',
+ value: 303,
+ average_conversion_time: 9000,
+ },
+ {
+ source: '2_https://example.com/product',
+ target: '3_https://example.com/cart',
+ value: 1596,
+ average_conversion_time: 65000,
+ },
+ {
+ source: '2_https://example.com/product',
+ target: '3_https://example.com/',
+ value: 555,
+ average_conversion_time: 31000,
+ },
+ {
+ source: '2_https://example.com/product',
+ target: '3_https://example.com/product',
+ value: 490,
+ average_conversion_time: 22000,
+ },
+ {
+ source: '2_https://example.com/cart',
+ target: '3_https://example.com/checkout',
+ value: 842,
+ average_conversion_time: 12000,
+ },
+ {
+ source: '2_https://example.com/cart',
+ target: '3_https://example.com/product',
+ value: 210,
+ average_conversion_time: 47000,
+ },
+ {
+ source: '3_https://example.com/cart',
+ target: '4_https://example.com/checkout',
+ value: 902,
+ average_conversion_time: 15000,
+ },
+ {
+ source: '3_https://example.com/',
+ target: '4_https://example.com/product',
+ value: 320,
+ average_conversion_time: 28000,
+ },
+]
+
+export const StoreJourneys: Story = {
+ render: () => <PathsVisualizer results={STORE_PATHS} />,
+ name: 'Store page journeys',
+}
+
+export const SingleTransition: Story = {
+ render: () => (
+ <PathsVisualizer
+ results={[{ source: '1_app opened', target: '2_report viewed', value: 120, average_conversion_time: 3500 }]}
+ />
+ ),
+ name: 'Single transition',
+}
+
+export const Empty: Story = {
+ render: () => <PathsVisualizer results={[]} />,
+ name: 'No path data',
+}
diff --git a/services/mcp/src/ui-apps/components/PathsVisualizer.tsx b/services/mcp/src/ui-apps/components/PathsVisualizer.tsx
index 956319f496a8..21a7a3716648 100644
--- a/services/mcp/src/ui-apps/components/PathsVisualizer.tsx
+++ b/services/mcp/src/ui-apps/components/PathsVisualizer.tsx
@@ -1,42 +1,52 @@
-import type { ReactElement } from 'react'
+import { type ReactElement, useMemo } from 'react'
import { emptyStateIllustration } from '@posthog/mcp-ui'
-import { DataTable, type DataTableProps, Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
+import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
+import { SankeyChart } from '@posthog/quill-charts'
+import type { SankeyChartConfig } from '@posthog/quill-charts'
+
+import { parsePathNodeKey } from 'products/product_analytics/frontend/insights/paths/pathsChartTransforms'
import { ChartHeader } from './ChartHeader'
-import type { PathsVisualizerProps } from './types'
+import { useMcpChartTheme } from './charts/theme'
+import { buildPathsView, MAX_DRAWN_STEPS } from './pathsView'
+import type { PathsResultItem, PathsVisualizerProps } from './types'
import { formatDuration, formatNumber } from './utils'
const TITLE = 'Paths'
-// Edges are sorted by user count and the busiest paths lead, so a truncated
-// view stays meaningful; columns are non-sortable to match.
-const MAX_ROWS = 20
-
-function formatCellValue(value: unknown): string {
- if (value === null || value === undefined) {
- return '-'
- }
- if (typeof value === 'number') {
- return formatNumber(value)
- }
- return String(value)
+const CHART_CONFIG: SankeyChartConfig = {
+ linkOpacity: 0.35,
+ valueFormatter: formatNumber,
}
-/** Node keys are `<stepIndex>_<value>`; split into the step number and the path/value. */
-function parseNode(key: string): { step: number; path: string } {
- const sep = key.indexOf('_')
- if (sep === -1) {
- return { step: 0, path: key }
- }
- const step = Number.parseInt(key.slice(0, sep), 10)
- return { step: Number.isNaN(step) ? 0 : step, path: key.slice(sep + 1) }
+/** Which steps a transition joins, so a pair of pages that repeats at two stages reads apart. */
+function stepRange(edge: PathsResultItem): string {
+ return `step ${parsePathNodeKey(edge.source).step} to ${parsePathNodeKey(edge.target).step}`
}
export function PathsVisualizer({ results }: PathsVisualizerProps): ReactElement {
- const edges = Array.isArray(results) ? results : []
+ const theme = useMcpChartTheme()
+ const {
+ allEdges,
+ edges,
+ truncated,
+ stepsClipped,
+ graph,
+ columnLabels,
+ nodePadding,
+ stepCount,
+ pathStarts,
+ chartWidth,
+ } = useMemo(() => buildPathsView(results), [results])
+ // A node's value counts only its drawn ribbons, so a truncated view would label partial totals.
+ const config = useMemo<SankeyChartConfig>(
+ () => ({ ...CHART_CONFIG, columnLabels, nodePadding, showNodeValues: !truncated }),
+ [columnLabels, nodePadding, truncated]
+ )
+ const labelOf = useMemo(() => new Map(graph.nodes.map((node) => [node.id, node.label])), [graph.nodes])
- if (edges.length === 0) {
+ if (allEdges.length === 0) {
return (
<div>
<ChartHeader title={TITLE} />
@@ -50,53 +60,54 @@ export function PathsVisualizer({ results }: PathsVisualizerProps): ReactElement
)
}
- // Each row is an edge between two nodes; sort by user count so the busiest paths lead.
- const sorted = [...edges].sort((a, b) => (b.value ?? 0) - (a.value ?? 0))
-
- const columns = ['Step', 'From', 'To', 'Users', 'Avg. time']
- const rows: unknown[][] = sorted.map((edge) => {
- const from = parseNode(edge.source)
- const to = parseNode(edge.target)
- return [
- `${from.step} → ${to.step}`,
- from.path,
- to.path,
- edge.value ?? 0,
- edge.average_conversion_time != null ? formatDuration(edge.average_conversion_time) : '-',
- ]
- })
-
- const displayRows = rows.slice(0, MAX_ROWS)
- const hasMore = displayRows.length < rows.length
- const tableColumns: DataTableProps<unknown[], unknown>['columns'] = columns.map((col, colIndex) => ({
- id: String(colIndex),
- header: col,
- accessorFn: (row: unknown[]) => row[colIndex],
- enableSorting: false,
- cell: (info: { getValue: () => unknown }) => formatCellValue(info.getValue()),
- }))
-
- const topUsers = sorted[0]?.value ?? 0
-
return (
- <div>
+ <div data-attr="paths-sankey" className="w-full">
<ChartHeader title={TITLE} />
- <DataTable columns={tableColumns} data={displayRows} className="rounded-lg border" />
- {hasMore && (
- <span className="mt-2 block text-center text-xs text-muted-foreground">
- Showing {displayRows.length} of {rows.length} transitions
- </span>
- )}
-
+ <div className="h-80 w-full overflow-x-auto">
+ {/* The chart sizes to its parent, so a long path needs a wider parent to scroll. */}
+ <div className="flex flex-col h-full" style={{ width: chartWidth }}>
+ <SankeyChart<string, PathsResultItem>
+ nodes={graph.nodes}
+ links={graph.links}
+ theme={theme}
+ config={config}
+ />
+ </div>
+ </div>
+ {/* The canvas has no per-ribbon semantics, so screen readers get the transitions as text. */}
+ <ul className="sr-only">
+ {edges.map((edge) => (
+ <li key={`${edge.source}→${edge.target}`}>
+ {labelOf.get(edge.source)} to {labelOf.get(edge.target)} ({stepRange(edge)}):{' '}
+ {formatNumber(edge.value ?? 0)} paths
+ {edge.average_conversion_time != null
+ ? `, ${formatDuration(edge.average_conversion_time)} on average`
+ : ''}
+ </li>
+ ))}
+ </ul>
<div className="mt-4 rounded-md bg-muted/50 p-3 text-sm text-muted-foreground">
- <strong className="text-foreground">{formatNumber(edges.length)}</strong> path transition
- {edges.length === 1 ? '' : 's'}
- {topUsers > 0 && (
+ {truncated ? (
+ <>
+ Showing the <strong className="text-foreground">{formatNumber(edges.length)}</strong> busiest of{' '}
+ <strong className="text-foreground">{formatNumber(allEdges.length)}</strong> path transitions
+ </>
+ ) : (
+ <>
+ <strong className="text-foreground">{formatNumber(edges.length)}</strong> path transition
+ {edges.length === 1 ? '' : 's'}
+ </>
+ )}{' '}
+ across <strong className="text-foreground">{formatNumber(stepCount)}</strong> step
+ {stepCount === 1 ? '' : 's'}
+ {pathStarts > 0 && (
<>
{' '}
- · busiest carries <strong className="text-foreground">{formatNumber(topUsers)}</strong> users
+ · <strong className="text-foreground">{formatNumber(pathStarts)}</strong> path
+ {pathStarts === 1 ? ' in this result begins' : 's in this result begin'} at step 1
</>
)}
+ {stepsClipped && <> · The chart shows steps 1 to {MAX_DRAWN_STEPS}</>}
</div>
</div>
)
diff --git a/services/mcp/src/ui-apps/components/pathsView.ts b/services/mcp/src/ui-apps/components/pathsView.ts
new file mode 100644
index 000000000000..6f16e44bccde
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/pathsView.ts
@@ -0,0 +1,76 @@
+import {
+ buildPathsSankeyGraph,
+ parsePathNodeKey,
+ pathStartCount,
+} from 'products/product_analytics/frontend/insights/paths/pathsChartTransforms'
+import type { PathsSankeyGraph } from 'products/product_analytics/frontend/insights/paths/pathsChartTransforms'
+
+import type { PathsResultItem } from './types'
+
+// The busiest transitions carry the story; past this many the ribbons are too thin to read and
+// the layout's iterative relaxation stops being cheap inside an embedded app.
+export const MAX_EDGES = 60
+
+const MAX_STEPS_IN_FRAME = 5
+
+// The chart draws transitions up to this step only, which bounds the scroll width and keeps every node pinned.
+export const MAX_DRAWN_STEPS = 25
+
+const NODE_PADDING = 6
+// Total gap one column may take out of the h-80 chart's plot, under half its height. When a dense
+// column's gaps fill the plot, the layout engine draws its nodes and ribbons with no height.
+const MAX_COLUMN_PADDING = 120
+
+export interface PathsView {
+ allEdges: PathsResultItem[]
+ /** The transitions the chart draws, busiest first. */
+ edges: PathsResultItem[]
+ truncated: boolean
+ /** True when the result has transitions past `MAX_DRAWN_STEPS` that the chart leaves out. */
+ stepsClipped: boolean
+ graph: PathsSankeyGraph<PathsResultItem>
+ columnLabels: string[]
+ nodePadding: number
+ /** The highest step in the full result, not only in the drawn transitions. */
+ stepCount: number
+ pathStarts: number
+ /** CSS width of the chart's scroll content. */
+ chartWidth: string
+}
+
+export function buildPathsView(results: unknown): PathsView {
+ const allEdges: PathsResultItem[] = Array.isArray(results) ? results : []
+ const drawable = allEdges.filter((edge) => parsePathNodeKey(edge.target).step <= MAX_DRAWN_STEPS)
+ // Busiest first, so a truncated view keeps the transitions that matter.
+ const edges = [...drawable].sort((a, b) => (b.value ?? 0) - (a.value ?? 0)).slice(0, MAX_EDGES)
+ const graph = buildPathsSankeyGraph(edges, { labelUrls: true, pinStepsUpTo: MAX_DRAWN_STEPS })
+ const columnLabels = Array.from({ length: graph.stepCount }, (_, i) => `Step ${i + 1}`)
+
+ const perStep = new Map<number, number>()
+ for (const node of graph.nodes) {
+ const step = parsePathNodeKey(node.id).step
+ perStep.set(step, (perStep.get(step) ?? 0) + 1)
+ }
+ const densest = Math.max(1, ...perStep.values())
+ const nodePadding = densest > 1 ? Math.min(NODE_PADDING, MAX_COLUMN_PADDING / (densest - 1)) : NODE_PADDING
+
+ // The busiest edges can leave out the last steps, so count steps on the full result.
+ const stepCount = allEdges.reduce((max, edge) => Math.max(max, parsePathNodeKey(edge.target).step), 0)
+ // Past five steps the chart grows a fifth of the frame per step and scrolls, as the paths
+ // insight does, so long paths keep readable columns.
+ const chartWidth =
+ graph.stepCount > MAX_STEPS_IN_FRAME ? `${(graph.stepCount / MAX_STEPS_IN_FRAME) * 100}%` : '100%'
+
+ return {
+ allEdges,
+ edges,
+ truncated: edges.length < allEdges.length,
+ stepsClipped: drawable.length < allEdges.length,
+ graph,
+ columnLabels,
+ nodePadding,
+ stepCount,
+ pathStarts: pathStartCount(allEdges),
+ chartWidth,
+ }
+}
diff --git a/services/mcp/tests/unit/paths-view.test.ts b/services/mcp/tests/unit/paths-view.test.ts
new file mode 100644
index 000000000000..52cd3200a7c7
--- /dev/null
+++ b/services/mcp/tests/unit/paths-view.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest'
+
+import { buildPathsView, MAX_EDGES } from '../../src/ui-apps/components/pathsView'
+import type { PathsResultItem } from '../../src/ui-apps/components/types'
+
+function edge(step: number, from: string, to: string, value: number): PathsResultItem {
+ return { source: `${step}_${from}`, target: `${step + 1}_${to}`, value }
+}
+
+describe('buildPathsView', () => {
+ it('draws only the busiest transitions but counts steps on the full result', () => {
+ const busy = Array.from({ length: MAX_EDGES }, (_, i) => edge(1, '/home', `/page-${i}`, 100 + i))
+ const quietDeepStep = edge(6, '/checkout', '/thanks', 1)
+
+ const view = buildPathsView([quietDeepStep, ...busy])
+
+ expect(view.truncated).toBe(true)
+ expect(view.edges).toHaveLength(MAX_EDGES)
+ expect(view.edges).not.toContainEqual(quietDeepStep)
+ expect(view.edges[0]?.value).toBe(100 + MAX_EDGES - 1)
+ expect(view.stepCount).toBe(7)
+ })
+
+ it.each([
+ { name: 'fits five steps in the frame', steps: 4, chartWidth: '100%', columns: 4, stepsClipped: false },
+ { name: 'scrolls past five steps', steps: 9, chartWidth: '180%', columns: 9, stepsClipped: false },
+ {
+ name: 'draws only the first steps of a very long path, each under its step header',
+ steps: 40,
+ chartWidth: '500%',
+ columns: 25,
+ stepsClipped: true,
+ },
+ ])('$name', ({ steps, chartWidth, columns, stepsClipped }) => {
+ const chain = Array.from({ length: steps - 1 }, (_, i) => edge(i + 1, `/p${i}`, `/p${i + 1}`, 10))
+
+ const view = buildPathsView(chain)
+
+ expect(view.chartWidth).toBe(chartWidth)
+ expect(view.graph.stepsPinned).toBe(true)
+ expect(view.columnLabels).toHaveLength(columns)
+ expect(view.stepsClipped).toBe(stepsClipped)
+ expect(view.stepCount).toBe(steps)
+ })
+
+ it('returns an empty view for a non-array result', () => {
+ expect(buildPathsView(undefined)).toMatchObject({ allEdges: [], edges: [], truncated: false, stepCount: 0 })
+ })
+})