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(paths): render user paths with the quill SankeyChart behind a flag (#104631)

Paul D'Ambraa7831e30701a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 230aec6a9f5c..b009ba5c2e1f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -204,10 +204,14 @@ snapshots:
hash: v1.k794b7964.8e7770037014d788ef5b7299b6b2f834c2afcad14dd6c6033ddd8ac885faa1c6.buSflXKIcQC5dcm7fbQWsczrZY8TleOkvO86ugYW8yw
charts-heatmap--linear-color-scale--light:
hash: v1.k794b7964.c94c02704b7f9b4972f811336d019e15b77cff047551902ca74d65c1571ea6ff.PA6k_wyPYr-SNYm1-Mv8sa0DFCLb2-8QxOVNlDn4hE8
+ charts-sankeychart--controlled-highlight--dark:
+ hash: v1.k794b7964.eba0651fe51c58db0efb22be780f9c3312770910860cf3c1c0ebc899677af34d.y1waF2MLNvKZONNX977TQ_wQE4cB_YRyddAMgZrBdBk
+ charts-sankeychart--controlled-highlight--light:
+ hash: v1.k794b7964.037b47557a521539baf510394e37a3947590d6e4f37158823c58d5a0009ee614.ROQipQPqSPpPTPDgQMtDB1xrv3R05qoKQ6KijSSsHgE
charts-sankeychart--hovered-link--dark:
hash: v1.k794b7964.e50f64b0a2556e240047944407ec800fb78ffc2ad3eca93219f235d64883327d.X8189N1MHu1yKO4xcQgIglRR8DdqCLFhNfcqHuspBNE
charts-sankeychart--hovered-link--light:
- hash: v1.k794b7964.e6a0d26ab605825cb5536b0d2ff19e606d1720fe7db242a0b72e710246fa01ad.iXgOgNfOVXu_y_Wg2MG9-4ugoULs_kgICgXVoRmaMh0
+ hash: v1.k794b7964.e13a6e93fd46df674c93764a5d35d4e880614ea11476c4aa73233dfdb26bc89d.HI4tX3ww4ZJGOZQVW95F4_VRUjg5a50dwjVm0DI3ngE
charts-sankeychart--left-aligned-with-values--dark:
hash: v1.k794b7964.1feb41fa4c6017593646eff1e33c11eb8ef9e224e5776a2bca43c97ff2390f9b.OQ83mEQIk1BTINe94sYI5ByoXnLHMvRo8W_9an60lrI
charts-sankeychart--left-aligned-with-values--light:
@@ -3916,6 +3920,10 @@ snapshots:
hash: v1.k794b7964.63b1b171e7a383ea613ae033e9455f932b4ecd23f2f2a9c8cea6ad172b7320c3.m4N1HRS9A1bcQK8FtoM5drv-4DLmsvWeXRVgReHzG0g
insights-paths--user-paths--light:
hash: v1.k794b7964.e0757ba6f44ade516787a8e68989216fcadd06f26a9f4bc4b9a91686a3173e4a.899TyMHHv2cx-QfVpz7xFZu72QNf_Ro_KOur0BZwq-M
+ insights-paths--user-paths-sankey-chart--dark:
+ hash: v1.k794b7964.08416361f74f936778d6bf316b3490c2b17889f8e4f845ab35eb54a2d184f9fb.4QIVsxjS5d-PXsbopqXzdBzYeMYiDUwW3oln8UuW-xk
+ insights-paths--user-paths-sankey-chart--light:
+ hash: v1.k794b7964.81f8b343ebbb9b039bf7907067bec981243ff77c7c0fac176652d6f25b131885.ilAVRrwxK7zxNHtEP8bwL_cT_XzXa4V9ndg-b1KjLbo
insights-regionmap--default--dark:
hash: v1.k794b7964.27f645d497cc1af88387932b1f580fff796596ea0cea520c6c3ce745a2625612.DbzWk3NIbbjDzeeJvLUlooVLALtBzLDZ02gl6S6mllk
insights-regionmap--default--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3ddfa93c9dd8..37f4161a6b9f 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -500,6 +500,7 @@ export const FEATURE_FLAGS = {
PRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analytics
PRODUCT_ANALYTICS_HOME_TAB: 'product-analytics-home-tab', // owner: #team-product-analytics
PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics
+ PRODUCT_ANALYTICS_PATHS_SANKEY_CHART: 'paths-sankey-chart', // owner: @pauldambra #team-product-analytics, renders the paths insight with the quill SankeyChart instead of the d3 SVG
PRODUCT_ANALYTICS_PATHS_STRIP_QUERY_STRING: 'paths-strip-query-string', // owner: #team-product-analytics, gates the "Ignore URL query strings" switch on paths insights
PRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS: 'product-analytics-quarter-year-intervals', // owner: @sampennington #team-product-analytics, gates quarter/year interval selection on insights
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsx
index 389f893661a0..61a306015bcb 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsx
@@ -89,6 +89,30 @@ export const LeftAlignedWithValues: Story = {
},
}
+// The host decides what emphasis means: here every session that reached execute-sql at the
+// second stage, upstream and downstream, while the chart's own hover dimming stays off.
+const SQL_PATH_HIGHLIGHT = {
+ nodeIds: new Set(['start', '1:schema', '1:sql', '2:sql', 'completed', 'error']),
+ linkIndices: new Set([0, 1, 3, 5, 9, 10]),
+}
+
+export const ControlledHighlight: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={720} height={320}>
+ <SankeyChart
+ nodes={NODES}
+ links={LINKS}
+ theme={theme}
+ config={{ columnLabels: STAGES }}
+ highlight={SQL_PATH_HIGHLIGHT}
+ />
+ </Stage>
+ )
+ },
+}
+
export const Narrow: Story = {
render: function Render() {
const theme = useReactiveTheme()
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 12dac8f59a6b..9b5e96ea4c95 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx
@@ -50,10 +50,17 @@ describe('SankeyChart', () => {
expect(chart.canvas.getAttribute('aria-label')).toBe('Sankey chart with 3 nodes and 2 links')
})
- it('shows the hovered node in the tooltip and fires onNodeClick for it', async () => {
+ 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()
const { chart, rerender } = renderHogChart(
- <SankeyChart nodes={NODES} links={LINKS} theme={THEME} onNodeClick={onNodeClick} />,
+ <SankeyChart
+ nodes={NODES}
+ links={LINKS}
+ theme={THEME}
+ onNodeClick={onNodeClick}
+ onHoverChange={onHoverChange}
+ />,
{ nativeTooltip: true }
)
await waitFor(() => {
@@ -65,15 +72,28 @@ describe('SankeyChart', () => {
fireEvent.click(chart.element)
expect(onNodeClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'a', value: 12 }))
+ // Repeated moves inside one node report a single hover; leaving reports null.
+ fireEvent.mouseMove(chart.element, nodeCenter('a'))
+ expect(onHoverChange.mock.calls).toEqual([[{ kind: 'node', node: expect.objectContaining({ id: 'a' }) }]])
+ fireEvent.mouseLeave(chart.element)
+ expect(onHoverChange).toHaveBeenLastCalledWith(null)
+
+ await waitFor(() => {
+ fireEvent.mouseMove(chart.element, nodeCenter('a'))
+ expect(getHogChartTooltip()?.textContent).toContain('Tool A')
+ })
+
rerender(
<SankeyChart
nodes={NODES}
links={LINKS}
theme={{ ...THEME, colors: [...THEME.colors] }}
onNodeClick={onNodeClick}
+ onHoverChange={onHoverChange}
/>
)
expect(getHogChartTooltip()?.textContent).toContain('Tool A')
+ expect(onHoverChange).not.toHaveBeenLastCalledWith(null)
onNodeClick.mockClear()
rerender(
@@ -82,32 +102,69 @@ describe('SankeyChart', () => {
links={LINKS}
theme={THEME}
onNodeClick={onNodeClick}
+ onHoverChange={onHoverChange}
config={{ nodeWidth: 24 }}
/>
)
await waitFor(() => expect(getHogChartTooltip()).toBeNull())
+ // The hovered node belonged to the old layout, so the host is told it is gone.
+ expect(onHoverChange).toHaveBeenLastCalledWith(null)
fireEvent.click(chart.element)
expect(onNodeClick).not.toHaveBeenCalled()
})
- it('shows the tooltip on a first tap and fires onNodeClick on the second', async () => {
+ it('shows the tooltip on a first tap, fires onNodeClick on the second, and clears on an empty tap', async () => {
const onNodeClick = jest.fn()
+ const onHoverChange = jest.fn()
const { chart } = renderHogChart(
- <SankeyChart nodes={NODES} links={LINKS} theme={THEME} onNodeClick={onNodeClick} />,
+ <SankeyChart
+ nodes={NODES}
+ links={LINKS}
+ theme={THEME}
+ onNodeClick={onNodeClick}
+ onHoverChange={onHoverChange}
+ />,
{ nativeTooltip: true }
)
// A tap sends no mousemove first, so nothing is hovered when the click arrives. jsdom has
// no PointerEvent, so the pointer type rides on a MouseEvent React reads it from.
- const tap = (): void => {
+ const tap = (at: { clientX: number; clientY: number }): void => {
const down = Object.assign(new MouseEvent('pointerdown', { bubbles: true }), { pointerType: 'touch' })
fireEvent(chart.element, down)
- fireEvent.click(chart.element, nodeCenter('a'))
+ fireEvent.click(chart.element, at)
}
- tap()
+ tap(nodeCenter('a'))
await waitFor(() => expect(getHogChartTooltip()?.textContent).toContain('Tool A'))
expect(onNodeClick).not.toHaveBeenCalled()
- tap()
+ tap(nodeCenter('a'))
expect(onNodeClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'a' }))
+
+ // Inside the margin, outside every node and ribbon.
+ tap({ clientX: 2, clientY: 2 })
+ expect(onHoverChange).toHaveBeenLastCalledWith(null)
+ })
+
+ it('ignores a tap on an interactive overlay over a node', () => {
+ const onNodeClick = jest.fn()
+ const onHoverChange = jest.fn()
+ const { chart, getByRole } = renderHogChart(
+ <SankeyChart
+ nodes={NODES}
+ links={LINKS}
+ theme={THEME}
+ onNodeClick={onNodeClick}
+ onHoverChange={onHoverChange}
+ config={{ tooltip: { enabled: false } }}
+ >
+ <button data-hog-charts-interactive-overlay="">card</button>
+ </SankeyChart>
+ )
+ const down = Object.assign(new MouseEvent('pointerdown', { bubbles: true }), { pointerType: 'touch' })
+ fireEvent(chart.element, down)
+ fireEvent.click(getByRole('button'), nodeCenter('a'))
+
+ expect(onNodeClick).not.toHaveBeenCalled()
+ expect(onHoverChange).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'node' }))
})
it('fires the click on the first tap when the tooltip is disabled', () => {
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
index 61d75907c46a..0de1b0df744c 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
@@ -12,8 +12,8 @@ import type { ChartDrawArgs, ChartMargins, ChartScales } from '../../core/types'
import { defaultResolveValue } from '../../core/types'
import { Tooltip } from '../../overlays/Tooltip'
import { PieTooltip } from '../PieChart/PieTooltip'
-import { drawSankey, drawSankeyHover, sankeyActiveFlow } from './draw-sankey'
-import type { SankeyActiveFlow } from './draw-sankey'
+import { drawSankey, drawSankeyHover, emphasisForHighlight, emphasisForHit } from './draw-sankey'
+import type { SankeyEmphasis } from './draw-sankey'
import { SankeyLayoutContext } from './sankey-context'
import type { SankeyLayoutContextValue } from './sankey-context'
import { computeSankeyLayout, defaultValueFormatter, hoverIndexToHit } from './sankey-data'
@@ -70,6 +70,8 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
tooltip,
onNodeClick,
onLinkClick,
+ onHoverChange,
+ highlight,
className,
dataAttr,
children,
@@ -139,10 +141,21 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
[nodes, links, dimensions, nodeWidth, nodePadding, nodeAlign, preserveNodeOrder, colorForLabel]
)
- // The shared draw loop keys repaints on `scales` identity, so wrap the layout in one.
+ // A controlled highlight paints on the static layer, so a change to it is a full repaint
+ // rather than a hover animation frame. The graph is small enough that this is cheap, and it
+ // keeps the hover overlay free to stay dark while the host owns emphasis.
+ const emphasis = useMemo(
+ () => (highlight ? emphasisForHighlight(layout as SankeyChartLayout<unknown, unknown>, highlight) : null),
+ [layout, highlight]
+ )
+ const hasEmphasis = emphasis !== null
+
+ // The shared draw loop keys repaints, including the hover overlay, on `scales` identity. The
+ // overlay must also repaint when `linkOpacity` changes or a controlled highlight starts or
+ // ends under a still cursor.
const scales = useMemo<ChartScales | null>(
- () => (dimensions ? { ...NO_SCALES, _private: { __sankey: layout, linkOpacity } } : null),
- [dimensions, layout, linkOpacity]
+ () => (dimensions ? { ...NO_SCALES, _private: { __sankey: layout, linkOpacity, hasEmphasis } } : null),
+ [dimensions, layout, linkOpacity, hasEmphasis]
)
const { hoverIndex, hoverPosition, tooltipCtx, handlers } = useSankeyInteraction<NodeMeta, LinkMeta>({
@@ -152,32 +165,39 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
showTooltip,
onNodeClick,
onLinkClick,
+ onHoverChange,
})
const drawStatic = useCallback(
- ({ ctx: drawCtx }: ChartDrawArgs) =>
- drawSankey(drawCtx, layout as SankeyChartLayout<unknown, unknown>, { linkOpacity }),
- [layout, linkOpacity]
+ ({ ctx: drawCtx, theme: drawTheme }: ChartDrawArgs) =>
+ drawSankey(drawCtx, layout as SankeyChartLayout<unknown, unknown>, {
+ linkOpacity,
+ emphasis,
+ backgroundColor: drawTheme.backgroundColor,
+ }),
+ [layout, linkOpacity, emphasis]
)
// The hover fade repaints every frame; resolve the connected flow once per hovered item.
- const activeFlowFor = useMemo(() => {
- let cached: { index: number; flow: SankeyActiveFlow | null } | null = null
- return (index: number): SankeyActiveFlow | null => {
+ const hoverEmphasisFor = useMemo(() => {
+ let cached: { index: number; emphasis: SankeyEmphasis | null } | null = null
+ return (index: number): SankeyEmphasis | null => {
if (cached?.index !== index) {
const untyped = layout as SankeyChartLayout<unknown, unknown>
- cached = { index, flow: sankeyActiveFlow(untyped, hoverIndexToHit(untyped, index)) }
+ cached = { index, emphasis: emphasisForHit(untyped, hoverIndexToHit(untyped, index)) }
}
- return cached.flow
+ return cached.emphasis
}
}, [layout])
const drawHover = useCallback(
({ ctx: drawCtx, hoverIndex: index, hoverProgress, theme: drawTheme }: ChartDrawArgs): boolean =>
- drawSankeyHover(drawCtx, layout as SankeyChartLayout<unknown, unknown>, activeFlowFor(index), {
- linkOpacity,
- backgroundColor: drawTheme.backgroundColor,
- progress: hoverProgress,
- }),
- [layout, linkOpacity, activeFlowFor]
+ emphasis
+ ? false
+ : drawSankeyHover(drawCtx, layout as SankeyChartLayout<unknown, unknown>, hoverEmphasisFor(index), {
+ linkOpacity,
+ backgroundColor: drawTheme.backgroundColor,
+ progress: hoverProgress,
+ }),
+ [layout, linkOpacity, emphasis, hoverEmphasisFor]
)
useChartDraw({
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.test.ts b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.test.ts
index d0841cf27f3b..27caa2f32098 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.test.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.test.ts
@@ -1,4 +1,4 @@
-import { drawSankeyHover, sankeyActiveFlow } from './draw-sankey'
+import { drawSankey, drawSankeyHover, emphasisForHit } from './draw-sankey'
import { computeSankeyLayout } from './sankey-data'
const BACKGROUND = 'hsl(235deg 8% 15%)'
@@ -24,10 +24,13 @@ function layoutOf(secondLinkValue = 10): ReturnType<typeof computeSankeyLayout>
function recordingCtx(serialize: Record<string, string>): {
ctx: CanvasRenderingContext2D
strokes: string[]
+ strokeAlphas: number[]
fills: string[]
} {
const strokes: string[] = []
+ const strokeAlphas: number[] = []
const fills: string[] = []
+ const savedAlphas: number[] = []
let fill = '#000000'
let stroke = '#000000'
const ctx = {
@@ -48,12 +51,17 @@ function recordingCtx(serialize: Record<string, string>): {
beginPath: () => {},
moveTo: () => {},
bezierCurveTo: () => {},
- save: () => {},
- restore: () => {},
+ save: () => savedAlphas.push(ctx.globalAlpha),
+ restore: () => {
+ ctx.globalAlpha = savedAlphas.pop() ?? 1
+ },
fillRect: () => fills.push(fill),
- stroke: () => strokes.push(stroke),
+ stroke: () => {
+ strokes.push(stroke)
+ strokeAlphas.push(ctx.globalAlpha)
+ },
} as unknown as CanvasRenderingContext2D
- return { ctx, strokes, fills }
+ return { ctx, strokes, strokeAlphas, fills }
}
describe('drawSankeyHover', () => {
@@ -66,7 +74,7 @@ describe('drawSankeyHover', () => {
(_name, serialize, secondLinkValue, expectedStrokes) => {
const layout = layoutOf(secondLinkValue)
const { ctx, strokes } = recordingCtx(serialize)
- drawSankeyHover(ctx, layout, sankeyActiveFlow(layout, { kind: 'link', index: 0 }), {
+ drawSankeyHover(ctx, layout, emphasisForHit(layout, { kind: 'link', index: 0 }), {
linkOpacity: 0.4,
backgroundColor: BACKGROUND,
progress: 1,
@@ -85,7 +93,7 @@ describe('drawSankeyHover', () => {
layout.links[1].color = 'transparent'
layout.nodes.find((node) => node.id === 'c')!.color = 'transparent'
const { ctx, strokes, fills } = recordingCtx({ [BACKGROUND]: '#202023' })
- drawSankeyHover(ctx, layout, sankeyActiveFlow(layout, { kind: 'link', index: 0 }), {
+ drawSankeyHover(ctx, layout, emphasisForHit(layout, { kind: 'link', index: 0 }), {
linkOpacity: 0.4,
backgroundColor: BACKGROUND,
progress: 1,
@@ -94,4 +102,56 @@ describe('drawSankeyHover', () => {
expect(strokes).toHaveLength(1)
expect(fills).toHaveLength(2)
})
+
+ it.each([
+ ['static layer below the hover target', 'static', 0.4, 0.85],
+ ['hover layer below the hover target', 'hover', 0.4, 0.85],
+ ['static layer above the hover target', 'static', 0.9, 0.9],
+ ['hover layer above the hover target', 'hover', 0.9, 0.9],
+ ])('composites an emphasized ribbon to its target opacity: %s', (_name, layer, linkOpacity, expectedOpacity) => {
+ const layout = layoutOf(0)
+ const emphasis = emphasisForHit(layout, { kind: 'link', index: 0 })
+ const { ctx, strokeAlphas } = recordingCtx({ [BACKGROUND]: '#202023' })
+ if (layer === 'static') {
+ drawSankey(ctx, layout, { linkOpacity, emphasis, backgroundColor: BACKGROUND })
+ } else {
+ drawSankeyHover(ctx, layout, emphasis, { linkOpacity, backgroundColor: BACKGROUND, progress: 1 })
+ }
+
+ // The hover layer sits on a static layer that already drew the ribbon at rest.
+ const painted = layer === 'hover' ? [linkOpacity, ...strokeAlphas] : strokeAlphas
+ const composite = 1 - painted.reduce((clear, alpha) => clear * (1 - alpha), 1)
+ expect(composite).toBeCloseTo(expectedOpacity)
+ })
+
+ it('composites an emphasized ribbon with a translucent color to the target opacity', () => {
+ const layout = layoutOf(0)
+ layout.links[0].color = 'rgba(255, 0, 0, 0.5)'
+ const emphasis = emphasisForHit(layout, { kind: 'link', index: 0 })
+ const { ctx, strokeAlphas } = recordingCtx({ [BACKGROUND]: '#202023' })
+ drawSankey(ctx, layout, { linkOpacity: 0.4, emphasis, backgroundColor: BACKGROUND })
+
+ const painted = strokeAlphas.map((alpha) => alpha * 0.5)
+ const composite = 1 - painted.reduce((clear, alpha) => clear * (1 - alpha), 1)
+ expect(composite).toBeCloseTo(0.5 * 0.85)
+ })
+
+ it('dims an inactive ribbon in proportion to hover progress', () => {
+ const layout = layoutOf()
+ const { ctx, strokes, strokeAlphas } = recordingCtx({ [BACKGROUND]: '#202023' })
+ drawSankeyHover(ctx, layout, emphasisForHit(layout, { kind: 'link', index: 0 }), {
+ linkOpacity: 0.4,
+ backgroundColor: BACKGROUND,
+ progress: 0.5,
+ })
+
+ const fullDim = recordingCtx({ [BACKGROUND]: '#202023' })
+ drawSankeyHover(fullDim.ctx, layout, emphasisForHit(layout, { kind: 'link', index: 0 }), {
+ linkOpacity: 0.4,
+ backgroundColor: BACKGROUND,
+ progress: 1,
+ })
+ expect(strokeAlphas[0]).toBeCloseTo(0.5)
+ expect(strokes[0]).toBe(fullDim.strokes[0])
+ })
})
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.ts b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.ts
index 752dd89b94d5..c79a8bc43556 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.ts
@@ -2,11 +2,20 @@ import { color as d3Color } from 'd3-color'
import { mixColors } from '../../core/color-utils'
import type { SankeyChartLayout, SankeyHit, SankeyLinkDatum, SankeyNodeDatum } from './sankey-data'
+import type { SankeyHighlight } from './types'
export interface DrawSankeyOptions {
linkOpacity: number
}
+/** The part of the graph that stays at full strength while the rest dims. */
+export interface SankeyEmphasis {
+ nodes: Set<SankeyNodeDatum>
+ links: Set<SankeyLinkDatum>
+ /** The node under the cursor, lightened a step further than the other active nodes. */
+ focus?: SankeyNodeDatum
+}
+
/** Ribbon opacity while it, or a node it touches, is hovered. */
const HOVER_LINK_OPACITY = 0.85
/** The rest of the graph fades toward the background so the hovered flow stands out. */
@@ -44,24 +53,8 @@ function fillNode(ctx: CanvasRenderingContext2D, node: SankeyNodeDatum, color: s
ctx.fillRect(node.x0, node.y0, node.x1 - node.x0, Math.max(1, node.y1 - node.y0))
}
-/** Static layer: every ribbon under every node, in input order. */
-export function drawSankey(ctx: CanvasRenderingContext2D, layout: SankeyChartLayout, options: DrawSankeyOptions): void {
- for (const link of layout.links) {
- strokeLink(ctx, link, link.color, options.linkOpacity)
- }
- for (const node of layout.nodes) {
- fillNode(ctx, node, node.color)
- }
-}
-
-export interface SankeyActiveFlow {
- hit: SankeyHit
- links: Set<SankeyLinkDatum>
- nodes: Set<SankeyNodeDatum>
-}
-
-/** The hovered node or ribbon plus everything connected to it, or `null` when nothing is hovered. */
-export function sankeyActiveFlow(layout: SankeyChartLayout, hit: SankeyHit | null): SankeyActiveFlow | null {
+/** The hovered node with every ribbon it touches, or the hovered ribbon with its two ends. */
+export function emphasisForHit(layout: SankeyChartLayout, hit: SankeyHit | null): SankeyEmphasis | null {
if (!hit) {
return null
}
@@ -77,13 +70,32 @@ export function sankeyActiveFlow(layout: SankeyChartLayout, hit: SankeyHit | nul
nodes.add(link.target)
}
}
- } else {
- const link = layout.links[hit.index]
- links.add(link)
- nodes.add(link.source)
- nodes.add(link.target)
+ return { nodes, links, focus: node }
}
- return { hit, links, nodes }
+ const link = layout.links[hit.index]
+ links.add(link)
+ nodes.add(link.source)
+ nodes.add(link.target)
+ return { nodes, links }
+}
+
+/** Resolves a consumer's highlight to laid-out data. Ids and indices the layout does not know are
+ * ignored, so a highlight computed from a previous dataset does not throw mid-transition. */
+export function emphasisForHighlight(layout: SankeyChartLayout, highlight: SankeyHighlight): SankeyEmphasis {
+ const nodes = new Set<SankeyNodeDatum>()
+ const links = new Set<SankeyLinkDatum>()
+ for (const node of layout.nodes) {
+ if (highlight.nodeIds.has(node.id)) {
+ nodes.add(node)
+ }
+ }
+ for (const index of highlight.linkIndices) {
+ const link = layout.links[index]
+ if (link) {
+ links.add(link)
+ }
+ }
+ return { nodes, links }
}
function isMixable(parsed: ReturnType<typeof d3Color> | null): boolean {
@@ -111,55 +123,106 @@ function parseableColor(ctx: CanvasRenderingContext2D, color: string): string |
return first === second && isMixable(d3Color(first)) ? first : null
}
-/** Hover layer: dims the graph toward the background, then repaints the active flow at full
- * strength. Returns false when nothing is hovered. */
-export function drawSankeyHover(
+/** Paints `emphasis` at full strength over a graph already drawn at rest, dimming the rest toward
+ * `dimTarget` as `progress` goes from 0 to 1. */
+function paintEmphasis(
ctx: CanvasRenderingContext2D,
layout: SankeyChartLayout,
- flow: SankeyActiveFlow | null,
- options: DrawSankeyOptions & { backgroundColor?: string; progress: number }
-): boolean {
- if (!flow) {
- return false
- }
- const { hit, links: activeLinks, nodes: activeNodes } = flow
- const dimTarget = parseableColor(ctx, options.backgroundColor || HOVER_DIM_TARGET_FALLBACK)
+ emphasis: SankeyEmphasis,
+ options: DrawSankeyOptions & { dimTarget: string; progress: number }
+): void {
+ const dimTarget = parseableColor(ctx, options.dimTarget)
const dim = options.progress * HOVER_DIM_AMOUNT
-
- // The dim fill must be opaque: a translucent repaint composites over the full-color static
- // layer and does not dim at all. A ribbon with nothing parseable to mix is left to the static
- // layer: any repaint over it would either darken it or paint it in the background color.
+ // The dim fill must be opaque: a translucent repaint composites over the full-color resting
+ // layer and does not dim at all. A ribbon with nothing parseable to mix is left as drawn at
+ // rest: any repaint over it would either darken it or paint it in the background color.
for (const link of layout.links) {
- if (activeLinks.has(link) || !dimTarget) {
+ if (emphasis.links.has(link) || !dimTarget) {
continue
}
const linkColor = parseableColor(ctx, link.color)
if (linkColor) {
const resting = mixColors(dimTarget, linkColor, options.linkOpacity)
- // Fading the opaque dim in with progress keeps the first frame identical to the static layer.
- strokeLink(ctx, link, mixColors(resting, dimTarget, dim), options.progress)
+ // The dim is painted at `progress` alpha over the resting ribbon, so the color carries the full
+ // dim: the two together move the ribbon toward the target linearly, and the first frame
+ // matches the resting layer.
+ strokeLink(ctx, link, mixColors(resting, dimTarget, HOVER_DIM_AMOUNT), options.progress)
}
}
- for (const link of activeLinks) {
- const opacity = options.linkOpacity + (HOVER_LINK_OPACITY - options.linkOpacity) * options.progress
- strokeLink(ctx, link, link.color, opacity)
+ // A resting opacity above the hover target must not drop when the flow is emphasized.
+ const targetOpacity = Math.max(HOVER_LINK_OPACITY, options.linkOpacity)
+ const activeOpacity = options.linkOpacity + (targetOpacity - options.linkOpacity) * options.progress
+ // The emphasized ribbon is already on the canvas at `linkOpacity`, and canvas alpha compounds.
+ // The repaint opacity makes the composite equal `activeOpacity` instead of overshooting it. A
+ // color's own alpha scales both the resting and the repaint stroke, so it enters the solution.
+ for (const link of emphasis.links) {
+ const colorAlpha = d3Color(link.color)?.opacity ?? 1
+ const restingAlpha = colorAlpha * options.linkOpacity
+ const repaintOpacity = restingAlpha < 1 ? (activeOpacity - options.linkOpacity) / (1 - restingAlpha) : 0
+ if (repaintOpacity > 0) {
+ strokeLink(ctx, link, link.color, repaintOpacity)
+ }
}
- // Nodes go last so a ribbon that skips a column never paints over the node it passes behind.
+ // Every ribbon goes under every node, as on the resting layer, so an emphasized ribbon that
+ // crosses a column does not cover a node it does not touch.
for (const node of layout.nodes) {
- if (!activeNodes.has(node) && dimTarget) {
+ if (!emphasis.nodes.has(node) && dimTarget) {
const nodeColor = parseableColor(ctx, node.color)
if (nodeColor) {
fillNode(ctx, node, mixColors(nodeColor, dimTarget, dim))
}
}
}
- for (const node of activeNodes) {
- const highlight = hit.kind === 'node' && node === layout.nodes[hit.index]
- const highlightBase = highlight ? parseableColor(ctx, node.color) : null
+ for (const node of emphasis.nodes) {
+ // A translucent node repainted over itself compounds its alpha, so it keeps its resting paint.
+ if ((d3Color(node.color)?.opacity ?? 1) < 1) {
+ continue
+ }
+ const highlightBase = node === emphasis.focus ? parseableColor(ctx, node.color) : null
const color = highlightBase
? mixColors(highlightBase, HOVER_HIGHLIGHT_TARGET, HOVER_HIGHLIGHT_AMOUNT * options.progress)
: node.color
fillNode(ctx, node, color)
}
+}
+
+/** Static layer: every ribbon under every node, in input order. With `emphasis`, the graph is
+ * painted already dimmed around that set, which is how a controlled highlight shows. */
+export function drawSankey(
+ ctx: CanvasRenderingContext2D,
+ layout: SankeyChartLayout,
+ options: DrawSankeyOptions & { emphasis?: SankeyEmphasis | null; backgroundColor?: string }
+): void {
+ for (const link of layout.links) {
+ strokeLink(ctx, link, link.color, options.linkOpacity)
+ }
+ for (const node of layout.nodes) {
+ fillNode(ctx, node, node.color)
+ }
+ if (options.emphasis) {
+ paintEmphasis(ctx, layout, options.emphasis, {
+ linkOpacity: options.linkOpacity,
+ dimTarget: options.backgroundColor || HOVER_DIM_TARGET_FALLBACK,
+ progress: 1,
+ })
+ }
+}
+
+/** Hover layer: dims the graph toward the background, then repaints the hovered flow (from
+ * `emphasisForHit`) at full strength. Returns false when nothing is hovered. */
+export function drawSankeyHover(
+ ctx: CanvasRenderingContext2D,
+ layout: SankeyChartLayout,
+ emphasis: SankeyEmphasis | null,
+ options: DrawSankeyOptions & { backgroundColor?: string; progress: number }
+): boolean {
+ if (!emphasis) {
+ return false
+ }
+ paintEmphasis(ctx, layout, emphasis, {
+ linkOpacity: options.linkOpacity,
+ dimTarget: options.backgroundColor || HOVER_DIM_TARGET_FALLBACK,
+ progress: options.progress,
+ })
return true
}
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 fa00de8775af..d02402262a7a 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
@@ -46,6 +46,8 @@ describe('computeSankeyLayout', () => {
expect(byId.done.value).toBe(40)
// The total is the inflow of the source nodes, which is what shares are measured against.
expect(layout.total).toBe(40)
+ // `SankeyHighlight.linkIndices` and click handlers address links by input position.
+ expect(layout.links.map((l) => [l.source.id, l.target.id])).toEqual(LINKS.map((l) => [l.source, l.target]))
})
it('places a flow that ends early by alignment: justify, left, and right', () => {
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 38145503bfb1..5477b70e8aac 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts
@@ -34,6 +34,8 @@ export interface SankeyNodeDatum<Meta = unknown> {
label: string
color: string
meta?: Meta
+ /** Position in the `nodes` prop and in `layout.nodes`. */
+ index: number
column: number
/** Sum of the larger side's link values (in or out). */
value: number
@@ -51,6 +53,8 @@ export interface SankeyLinkDatum<NodeMeta = unknown, LinkMeta = NodeMeta> {
value: number
color: string
meta?: LinkMeta
+ /** Position in the `links` prop and in `layout.links`; what `SankeyHighlight.linkIndices` names. */
+ index: number
y0: number
y1: number
width: number
@@ -233,6 +237,7 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
label: node.label,
color: node.color,
meta: node.meta as NodeMeta | undefined,
+ index: node.index,
column: node.layer,
value: node.value,
x0: node.x0,
@@ -244,7 +249,7 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
return datum
})
- const outLinks = graph.links.map((link): SankeyLinkDatum<NodeMeta, LinkMeta> => {
+ const outLinks = graph.links.map((link, index): SankeyLinkDatum<NodeMeta, LinkMeta> => {
const source = datumByIndex.get(link.source.index)!
const target = datumByIndex.get(link.target.index)!
return {
@@ -253,6 +258,7 @@ export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({
value: link.value,
color: link.color ? resolveColor(link.color) : source.color,
meta: link.meta as LinkMeta | undefined,
+ index,
y0: link.y0,
y1: link.y1,
width: link.width,
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
index 59fc9d715cf1..6a1497df1ef0 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
@@ -14,6 +14,13 @@ export type SankeyTooltipContext<NodeMeta = unknown, LinkMeta = NodeMeta> = Tool
total: number
}
+/** A consumer-chosen part of the graph to keep at full strength while the rest dims. Nodes are
+ * named by id; links by their index in the `links` prop, which the layout keeps. */
+export interface SankeyHighlight {
+ nodeIds: ReadonlySet<string>
+ linkIndices: ReadonlySet<number>
+}
+
export interface SankeyChartConfig {
/** Node rectangle width in px. Defaults to 12. */
nodeWidth?: number
@@ -54,6 +61,14 @@ export interface SankeyChartProps<NodeMeta = unknown, LinkMeta = NodeMeta> {
tooltip?: (ctx: SankeyTooltipContext<NodeMeta, LinkMeta>) => React.ReactNode
onNodeClick?: (node: SankeyNodeDatum<NodeMeta>) => void
onLinkClick?: (link: SankeyLinkDatum<NodeMeta, LinkMeta>) => void
+ /** Fires when the cursor moves onto a different node or ribbon or a touch tap lands on one, and
+ * with `null` when the cursor leaves the graph, a tap lands on empty space, or the layout
+ * changes. Lets a host drive its own emphasis, for example through `highlight`. */
+ onHoverChange?: (hit: SankeyTooltipHit<NodeMeta, LinkMeta> | null) => void
+ /** Controlled emphasis. While set, the chart dims everything outside this set and the built-in
+ * hover dimming is off, so the host decides what a hover means (the whole downstream path, a
+ * selection). Pass `null` to hand emphasis back to the hover. */
+ highlight?: SankeyHighlight | null
className?: string
dataAttr?: string
/** Overlays rendered above the canvas. Read the layout with `useSankeyLayout()`. */
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts b/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts
index 77066c9e06eb..e623b8320145 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts
@@ -1,6 +1,6 @@
-import React, { useCallback, useEffect, useMemo } from 'react'
+import React, { useCallback, useEffect, useMemo, useRef } from 'react'
-import { originatesInInteractiveOverlay } from '../../core/hooks/useChartInteraction'
+import { originatesInInteractiveOverlay } from '../../core/dom-events'
import { useLatest } from '../../core/hooks/useLatest'
import { useTapTracking } from '../../core/hooks/useTapTracking'
import { useTooltipLifecycle } from '../../core/hooks/useTooltipLifecycle'
@@ -16,6 +16,11 @@ interface UseSankeyInteractionOptions<NodeMeta, LinkMeta> {
showTooltip: boolean
onNodeClick?: (node: SankeyNodeDatum<NodeMeta>) => void
onLinkClick?: (link: SankeyLinkDatum<NodeMeta, LinkMeta>) => void
+ onHoverChange?: (hit: SankeyTooltipHit<NodeMeta, LinkMeta> | null) => void
+}
+
+function hitKey(hit: SankeyHit | null): string | null {
+ return hit ? `${hit.kind}:${hit.index}` : null
}
interface UseSankeyInteractionResult<NodeMeta, LinkMeta> {
@@ -82,9 +87,35 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
showTooltip,
onNodeClick,
onLinkClick,
+ onHoverChange,
}: UseSankeyInteractionOptions<NodeMeta, LinkMeta>): UseSankeyInteractionResult<NodeMeta, LinkMeta> {
type Ctx = SankeyTooltipContext<NodeMeta, LinkMeta>
const layoutRef = useLatest(layout)
+ 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)
+
+ // A new layout rebuilds nodes/links with fresh objects, so a stale key can coincidentally
+ // match the next real hit and suppress the hover callback the consumer needs to update. The
+ // reported hit is gone with the old layout, so the host hears that too.
+ useEffect(() => {
+ if (reportedHitRef.current !== null) {
+ reportedHitRef.current = null
+ onHoverChangeRef.current?.(null)
+ }
+ }, [layout, onHoverChangeRef])
+
+ const reportHover = useCallback(
+ (hit: SankeyHit | null) => {
+ const key = hitKey(hit)
+ if (key === reportedHitRef.current) {
+ return
+ }
+ reportedHitRef.current = key
+ onHoverChangeRef.current?.(hit ? resolveHit(layoutRef.current, hit) : null)
+ },
+ [onHoverChangeRef, layoutRef]
+ )
const rebuildPinnedCtx = useCallback(
(prev: TooltipContext<NodeMeta | LinkMeta>): Ctx | null => {
@@ -122,28 +153,38 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
const showHit = useCallback(
(hit: SankeyHit, cursor: { x: number; y: number }) => {
- setHover(hitToHoverIndex(layoutRef.current, hit), cursor)
- if (!showTooltip) {
+ // Only the tooltip reads the cursor position. Without one, a constant position lets React skip
+ // the state update on every mouse move inside the same node or ribbon.
+ setHover(hitToHoverIndex(layoutRef.current, hit), showTooltip ? cursor : null)
+ if (showTooltip) {
+ const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()
+ setTooltipCtx(buildTooltipCtx(layoutRef.current, hit, cursor, canvasBounds))
+ } else {
setTooltipCtx(null)
- return
}
- const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()
- setTooltipCtx(buildTooltipCtx(layoutRef.current, hit, cursor, canvasBounds))
+ reportHover(hit)
},
- [layoutRef, showTooltip, setHover, setTooltipCtx, canvasRef]
+ [layoutRef, showTooltip, setHover, setTooltipCtx, canvasRef, reportHover]
)
const onMouseMove = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
const current = layoutRef.current
if (current.nodes.length === 0) {
+ reportHover(null)
+ return
+ }
+ if (originatesInInteractiveOverlay(e)) {
+ clearTooltip()
+ reportHover(null)
return
}
const rect = e.currentTarget.getBoundingClientRect()
const cursor = { x: e.clientX - rect.left, y: e.clientY - rect.top }
- const hit = originatesInInteractiveOverlay(e) ? null : sankeyHitAt(current, cursor)
+ const hit = sankeyHitAt(current, cursor)
if (!hit) {
clearTooltip()
+ reportHover(null)
return
}
showHit(hit, cursor)
@@ -153,7 +194,8 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
const onMouseLeave = useCallback(() => {
clearTooltip()
- }, [clearTooltip])
+ reportHover(null)
+ }, [clearTooltip, reportHover])
// As on the cartesian charts, the first tap on a node or ribbon shows its tooltip and only a
// tap on the element already showing one fires the click handler.
@@ -161,7 +203,12 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
const onClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
+ // A click or tap meant for an overlay control must not act on the node behind it.
if (originatesInInteractiveOverlay(e)) {
+ if (lastPointerTypeRef.current === 'touch') {
+ clearTooltip()
+ reportHover(null)
+ }
return
}
const current = layoutRef.current
@@ -172,6 +219,7 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
hit = sankeyHitAt(current, cursor)
if (!hit) {
clearTooltip()
+ reportHover(null)
return
}
if (hitToHoverIndex(current, hit) !== tapDownTooltipIndexRef.current) {
@@ -197,6 +245,7 @@ export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({
lastPointerTypeRef,
tapDownTooltipIndexRef,
clearTooltip,
+ reportHover,
showHit,
showTooltip,
onNodeClick,
diff --git a/packages/quill/packages/charts/src/core/dom-events.ts b/packages/quill/packages/charts/src/core/dom-events.ts
new file mode 100644
index 000000000000..bf49def408c9
--- /dev/null
+++ b/packages/quill/packages/charts/src/core/dom-events.ts
@@ -0,0 +1,13 @@
+import type React from 'react'
+
+export function originatesInElement(e: React.SyntheticEvent, selector: string): boolean {
+ return e.target instanceof Element && !!e.target.closest(selector)
+}
+
+/** An interactive overlay child (a clickable marker, a node card) renders inside the same wrapper
+ * the chart's mousemove handler is bound to, so every hover over it still bubbles there. Without
+ * this guard the chart's own hover tracking fights the overlay for the cursor. An overlay opts out
+ * by marking its interactive root with this attribute. */
+export function originatesInInteractiveOverlay(e: React.SyntheticEvent): boolean {
+ return originatesInElement(e, '[data-hog-charts-interactive-overlay]')
+}
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
index 1908b8c238ee..dfe6aaf0f663 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
@@ -1,6 +1,7 @@
import React, { useCallback, useMemo } from 'react'
import { findClosestSeriesKey } from '../../overlays/tooltipUtils'
+import { originatesInElement, originatesInInteractiveOverlay } from '../dom-events'
import {
buildLabelPositions,
buildPointClickData,
@@ -25,10 +26,6 @@ import { useLatest } from './useLatest'
import { useTapTracking } from './useTapTracking'
import { useTooltipLifecycle } from './useTooltipLifecycle'
-function originatesInElement(e: React.SyntheticEvent, selector: string): boolean {
- return e.target instanceof Element && !!e.target.closest(selector)
-}
-
/** The tooltip is portaled out of the wrapper's DOM tree, but React portals still bubble
* synthetic events through the React tree — so a click or drag that starts inside the pinned
* tooltip reaches the wrapper's handlers and would dismiss the pin or start a zoom drag. */
@@ -36,15 +33,6 @@ function originatesInTooltip(e: React.SyntheticEvent): boolean {
return originatesInElement(e, '[data-hog-charts-tooltip]')
}
-/** An interactive overlay child (e.g. a clickable exemplar marker) renders inside the same
- * wrapper this hook's mousemove handler is bound to, so every hover over it still bubbles here.
- * Without this guard the chart's own nearest-point tooltip fights the overlay child's tooltip
- * for the cursor. An overlay opts out of chart hover tracking by marking its interactive root
- * with this attribute. */
-export function originatesInInteractiveOverlay(e: React.SyntheticEvent): boolean {
- return originatesInElement(e, '[data-hog-charts-interactive-overlay]')
-}
-
interface UseChartInteractionOptions<Meta> {
scales: ChartScales | null
dimensions: ChartDimensions | null
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
index cdec9f04bbc5..d4c7f7fd52f1 100644
--- a/packages/quill/packages/charts/src/docs/chart-types.md
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -107,7 +107,11 @@ There is no `series` or `labels`.
`onNodeClick` and `onLinkClick` receive the laid-out datum with its `meta`.
`tooltip.placement` takes the cartesian charts' values and defaults to `cursor`.
On touch, the first tap on a node or ribbon shows its tooltip and a second tap on the same one fires the click handler.
+- `onHoverChange` reports the node or ribbon under the cursor or a touch tap, and `null` when the cursor leaves, a tap lands on empty space, or the layout changes.
+ `highlight` takes over emphasis: the chart dims everything outside `{ nodeIds, linkIndices }` and stops its own hover dimming, so a host can light up a whole downstream path or a selection.
+ Link indices are positions in the `links` prop; the layout keeps that order.
- Custom overlays read `useSankeyLayout()` for the positioned `nodes`, `links`, `columnX`, and `total`.
+ An overlay with its own pointer handling marks its root with `data-hog-charts-interactive-overlay`, which also stops the chart from reporting a hover while the cursor is on it.
- The layout engine ships on its own as `sankeyLayout` (plus the `sankeyLeft` / `sankeyJustify` alignments and `sankeyLinkHorizontal`) for hosts that draw their own SVG.
It does not validate its input: the checks above run in `computeSankeyLayout`, so a host that calls the engine directly validates its own graph.
Links resolve their endpoints by array index by default; for links that name string node ids, call `sankeyLayout().nodeId((node) => node.id)` first.
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index 41993fcb728b..d2c82a38475d 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -122,6 +122,7 @@ export { SankeyChart } from './charts/SankeyChart/SankeyChart'
export type {
SankeyChartConfig,
SankeyChartProps,
+ SankeyHighlight,
SankeyTooltipContext,
SankeyTooltipHit,
} from './charts/SankeyChart/types'
diff --git a/products/product_analytics/frontend/insights/paths/PathNodeCard.tsx b/products/product_analytics/frontend/insights/paths/PathNodeCard.tsx
index d0ac79e97599..708894668d47 100644
--- a/products/product_analytics/frontend/insights/paths/PathNodeCard.tsx
+++ b/products/product_analytics/frontend/insights/paths/PathNodeCard.tsx
@@ -93,7 +93,7 @@ export function PathNodeCard({
onMouseLeaveInside={onMouseLeave}
>
<div
- className={`PathNodeCard absolute rounded bg-surface-primary p-1${node.active ? ' PathNodeCard--active' : ''}`}
+ className={`PathNodeCard absolute rounded bg-surface-primary p-1 pointer-events-auto${node.active ? ' PathNodeCard--active' : ''}`}
// eslint-disable-next-line react/forbid-dom-props
style={getCardStyle(
node,
@@ -102,6 +102,9 @@ export function PathNodeCard({
canvasHeight
)}
data-attr="path-node-card-button"
+ // Inside the chart overlay, the card owns the cursor: the chart stops hit-testing
+ // the nodes and ribbons under it.
+ data-hog-charts-interactive-overlay
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
diff --git a/products/product_analytics/frontend/insights/paths/PathNodeCardMenu.tsx b/products/product_analytics/frontend/insights/paths/PathNodeCardMenu.tsx
index 9fee51ecdfe9..7a934322870c 100644
--- a/products/product_analytics/frontend/insights/paths/PathNodeCardMenu.tsx
+++ b/products/product_analytics/frontend/insights/paths/PathNodeCardMenu.tsx
@@ -38,6 +38,9 @@ export function PathNodeCardMenu({
return (
<div
+ // The popover is portaled out of the card but its events still bubble through the chart,
+ // so it needs the same overlay mark as the card.
+ data-hog-charts-interactive-overlay
// eslint-disable-next-line react/forbid-dom-props
style={{ width: PATH_NODE_CARD_WIDTH }}
>
diff --git a/products/product_analytics/frontend/insights/paths/PathNodeCards.tsx b/products/product_analytics/frontend/insights/paths/PathNodeCards.tsx
new file mode 100644
index 000000000000..86596b266379
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/PathNodeCards.tsx
@@ -0,0 +1,47 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useMemo } from 'react'
+
+import { useChartLayout, useSankeyLayout } from '@posthog/quill-charts'
+
+import { PathsLink } from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+import { PathNodeCard } from './PathNodeCard'
+import { toPathNodeData } from './pathsChartData'
+import { pathsInteractionLogic } from './pathsInteractionLogic'
+
+export interface PathNodeCardsProps {
+ insightProps: InsightLogicProps
+}
+
+/** Chart overlay: hands the laid-out nodes to the interaction logic and renders one card per
+ * node the logic decides to show. */
+export function PathNodeCards({ insightProps }: PathNodeCardsProps): JSX.Element {
+ const { layout } = useSankeyLayout<unknown, PathsLink>()
+ const { dimensions } = useChartLayout()
+ const interactionLogic = pathsInteractionLogic(insightProps)
+ const { resolvedNodeCards, cardPopoverIndex } = useValues(interactionLogic)
+ const { setNodes, hoverCard, unhoverCard } = useActions(interactionLogic)
+
+ const nodes = useMemo(() => toPathNodeData(layout), [layout])
+ const canvasHeight = dimensions.plotTop + dimensions.plotHeight
+ useEffect(() => {
+ setNodes(nodes, canvasHeight)
+ }, [nodes, canvasHeight, setNodes])
+
+ return (
+ <>
+ {resolvedNodeCards.map((node) => (
+ <PathNodeCard
+ key={node.index}
+ node={node}
+ insightProps={insightProps}
+ canvasHeight={canvasHeight}
+ popoverVisible={cardPopoverIndex === node.index}
+ onMouseEnter={() => hoverCard(node.index)}
+ onMouseLeave={unhoverCard}
+ />
+ ))}
+ </>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/paths/Paths.stories.tsx b/products/product_analytics/frontend/insights/paths/Paths.stories.tsx
index 9a31eb6e6041..91848ec86338 100644
--- a/products/product_analytics/frontend/insights/paths/Paths.stories.tsx
+++ b/products/product_analytics/frontend/insights/paths/Paths.stories.tsx
@@ -1,6 +1,7 @@
import { Meta, StoryObj } from '@storybook/react'
import { waitFor } from '@testing-library/react'
+import { FEATURE_FLAGS } from 'lib/constants'
import {
createInsightStory,
insightSceneMswDecorator,
@@ -42,6 +43,13 @@ export const UserPaths: Story = {
),
}
+export const UserPathsSankeyChart: Story = {
+ ...UserPaths,
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_SANKEY_CHART],
+ },
+}
+
// The Paths component uses useResizeObserver to measure canvasWidth/canvasHeight, then destroys
// and recreates the SVG when they change (or when theme/data changes). Dimension updates are
// debounced to reduce recreations. The canvas div gets data-stable removed during recreation
diff --git a/products/product_analytics/frontend/insights/paths/Paths.tsx b/products/product_analytics/frontend/insights/paths/Paths.tsx
index 46b977d96761..80920f76d17d 100644
--- a/products/product_analytics/frontend/insights/paths/Paths.tsx
+++ b/products/product_analytics/frontend/insights/paths/Paths.tsx
@@ -1,171 +1,30 @@
-import './Paths.scss'
+import { useValues } from 'kea'
+import { Suspense, lazy } from 'react'
-import { useActions, useValues } from 'kea'
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { retryImport } from 'lib/utils/retryImport'
-import { useResizeObserver } from 'lib/hooks/useResizeObserver'
-import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
-import { insightDataLogic } from 'scenes/insights/insightDataLogic'
-import { insightLogic } from 'scenes/insights/insightLogic'
+import { PathsLegacy } from './PathsLegacy'
-import { FunnelPathsFilter } from '~/queries/schema/schema-general'
-import { shouldQueryBeAsync } from '~/queries/utils'
-
-import { PathNodeCard } from './PathNodeCard'
-import { pathsDataLogic } from './pathsDataLogic'
-import { pathsInteractionLogic } from './pathsInteractionLogic'
-import type { PathNodeData } from './pathUtils'
-import type { PathsHoverHandlers } from './renderPaths'
-// eslint-disable-next-line import/no-cycle
-import { renderPaths } from './renderPaths'
-
-const DEFAULT_PATHS_ID = 'default_paths'
-export const HIDE_PATH_CARD_HEIGHT = 30
-export const FALLBACK_CANVAS_WIDTH = 1000
-const FALLBACK_CANVAS_HEIGHT = 0
-const CANVAS_RESIZE_DEBOUNCE_MS = 50
+// Loaded on demand so users on the legacy renderer do not download the Sankey chart.
+const PathsChart = lazy(() => retryImport(() => import('./PathsChart').then((m) => ({ default: m.PathsChart }))))
export function Paths(): JSX.Element {
- const canvasRef = useRef<HTMLDivElement>(null)
- const canvasContainerRef = useRef<HTMLDivElement>(null)
- const { width: rawCanvasWidth, height: rawCanvasHeight } = useResizeObserver({ ref: canvasRef })
- const [canvasWidth, setCanvasWidth] = useState(FALLBACK_CANVAS_WIDTH)
- const [canvasHeight, setCanvasHeight] = useState(FALLBACK_CANVAS_HEIGHT)
-
- // Debounce canvas dimension updates to prevent rapid SVG recreation from ResizeObserver.
- // We do NOT remove data-stable here — the render effect below removes it only when the SVG
- // is actually being recreated. Removing it here would cause data-stable to disappear for the
- // entire debounce window on every resize, making Playwright's waitForSelector time out.
- useEffect(() => {
- const timer = setTimeout(() => {
- setCanvasWidth(rawCanvasWidth ?? FALLBACK_CANVAS_WIDTH)
- setCanvasHeight(rawCanvasHeight ?? FALLBACK_CANVAS_HEIGHT)
- }, CANVAS_RESIZE_DEBOUNCE_MS)
- return () => clearTimeout(timer)
- }, [rawCanvasWidth, rawCanvasHeight])
-
- const { insight, insightProps } = useValues(insightLogic)
- const { insightQuery, paths, pathsFilter, funnelPathsFilter, insightDataLoading, insightDataError, theme } =
- useValues(pathsDataLogic(insightProps))
- const { loadData } = useActions(insightDataLogic(insightProps))
-
- const interactionLogic = pathsInteractionLogic(insightProps)
- const { resolvedNodeCards, activeIndices, cardPopoverIndex } = useValues(interactionLogic)
- const { setNodes, hoverNode, hoverLink, clearHover, requestClearHover, hoverCard, unhoverCard } =
- useActions(interactionLogic)
-
- // The handlers must keep their identity for the lifetime of the component. They are a
- // dependency of the render effect below, so a new object there tears the SVG out from under
- // the pointer and clears the hover that had just been set. Anything that changes is read
- // when the handler runs, not when it is built.
- const canvasHeightRef = useRef(canvasHeight)
- canvasHeightRef.current = canvasHeight
- const hoverHandlers = useMemo<PathsHoverHandlers>(
- () => ({
- onNodesReady: (nodes: PathNodeData[]) => setNodes(nodes, canvasHeightRef.current),
- onNodeHover: hoverNode,
- onLinkHover: hoverLink,
- onHoverClear: requestClearHover,
- isCardHovered: () => interactionLogic.values.cardHovered,
- }),
- [interactionLogic, setNodes, hoverNode, hoverLink, requestClearHover]
- )
-
- useLayoutEffect(() => {
- canvasRef.current?.querySelectorAll<SVGPathElement>('path[id^="path-"]').forEach((el) => {
- const pathIndex = Number(el.id.replace('path-', ''))
- el.setAttribute(
- 'stroke',
- activeIndices.linkIndices.has(pathIndex) ? 'var(--paths-link-hover)' : 'var(--paths-link)'
- )
- })
- }, [activeIndices])
-
- const id = `'${insight?.short_id || DEFAULT_PATHS_ID}'`
-
- useEffect(() => {
- clearHover()
-
- const elements = canvasContainerRef.current?.querySelectorAll(`.Paths__canvas`)
- elements?.forEach((node) => node?.parentNode?.removeChild(node))
-
- if (canvasRef.current) {
- canvasRef.current.removeAttribute('data-stable')
- }
-
- renderPaths(
- canvasRef,
- canvasWidth,
- canvasHeight,
- paths,
- pathsFilter || {},
- funnelPathsFilter || ({} as FunnelPathsFilter),
- hoverHandlers
- )
-
- if (canvasRef.current) {
- canvasRef.current.setAttribute('data-stable', 'true')
- }
-
- return () => {
- const elements = canvasContainerRef.current?.querySelectorAll(`.Paths__canvas`)
- elements?.forEach((node) => node?.parentNode?.removeChild(node))
- }
- }, [
- paths,
- insightDataLoading,
- canvasWidth,
- canvasHeight,
- theme,
- pathsFilter,
- funnelPathsFilter,
- hoverHandlers,
- clearHover,
- ])
-
- if (insightDataError) {
- return (
- <InsightErrorState
- query={insightQuery}
- excludeDetail
- onRetry={() => {
- loadData(shouldQueryBeAsync(insightQuery) ? 'force_async' : 'force_blocking')
- }}
- />
- )
+ const { featureFlags } = useValues(featureFlagLogic)
+ if (!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_SANKEY_CHART]) {
+ return <PathsLegacy />
}
-
return (
- <div className="h-full w-full overflow-auto" id={id} ref={canvasContainerRef}>
- <div
- ref={canvasRef}
- className="Paths"
- data-attr="paths-viz"
- // eslint-disable-next-line react/forbid-dom-props
- style={
- {
- '--paths-node': theme?.['preset-1'] || '#000000',
- '--paths-node-start-or-end': theme?.['preset-2'] || '#000000',
- '--paths-link': theme?.['preset-1'] || '#000000',
- '--paths-link-hover': theme?.['preset-2'] || '#000000',
- '--paths-dropoff': 'rgba(220,53,69,0.7)',
- } as React.CSSProperties
- }
- >
- {!insightDataLoading && paths && paths.nodes.length === 0 && !insightDataError && <InsightEmptyState />}
- {!insightDataError &&
- resolvedNodeCards.map((node, idx) => (
- <PathNodeCard
- key={idx}
- node={node}
- insightProps={insightProps}
- canvasHeight={canvasHeight}
- popoverVisible={cardPopoverIndex === node.index}
- onMouseEnter={() => hoverCard(node.index)}
- onMouseLeave={unhoverCard}
- />
- ))}
- </div>
- </div>
+ <Suspense
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner />
+ </div>
+ }
+ >
+ <PathsChart />
+ </Suspense>
)
}
diff --git a/products/product_analytics/frontend/insights/paths/PathsChart.tsx b/products/product_analytics/frontend/insights/paths/PathsChart.tsx
new file mode 100644
index 000000000000..310c14e18e69
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/PathsChart.tsx
@@ -0,0 +1,161 @@
+import './Paths.scss'
+
+import { useActions, useValues } from 'kea'
+import { useCallback, useMemo, useRef } from 'react'
+
+import { SankeyChart } from '@posthog/quill-charts'
+import type { SankeyChartConfig, SankeyHighlight, SankeyTooltipHit } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { useResizeObserver } from 'lib/hooks/useResizeObserver'
+import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
+import { insightDataLogic } from 'scenes/insights/insightDataLogic'
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { PathsLink } from '~/queries/schema/schema-general'
+import { shouldQueryBeAsync } from '~/queries/utils'
+
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
+
+import { FALLBACK_CANVAS_WIDTH } from './constants'
+import { PathNodeCards } from './PathNodeCards'
+import { buildPathsGraph, maxPathLayer, pathsChartWidth } from './pathsChartData'
+import type { PathsGraphColors } from './pathsChartData'
+import { PathsColumnDividers } from './PathsColumnDividers'
+import { pathsDataLogic } from './pathsDataLogic'
+import { PathsDropoffs } from './PathsDropoffs'
+import { pathsInteractionLogic } from './pathsInteractionLogic'
+
+const DEFAULT_PATHS_ID = 'default_paths'
+const FALLBACK_COLOR = '#000000'
+const NO_MARGINS = { top: 0, right: 0, bottom: 0, left: 0 }
+const handleChartError = makeChartErrorHandler('paths-sankey-chart')
+
+// The cards carry every label and number, so the chart draws bare nodes and ribbons. Node order
+// follows the result, as the SVG renderer did, so the two renderers agree on where a step sits.
+const CHART_CONFIG: SankeyChartConfig = {
+ nodeWidth: 15,
+ nodePadding: 8,
+ nodeAlign: 'justify',
+ preserveNodeOrder: true,
+ showNodeLabels: false,
+ linkOpacity: 0.35,
+ tooltip: { enabled: false },
+ margins: NO_MARGINS,
+}
+
+/** The paths insight on the quill `SankeyChart`. The chart lays out and paints the graph; the
+ * cards, drop-offs, and hover emphasis stay with the paths logic through overlays. */
+export function PathsChart(): JSX.Element {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const { width: containerWidth } = useResizeObserver({ ref: containerRef })
+
+ const { insight, insightProps } = useValues(insightLogic)
+ const { insightQuery, paths, pathsFilter, funnelPathsFilter, insightDataLoading, insightDataError, theme } =
+ useValues(pathsDataLogic(insightProps))
+ const { loadData } = useActions(insightDataLogic(insightProps))
+ const interactionLogic = pathsInteractionLogic(insightProps)
+ const { activeIndices, nodes } = useValues(interactionLogic)
+ const { hoverNode, hoverLink, requestClearHover } = useActions(interactionLogic)
+ const chartTheme = useChartTheme()
+
+ const colors = useMemo<PathsGraphColors>(
+ () => ({
+ node: theme?.['preset-1'] || FALLBACK_COLOR,
+ selectedNode: theme?.['preset-2'] || FALLBACK_COLOR,
+ link: theme?.['preset-1'] || FALLBACK_COLOR,
+ }),
+ [theme]
+ )
+ const graph = useMemo(
+ () => buildPathsGraph(paths, pathsFilter || {}, funnelPathsFilter || undefined, colors),
+ [paths, pathsFilter, funnelPathsFilter, colors]
+ )
+ const chartWidth = useMemo(
+ () => pathsChartWidth(containerWidth ?? FALLBACK_CANVAS_WIDTH, maxPathLayer(paths)),
+ [containerWidth, paths]
+ )
+
+ const highlight = useMemo<SankeyHighlight | null>(() => {
+ if (activeIndices.nodeIndices.size === 0) {
+ return null
+ }
+ const nodeIds = new Set<string>()
+ for (const node of nodes) {
+ if (activeIndices.nodeIndices.has(node.index)) {
+ nodeIds.add(node.name)
+ }
+ }
+ return { nodeIds, linkIndices: activeIndices.linkIndices }
+ }, [activeIndices, nodes])
+
+ const onHoverChange = useCallback(
+ (hit: SankeyTooltipHit<unknown, PathsLink> | null) => {
+ // A card under the cursor owns the hover until the pointer leaves it.
+ if (interactionLogic.values.cardHovered) {
+ return
+ }
+ if (!hit) {
+ requestClearHover()
+ } else if (hit.kind === 'node') {
+ hoverNode(hit.node.index)
+ } else {
+ hoverLink(hit.link.source.index, hit.link.target.index, hit.link.index)
+ }
+ },
+ [interactionLogic, hoverNode, hoverLink, requestClearHover]
+ )
+
+ if (insightDataError) {
+ return (
+ <InsightErrorState
+ query={insightQuery}
+ excludeDetail
+ onRetry={() => {
+ loadData(shouldQueryBeAsync(insightQuery) ? 'force_async' : 'force_blocking')
+ }}
+ />
+ )
+ }
+
+ const id = `'${insight?.short_id || DEFAULT_PATHS_ID}'`
+ const isEmpty = !insightDataLoading && paths.nodes.length === 0
+
+ return (
+ <div className="h-full w-full overflow-auto" id={id} ref={containerRef}>
+ <div
+ className="Paths"
+ data-attr="paths-viz"
+ // Visual tests wait for this; it appears once the logic holds the laid-out nodes.
+ data-stable={nodes.length > 0 ? 'true' : undefined}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ {
+ width: chartWidth,
+ '--paths-link-hover': colors.selectedNode,
+ '--paths-dropoff': 'rgba(220,53,69,0.7)',
+ } as React.CSSProperties
+ }
+ >
+ {isEmpty ? <InsightEmptyState /> : null}
+ {graph.nodes.length > 0 ? (
+ <SankeyChart<unknown, PathsLink>
+ nodes={graph.nodes}
+ links={graph.links}
+ theme={chartTheme}
+ config={CHART_CONFIG}
+ highlight={highlight}
+ onHoverChange={onHoverChange}
+ onError={handleChartError}
+ className="h-full"
+ dataAttr="paths-sankey-chart"
+ >
+ <PathsDropoffs />
+ <PathsColumnDividers />
+ <PathNodeCards insightProps={insightProps} />
+ </SankeyChart>
+ ) : null}
+ </div>
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/paths/PathsColumnDividers.tsx b/products/product_analytics/frontend/insights/paths/PathsColumnDividers.tsx
new file mode 100644
index 000000000000..c2ad209837c8
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/PathsColumnDividers.tsx
@@ -0,0 +1,22 @@
+import { useSankeyLayout } from '@posthog/quill-charts'
+
+/** Chart overlay: a divider before each step once the chart is wide enough to scroll, so the eye
+ * keeps its place in a long path. */
+export function PathsColumnDividers(): JSX.Element | null {
+ const { layout } = useSankeyLayout()
+ if (layout.columnCount <= 5) {
+ return null
+ }
+ return (
+ <>
+ {layout.columnX.slice(1).map((x, i) => (
+ <div
+ key={i}
+ className="absolute top-0 h-full w-0.5 bg-border-primary"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: x - 20 }}
+ />
+ ))}
+ </>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/paths/PathsDropoffs.tsx b/products/product_analytics/frontend/insights/paths/PathsDropoffs.tsx
new file mode 100644
index 000000000000..924ed690c3d0
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/PathsDropoffs.tsx
@@ -0,0 +1,51 @@
+import { useMemo } from 'react'
+
+import { useSankeyLayout } from '@posthog/quill-charts'
+
+const DROPOFF_WIDTH = 30
+const DROPOFF_MAX_RADIUS = 25
+
+/** Chart overlay: a fading block to the right of each node for the users who did not continue,
+ * sized to the part of the node no outgoing ribbon covers. First-step nodes and path ends get
+ * none, matching the SVG renderer. */
+export function PathsDropoffs(): JSX.Element {
+ const { layout } = useSankeyLayout()
+ const outflow = useMemo(() => {
+ const totals = new Map<string, number>()
+ for (const link of layout.links) {
+ totals.set(link.source.id, (totals.get(link.source.id) ?? 0) + link.width)
+ }
+ return totals
+ }, [layout.links])
+ return (
+ <>
+ {layout.nodes.map((node) => {
+ const continuing = outflow.get(node.id)
+ if (node.column === 0 || continuing === undefined) {
+ return null
+ }
+ const height = node.y1 - node.y0 - continuing
+ if (height < 1) {
+ return null
+ }
+ return (
+ <div
+ key={node.id}
+ // The block covers ribbons the canvas still hit-tests, so it opts out of the
+ // chart's hover tracking to keep a dropped-off area from showing a ribbon.
+ data-hog-charts-interactive-overlay
+ className="absolute bg-gradient-to-b from-[var(--paths-dropoff)] to-[var(--color-bg-surface-primary)]"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ left: Math.round(node.x1),
+ top: Math.round(node.y0 + continuing),
+ width: DROPOFF_WIDTH,
+ height,
+ borderTopRightRadius: Math.min(DROPOFF_MAX_RADIUS, height),
+ }}
+ />
+ )
+ })}
+ </>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/paths/PathsLegacy.tsx b/products/product_analytics/frontend/insights/paths/PathsLegacy.tsx
new file mode 100644
index 000000000000..496333cd118a
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/PathsLegacy.tsx
@@ -0,0 +1,170 @@
+import './Paths.scss'
+
+import { useActions, useValues } from 'kea'
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+
+import { useResizeObserver } from 'lib/hooks/useResizeObserver'
+import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
+import { insightDataLogic } from 'scenes/insights/insightDataLogic'
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { FunnelPathsFilter } from '~/queries/schema/schema-general'
+import { shouldQueryBeAsync } from '~/queries/utils'
+
+import { FALLBACK_CANVAS_WIDTH } from './constants'
+import { PathNodeCard } from './PathNodeCard'
+import { pathsDataLogic } from './pathsDataLogic'
+import { pathsInteractionLogic } from './pathsInteractionLogic'
+import type { PathNodeData } from './pathUtils'
+import type { PathsHoverHandlers } from './renderPaths'
+import { renderPaths } from './renderPaths'
+
+const DEFAULT_PATHS_ID = 'default_paths'
+const FALLBACK_CANVAS_HEIGHT = 0
+const CANVAS_RESIZE_DEBOUNCE_MS = 50
+
+/** The d3 SVG renderer. `Paths` shows it while the `paths-sankey-chart` flag is off. */
+export function PathsLegacy(): JSX.Element {
+ const canvasRef = useRef<HTMLDivElement>(null)
+ const canvasContainerRef = useRef<HTMLDivElement>(null)
+ const { width: rawCanvasWidth, height: rawCanvasHeight } = useResizeObserver({ ref: canvasRef })
+ const [canvasWidth, setCanvasWidth] = useState(FALLBACK_CANVAS_WIDTH)
+ const [canvasHeight, setCanvasHeight] = useState(FALLBACK_CANVAS_HEIGHT)
+
+ // Debounce canvas dimension updates to prevent rapid SVG recreation from ResizeObserver.
+ // We do NOT remove data-stable here — the render effect below removes it only when the SVG
+ // is actually being recreated. Removing it here would cause data-stable to disappear for the
+ // entire debounce window on every resize, making Playwright's waitForSelector time out.
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setCanvasWidth(rawCanvasWidth ?? FALLBACK_CANVAS_WIDTH)
+ setCanvasHeight(rawCanvasHeight ?? FALLBACK_CANVAS_HEIGHT)
+ }, CANVAS_RESIZE_DEBOUNCE_MS)
+ return () => clearTimeout(timer)
+ }, [rawCanvasWidth, rawCanvasHeight])
+
+ const { insight, insightProps } = useValues(insightLogic)
+ const { insightQuery, paths, pathsFilter, funnelPathsFilter, insightDataLoading, insightDataError, theme } =
+ useValues(pathsDataLogic(insightProps))
+ const { loadData } = useActions(insightDataLogic(insightProps))
+
+ const interactionLogic = pathsInteractionLogic(insightProps)
+ const { resolvedNodeCards, activeIndices, cardPopoverIndex } = useValues(interactionLogic)
+ const { setNodes, hoverNode, hoverLink, clearHover, requestClearHover, hoverCard, unhoverCard } =
+ useActions(interactionLogic)
+
+ // The handlers must keep their identity for the lifetime of the component. They are a
+ // dependency of the render effect below, so a new object there tears the SVG out from under
+ // the pointer and clears the hover that had just been set. Anything that changes is read
+ // when the handler runs, not when it is built.
+ const canvasHeightRef = useRef(canvasHeight)
+ canvasHeightRef.current = canvasHeight
+ const hoverHandlers = useMemo<PathsHoverHandlers>(
+ () => ({
+ onNodesReady: (nodes: PathNodeData[]) => setNodes(nodes, canvasHeightRef.current),
+ onNodeHover: hoverNode,
+ onLinkHover: hoverLink,
+ onHoverClear: requestClearHover,
+ isCardHovered: () => interactionLogic.values.cardHovered,
+ }),
+ [interactionLogic, setNodes, hoverNode, hoverLink, requestClearHover]
+ )
+
+ useLayoutEffect(() => {
+ canvasRef.current?.querySelectorAll<SVGPathElement>('path[id^="path-"]').forEach((el) => {
+ const pathIndex = Number(el.id.replace('path-', ''))
+ el.setAttribute(
+ 'stroke',
+ activeIndices.linkIndices.has(pathIndex) ? 'var(--paths-link-hover)' : 'var(--paths-link)'
+ )
+ })
+ }, [activeIndices])
+
+ const id = `'${insight?.short_id || DEFAULT_PATHS_ID}'`
+
+ useEffect(() => {
+ clearHover()
+
+ const elements = canvasContainerRef.current?.querySelectorAll(`.Paths__canvas`)
+ elements?.forEach((node) => node?.parentNode?.removeChild(node))
+
+ if (canvasRef.current) {
+ canvasRef.current.removeAttribute('data-stable')
+ }
+
+ renderPaths(
+ canvasRef,
+ canvasWidth,
+ canvasHeight,
+ paths,
+ pathsFilter || {},
+ funnelPathsFilter || ({} as FunnelPathsFilter),
+ hoverHandlers
+ )
+
+ if (canvasRef.current) {
+ canvasRef.current.setAttribute('data-stable', 'true')
+ }
+
+ return () => {
+ const elements = canvasContainerRef.current?.querySelectorAll(`.Paths__canvas`)
+ elements?.forEach((node) => node?.parentNode?.removeChild(node))
+ }
+ }, [
+ paths,
+ insightDataLoading,
+ canvasWidth,
+ canvasHeight,
+ theme,
+ pathsFilter,
+ funnelPathsFilter,
+ hoverHandlers,
+ clearHover,
+ ])
+
+ if (insightDataError) {
+ return (
+ <InsightErrorState
+ query={insightQuery}
+ excludeDetail
+ onRetry={() => {
+ loadData(shouldQueryBeAsync(insightQuery) ? 'force_async' : 'force_blocking')
+ }}
+ />
+ )
+ }
+
+ return (
+ <div className="h-full w-full overflow-auto" id={id} ref={canvasContainerRef}>
+ <div
+ ref={canvasRef}
+ className="Paths"
+ data-attr="paths-viz"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ {
+ '--paths-node': theme?.['preset-1'] || '#000000',
+ '--paths-node-start-or-end': theme?.['preset-2'] || '#000000',
+ '--paths-link': theme?.['preset-1'] || '#000000',
+ '--paths-link-hover': theme?.['preset-2'] || '#000000',
+ '--paths-dropoff': 'rgba(220,53,69,0.7)',
+ } as React.CSSProperties
+ }
+ >
+ {!insightDataLoading && paths && paths.nodes.length === 0 && !insightDataError && <InsightEmptyState />}
+ {!insightDataError &&
+ resolvedNodeCards.map((node, idx) => (
+ <PathNodeCard
+ key={idx}
+ node={node}
+ insightProps={insightProps}
+ canvasHeight={canvasHeight}
+ popoverVisible={cardPopoverIndex === node.index}
+ onMouseEnter={() => hoverCard(node.index)}
+ onMouseLeave={unhoverCard}
+ />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/paths/constants.ts b/products/product_analytics/frontend/insights/paths/constants.ts
index f3b8ce49361f..42d9fe403cf4 100644
--- a/products/product_analytics/frontend/insights/paths/constants.ts
+++ b/products/product_analytics/frontend/insights/paths/constants.ts
@@ -3,3 +3,6 @@ export const PATH_NODE_CARD_HEIGHT = 38
export const PATH_NODE_CARD_OVERLAP_GAP = 4
export const PATH_NODE_CARD_TOP_OFFSET = 5
export const PATH_NODE_CARD_LEFT_OFFSET = 7
+/** A node shorter than this shows its card only while it is part of the hovered path. */
+export const HIDE_PATH_CARD_HEIGHT = 30
+export const FALLBACK_CANVAS_WIDTH = 1000
diff --git a/products/product_analytics/frontend/insights/paths/pathUtils.ts b/products/product_analytics/frontend/insights/paths/pathUtils.ts
index 45f58648df4b..80541c1e027f 100644
--- a/products/product_analytics/frontend/insights/paths/pathUtils.ts
+++ b/products/product_analytics/frontend/insights/paths/pathUtils.ts
@@ -5,9 +5,12 @@ import { tryDecodeURIComponent } from 'lib/utils/url'
import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
import { FunnelPathType } from '~/types'
-import { PATH_NODE_CARD_HEIGHT, PATH_NODE_CARD_OVERLAP_GAP, PATH_NODE_CARD_TOP_OFFSET } from './constants'
-// eslint-disable-next-line import/no-cycle
-import { HIDE_PATH_CARD_HEIGHT } from './Paths'
+import {
+ HIDE_PATH_CARD_HEIGHT,
+ PATH_NODE_CARD_HEIGHT,
+ PATH_NODE_CARD_OVERLAP_GAP,
+ PATH_NODE_CARD_TOP_OFFSET,
+} from './constants'
const PATH_NODE_CARD_TOP_ADJUSTMENTS = 33
@@ -19,7 +22,7 @@ export interface PathTargetLink {
value: number
width: number
y0: number
- color: RGBColor
+ color?: RGBColor
}
export interface PathNodeData {
@@ -36,13 +39,17 @@ export interface PathNodeData {
y0: number
y1: number
layer: number
- source: PathNodeData
- target: PathNodeData
+ /** Set by the SVG renderer, which types its link data as nodes. */
+ source?: PathNodeData
+ target?: PathNodeData
visible?: boolean
active?: boolean
resolvedTop?: number
}
+/** 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 function getForwardConnectedIndices(startNode: PathNodeData): {
nodeIndices: Set<number>
linkIndices: Set<number>
@@ -97,13 +104,19 @@ const findClosestAvailableCardTop = (
const minimumDistance = PATH_NODE_CARD_HEIGHT + PATH_NODE_CARD_OVERLAP_GAP
const maximumTop = Math.max(0, canvasHeight - PATH_NODE_CARD_HEIGHT)
const clamp = (top: number): number => Math.min(Math.max(top, 0), maximumTop)
+ // A candidate sits within MAXIMUM_CARD_NUDGE of naturalTop, and only a card within
+ // minimumDistance of a candidate can block it, so cards further away cannot change the result.
+ // Skipping them stops a dense layer from checking every card against every candidate.
+ const nearbyTops = occupiedTops.filter(
+ (occupiedTop) => Math.abs(occupiedTop - naturalTop) <= MAXIMUM_CARD_NUDGE + minimumDistance
+ )
const candidateTops = [
clamp(naturalTop),
- ...occupiedTops.flatMap((occupiedTop) => [occupiedTop - minimumDistance, occupiedTop + minimumDistance]),
+ ...nearbyTops.flatMap((occupiedTop) => [occupiedTop - minimumDistance, occupiedTop + minimumDistance]),
].filter((top) => top >= 0 && top <= maximumTop && Math.abs(top - naturalTop) <= MAXIMUM_CARD_NUDGE)
const freeTop = candidateTops
- .filter((top) => occupiedTops.every((occupiedTop) => Math.abs(top - occupiedTop) >= minimumDistance))
+ .filter((top) => nearbyTops.every((occupiedTop) => Math.abs(top - occupiedTop) >= minimumDistance))
.sort((a, b) => Math.abs(a - naturalTop) - Math.abs(b - naturalTop) || a - b)[0]
return freeTop === undefined ? { top: clamp(naturalTop), foundGap: false } : { top: freeTop, foundGap: true }
@@ -204,7 +217,7 @@ export function roundedRect(
export function pageUrl(d: PathNodeData, display?: boolean, showFullUrls?: boolean): string {
const incomingUrls = d.targetLinks
- .map((l) => l?.source?.name?.replace(/(^[0-9]+_)/, ''))
+ .map((l) => stripStepPrefix(l?.source?.name ?? ''))
.filter((a) => {
try {
new URL(a)
@@ -216,7 +229,7 @@ export function pageUrl(d: PathNodeData, display?: boolean, showFullUrls?: boole
.map((a) => new URL(a))
const incomingDomains = Array.from(new Set(incomingUrls.map((url) => url.origin)))
- let name = d.name.replace(/(^[0-9]+_)/, '')
+ let name = stripStepPrefix(d.name)
if (!display) {
return name
@@ -240,30 +253,46 @@ export function pageUrl(d: PathNodeData, display?: boolean, showFullUrls?: boole
return name.length > 15
? name.substring(0, 6) + '...' + name.slice(-8)
: name.length < 4 && d.name.length < 25
- ? d.name.replace(/(^[0-9]+_)/, '')
+ ? stripStepPrefix(d.name)
: name
}
-export const isSelectedPathStartOrEnd = (
+export interface PathEndpoint {
+ /** The node name without its step prefix. */
+ name: string
+ isPathStart: boolean
+ isPathEnd: boolean
+}
+
+/** Whether the node is the start or end point the filter selected, so it draws in the accent color. */
+export const isSelectedPathEndpoint = (
pathsFilter: PathsFilter,
- funnelPathsFilter: FunnelPathsFilter,
- pathItemCard: PathNodeData
+ funnelPathsFilter: FunnelPathsFilter | undefined,
+ { name, isPathStart, isPathEnd }: PathEndpoint
): boolean => {
- const cardName = pageUrl(pathItemCard)
- const isPathStart = pathItemCard.targetLinks.length === 0
- const isPathEnd = pathItemCard.sourceLinks.length === 0
const { startPoint, endPoint } = pathsFilter
const { funnelPathType, funnelSource, funnelStep } = funnelPathsFilter || {}
return (
- (startPoint === cardName && isPathStart) ||
- (endPoint === cardName && isPathEnd) ||
+ (startPoint === name && isPathStart) ||
+ (endPoint === name && isPathEnd) ||
(funnelPathType === FunnelPathType.between &&
- ((cardName === funnelSource?.series[funnelStep! - 1].name && isPathEnd) ||
- (cardName === funnelSource?.series[funnelStep! - 2].name && isPathStart)))
+ ((name === funnelSource?.series[funnelStep! - 1].name && isPathEnd) ||
+ (name === funnelSource?.series[funnelStep! - 2].name && isPathStart)))
)
}
+export const isSelectedPathStartOrEnd = (
+ pathsFilter: PathsFilter,
+ funnelPathsFilter: FunnelPathsFilter,
+ pathItemCard: PathNodeData
+): boolean =>
+ isSelectedPathEndpoint(pathsFilter, funnelPathsFilter, {
+ name: pageUrl(pathItemCard),
+ isPathStart: pathItemCard.targetLinks.length === 0,
+ isPathEnd: pathItemCard.sourceLinks.length === 0,
+ })
+
export const calculatePathNodeCardTop = (node: PathNodeData, canvasHeight: number): number => {
const isNodeCutoff = node.y1 - node.y0 < HIDE_PATH_CARD_HEIGHT && node.y1 > canvasHeight - HIDE_PATH_CARD_HEIGHT
const isPathEnd = node.sourceLinks.length === 0
diff --git a/products/product_analytics/frontend/insights/paths/pathsChartData.test.ts b/products/product_analytics/frontend/insights/paths/pathsChartData.test.ts
new file mode 100644
index 000000000000..d4d88a1b0ace
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/pathsChartData.test.ts
@@ -0,0 +1,89 @@
+import type { SankeyChartLayout, SankeyLinkDatum, SankeyNodeDatum } from '@posthog/quill-charts'
+
+import { PathsLink } from '~/queries/schema/schema-general'
+
+import { buildPathsGraph, maxPathLayer, pathsChartWidth, toPathNodeData } from './pathsChartData'
+import { Paths } from './types'
+
+const COLORS = { node: '#111111', selectedNode: '#222222', link: '#333333' }
+
+const LINKS: PathsLink[] = [
+ { source: '1_/home', target: '2_/pricing', value: 30, average_conversion_time: 4000 },
+ { source: '1_/home', target: '2_/docs', value: 10, average_conversion_time: 2000 },
+ { source: '2_/pricing', target: '3_/signup', value: 12, average_conversion_time: 9000 },
+]
+const PATHS: Paths = {
+ nodes: [{ name: '1_/home' }, { name: '2_/pricing' }, { name: '2_/docs' }, { name: '3_/signup' }],
+ links: LINKS,
+}
+
+function layoutOf(paths: Paths): SankeyChartLayout<unknown, PathsLink> {
+ const nodes = paths.nodes.map(
+ (node, index): SankeyNodeDatum => ({
+ id: node.name,
+ label: node.name,
+ color: '#000',
+ index,
+ column: Number(node.name.match(/[^_]*/)) - 1,
+ value: 40,
+ x0: index * 100,
+ x1: index * 100 + 15,
+ y0: 0,
+ y1: 40,
+ })
+ )
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const links = paths.links.map(
+ (link, index): SankeyLinkDatum<unknown, PathsLink> => ({
+ source: byId.get(link.source)!,
+ target: byId.get(link.target)!,
+ value: link.value,
+ color: '#000',
+ meta: link,
+ index,
+ y0: 0,
+ y1: 0,
+ width: link.value,
+ })
+ )
+ return { nodes, links, columnCount: 3, columnX: [0, 100, 300], total: 40, nodeWidth: 15 }
+}
+
+describe('pathsChartData', () => {
+ it('colors the selected start point and keeps the result link on each ribbon', () => {
+ const graph = buildPathsGraph(PATHS, { startPoint: '/home' }, undefined, COLORS)
+ expect(graph.nodes.map((n) => n.color)).toEqual(['#222222', '#111111', '#111111', '#111111'])
+ // A selected start point that other steps lead into is not a path start, so no accent.
+ const notAStart = buildPathsGraph(PATHS, { startPoint: '/pricing' }, undefined, COLORS)
+ expect(notAStart.nodes[1].color).toBe('#111111')
+ expect(graph.links[2].meta).toBe(LINKS[2])
+ })
+
+ it('rebuilds the node graph the hover logic walks, keyed by the chart indices', () => {
+ const nodes = toPathNodeData(layoutOf(PATHS))
+ const home = nodes.find((n) => n.name === '1_/home')!
+ const signup = nodes.find((n) => n.name === '3_/signup')!
+ expect(nodes.map((n) => n.index)).toEqual([0, 1, 2, 3])
+ expect(home.sourceLinks.map((l) => [l.index, l.target.name])).toEqual([
+ [0, '2_/pricing'],
+ [1, '2_/docs'],
+ ])
+ expect(signup.targetLinks[0]).toMatchObject({ index: 2, average_conversion_time: 9000, value: 12 })
+ expect(signup.targetLinks[0].source).toBe(nodes[1])
+ expect([home.layer, signup.layer]).toEqual([0, 2])
+ })
+
+ it.each([
+ [1200, 3, 1200],
+ [600, 2, 600],
+ [600, 3, 1000],
+ [1000, 8, 1600],
+ ])('sizes a %dpx container with %d steps to %dpx', (containerWidth, steps, expected) => {
+ expect(pathsChartWidth(containerWidth, steps)).toBe(expected)
+ })
+
+ it('reads the step count from the link targets', () => {
+ expect(maxPathLayer(PATHS)).toBe(3)
+ expect(maxPathLayer({ nodes: [], links: [] })).toBe(0)
+ })
+})
diff --git a/products/product_analytics/frontend/insights/paths/pathsChartData.ts b/products/product_analytics/frontend/insights/paths/pathsChartData.ts
new file mode 100644
index 000000000000..ebc9975307be
--- /dev/null
+++ b/products/product_analytics/frontend/insights/paths/pathsChartData.ts
@@ -0,0 +1,103 @@
+import type { SankeyChartLayout, SankeyLinkInput, SankeyNodeInput } from '@posthog/quill-charts'
+
+import { FunnelPathsFilter, PathsFilter, PathsLink } from '~/queries/schema/schema-general'
+
+import { FALLBACK_CANVAS_WIDTH } from './constants'
+import { PathNodeData, PathTargetLink, isSelectedPathEndpoint, stripStepPrefix } from './pathUtils'
+import { Paths } from './types'
+
+export interface PathsGraphColors {
+ node: string
+ /** The start or end point the filter selected. */
+ selectedNode: string
+ link: string
+}
+
+export interface PathsGraph {
+ nodes: SankeyNodeInput[]
+ 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. */
+export function buildPathsGraph(
+ paths: Paths,
+ pathsFilter: PathsFilter,
+ funnelPathsFilter: FunnelPathsFilter | undefined,
+ colors: PathsGraphColors
+): PathsGraph {
+ const hasIncoming = new Set<string>()
+ const hasOutgoing = new Set<string>()
+ for (const link of paths.links) {
+ 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 links = paths.links.map(
+ (link): SankeyLinkInput<PathsLink> => ({
+ source: link.source,
+ target: link.target,
+ value: link.value,
+ color: colors.link,
+ meta: link,
+ })
+ )
+ return { nodes, links }
+}
+
+/** The laid-out graph in the shape the card and hover logic works on. Node and link indices are
+ * the chart's, so a hover reported by the chart addresses the same node the logic holds. */
+export function toPathNodeData(layout: SankeyChartLayout<unknown, PathsLink>): PathNodeData[] {
+ const nodes = layout.nodes.map(
+ (node): PathNodeData => ({
+ name: node.id,
+ targetLinks: [],
+ sourceLinks: [],
+ depth: node.column,
+ layer: node.column,
+ index: node.index,
+ value: node.value,
+ x0: node.x0,
+ x1: node.x1,
+ y0: node.y0,
+ y1: node.y1,
+ width: node.x1 - node.x0,
+ height: node.y1 - node.y0,
+ })
+ )
+ for (const link of layout.links) {
+ const source = nodes[link.source.index]
+ const target = nodes[link.target.index]
+ const targetLink: PathTargetLink = {
+ average_conversion_time: link.meta?.average_conversion_time ?? 0,
+ index: link.index,
+ source,
+ target,
+ value: link.value,
+ width: link.width,
+ y0: link.y0,
+ }
+ source.sourceLinks.push(targetLink)
+ target.targetLinks.push(targetLink)
+ }
+ return nodes
+}
+
+export function maxPathLayer(paths: Paths): number {
+ return paths.links.reduce((max, link) => Math.max(max, Number(link.target.match(/[^_]*/))), 0)
+}
+
+/** Chart width for a container. Past five steps the chart grows by a fifth of the container per
+ * step and the container scrolls, so long paths keep readable column spacing. A narrow container
+ * with three or more steps gets the fallback width for the same reason. */
+export function pathsChartWidth(containerWidth: number, maxLayer: number): number {
+ const minWidth = containerWidth > FALLBACK_CANVAS_WIDTH || maxLayer < 3 ? containerWidth : FALLBACK_CANVAS_WIDTH
+ return maxLayer > 5 && containerWidth ? (minWidth / 5) * maxLayer : minWidth
+}
diff --git a/products/product_analytics/frontend/insights/paths/renderPaths.ts b/products/product_analytics/frontend/insights/paths/renderPaths.ts
index 073c26f9d22c..d8d9987870f7 100644
--- a/products/product_analytics/frontend/insights/paths/renderPaths.ts
+++ b/products/product_analytics/frontend/insights/paths/renderPaths.ts
@@ -14,9 +14,8 @@ import { stripHTTP } from 'lib/utils/url'
import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
-// eslint-disable-next-line import/no-cycle
-import { FALLBACK_CANVAS_WIDTH } from './Paths'
-import { PathNodeData, isSelectedPathStartOrEnd, roundedRect } from './pathUtils'
+import { FALLBACK_CANVAS_WIDTH } from './constants'
+import { PathNodeData, PathTargetLink, isSelectedPathStartOrEnd, roundedRect } from './pathUtils'
import { Paths } from './types'
export interface PathsHoverHandlers {
@@ -125,11 +124,11 @@ const appendPathLinks = (svg: any, links: SankeyLink<PathNodeData, {}>[], handle
link.append('path')
.attr('d', sankeyLinkHorizontal())
- .attr('id', (d: PathNodeData) => `path-${d.index}`)
- .attr('stroke-width', (d: PathNodeData) => {
+ .attr('id', (d: PathTargetLink) => `path-${d.index}`)
+ .attr('stroke-width', (d: PathTargetLink) => {
return Math.max(1, d.width)
})
- .on('mouseover', (_event: MouseEvent, data: PathNodeData) => {
+ .on('mouseover', (_event: MouseEvent, data: PathTargetLink) => {
if (handlers.isCardHovered()) {
return
}
@@ -144,7 +143,7 @@ const appendPathLinks = (svg: any, links: SankeyLink<PathNodeData, {}>[], handle
link.append('g')
.append('path')
- .attr('d', (data: PathNodeData) => {
+ .attr('d', (data: PathTargetLink) => {
if (data.source.layer === 0) {
return
}
@@ -154,7 +153,7 @@ const appendPathLinks = (svg: any, links: SankeyLink<PathNodeData, {}>[], handle
})
.attr('fill', 'url(#dropoff-gradient)')
.attr('stroke-width', 0)
- .attr('transform', (data: PathNodeData) => {
+ .attr('transform', (data: PathTargetLink) => {
return (
'translate(' +
Math.round(data.source.x1) +