:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(quill-charts): add SankeyChart and use it for MCP cluster journeys (#104591)
Paul D'Ambra76f049c269c1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4b1bcf346b6a..230aec6a9f5c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -204,6 +204,22 @@ snapshots:hash: v1.k794b7964.8e7770037014d788ef5b7299b6b2f834c2afcad14dd6c6033ddd8ac885faa1c6.buSflXKIcQC5dcm7fbQWsczrZY8TleOkvO86ugYW8ywcharts-heatmap--linear-color-scale--light:hash: v1.k794b7964.c94c02704b7f9b4972f811336d019e15b77cff047551902ca74d65c1571ea6ff.PA6k_wyPYr-SNYm1-Mv8sa0DFCLb2-8QxOVNlDn4hE8+ charts-sankeychart--hovered-link--dark:+ hash: v1.k794b7964.e50f64b0a2556e240047944407ec800fb78ffc2ad3eca93219f235d64883327d.X8189N1MHu1yKO4xcQgIglRR8DdqCLFhNfcqHuspBNE+ charts-sankeychart--hovered-link--light:+ hash: v1.k794b7964.e6a0d26ab605825cb5536b0d2ff19e606d1720fe7db242a0b72e710246fa01ad.iXgOgNfOVXu_y_Wg2MG9-4ugoULs_kgICgXVoRmaMh0+ charts-sankeychart--left-aligned-with-values--dark:+ hash: v1.k794b7964.1feb41fa4c6017593646eff1e33c11eb8ef9e224e5776a2bca43c97ff2390f9b.OQ83mEQIk1BTINe94sYI5ByoXnLHMvRo8W_9an60lrI+ 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+ charts-sankeychart--narrow--light:+ hash: v1.k794b7964.1f36bc77ab15bef2f717ba801cb66cb03cfe83d0deedffc0e69b0448302bb56c.1uAAAcF-jsEeS7JkUg0VbDHHQ1YZAdpwXiMG_8X9TRM+ charts-sankeychart--tool-call-journeys--dark:+ hash: v1.k794b7964.e50f64b0a2556e240047944407ec800fb78ffc2ad3eca93219f235d64883327d.9_vvmCGYMQ1aMSvgEOizcAf1tRGe7r0-FwNnrD3cHMo+ charts-sankeychart--tool-call-journeys--light:+ hash: v1.k794b7964.3d80ddb75942d750e8966a762b6605b9780e848478da52fbfc853336f1e1602f.-Pdh9g0MEEZjcHHMAB5swPyzQpd8gsqrUd6SN3sCM1wcharts-scatterchart--best-fit--dark:hash: v1.k794b7964.0e422af020ee282c07fb513987159483cf8bc1ae701a576ba4e224f7d97bf355.f3zUaa87P5UbRRWD0X8BsZv-kDBKL422D_fxJJpUUd0charts-scatterchart--best-fit--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 78353127b461..a18f798e6bd1 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -20,6 +20,7 @@ This file is the map. Prop-level semantics live in the JSDoc on the config and p| `ScatterChart` | Two continuous numeric axes — one marker per `{ x, y }` point; takes `points`, not `labels` || `BoxPlot` | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label || `Heatmap` | 2D density grid (latency over time) — `xLabels` × `yLabels`, `cells[row][col]` |+| `SankeyChart` | Flow between stages (tool call journeys, user paths) — `nodes` + `links` keyed by id, no `series`; the graph must be acyclic || `SlopeChart` | Change between two points — one line per series, `data: [start, end]` || `Sparkline` | Tiny inline trend, no axes — gradient line or stacked bars; tooltip off by default || `MetricCard` | Headline number + sparkline + change pill (dashboard stat tiles) |@@ -39,7 +40,7 @@ const theme = useChartTheme() // reads CSS vars, tracks light/dark switches```- Series colors come from `--data-color-1..15`; chrome from `--color-graph-axis-label` / `--color-graph-axis-line` / `--color-graph-crosshair`. `themeFromCssVars()` is the one-shot version; `DEFAULT_CHART_COLORS` is the no-DOM fallback.-- Omit `color` on a series to get palette assignment by index (preferred). An explicit `color` must be a concrete color (hex, rgb): line, area, and bar series hand it to the canvas unresolved, so resolve `var(--...)` in the host first. Only `Heatmap` and `ScatterChart` resolve `var()` themselves.+- Omit `color` on a series to get palette assignment by index (preferred). An explicit `color` must be a concrete color (hex, rgb): line, area, and bar series hand it to the canvas unresolved, so resolve `var(--...)` in the host first. Only `Heatmap`, `ScatterChart`, and `SankeyChart` (node and link colors) resolve `var()` themselves.- The theme helpers carry the default chrome (faint dashed grid, stronger axis line, dashed crosshair), and `DEFAULT_CHART_CONFIG` carries the matching switches. Consumers opt out field by field (`showGrid: false`). Details: [docs/axes.md](./src/docs/axes.md).- `theme.skipDraw` mounts the canvas without painting, for deterministic visual snapshots.- The static canvas carries `data-hog-charts-paint`: `pending` from a wipe or an input change until the next paint, then `done`. The Storybook runner waits for no `pending` canvas before a snapshot.@@ -109,7 +110,7 @@ Import helpers from `@posthog/quill-charts/testing` (jsdom only): `getHogChart`| Doc | Covers || -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- || [src/README.md](./src/README.md) | Public surface, setup, theme, custom tooltip and overlay basics, sparkline |-| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, proportion bar, box plot, heatmap, sparkline, metric card |+| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, proportion bar, box plot, heatmap, sankey, sparkline, metric card || [docs/axes.md](./src/docs/axes.md) | Defaults, grid and axis chrome, x-axis labels, y format, baseline and range, multi-axis, margins, blank-plot diagnosis || [docs/bars.md](./src/docs/bars.md) | Layouts, per-bar overrides, `minBarSize`, `trackData`, hit-testing, trend lines, combo || [docs/tooltips.md](./src/docs/tooltips.md) | `config.tooltip`, `DefaultTooltip` props, custom pieces, context fields, touch |diff --git a/packages/quill/packages/charts/package.json b/packages/quill/packages/charts/package.jsonindex 411dedfcac78..09cd57e7c512 100644--- a/packages/quill/packages/charts/package.json+++ b/packages/quill/packages/charts/package.json@@ -33,6 +33,7 @@},"dependencies": {"@floating-ui/react": "^0.27.19",+ "@types/d3-shape": "^3.1.6","d3-array": "^3.2.4","d3-color": "^3.1.0","d3-scale": "^4.0.2",@@ -48,7 +49,6 @@"@types/d3-array": "^3.2.1","@types/d3-color": "^3.1.3","@types/d3-scale": "^4.0.8",- "@types/d3-shape": "^3.1.6","@types/jest": "catalog:","@types/react": "^18.3.27","@types/react-dom": "^18.3.7",diff --git a/packages/quill/packages/charts/src/README.md b/packages/quill/packages/charts/src/README.mdindex 3224591a3c86..9b15654229e3 100644--- a/packages/quill/packages/charts/src/README.md+++ b/packages/quill/packages/charts/src/README.md@@ -133,7 +133,7 @@ import { Sparkline } from '@posthog/quill-charts'## More- Choosing a chart, the gotchas, and the docs index → [AGENTS.md](../AGENTS.md)-- Per-chart behavior (scatter, funnel, slope, pie, proportion bar, metric card) → [docs/chart-types.md](./docs/chart-types.md)+- Per-chart behavior (scatter, funnel, slope, pie, proportion bar, box plot, heatmap, sankey, sparkline, metric card) → [docs/chart-types.md](./docs/chart-types.md)- Axes, ranges, multi-axis, chrome → [docs/axes.md](./docs/axes.md)- Bars: layouts, per-bar overrides, `minBarSize`, `trackData` → [docs/bars.md](./docs/bars.md)- Tooltips → [docs/tooltips.md](./docs/tooltips.md); legend → [docs/legend.md](./docs/legend.md)diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsxnew file mode 100644index 000000000000..389f893661a0--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.stories.tsx@@ -0,0 +1,101 @@+import { Meta, StoryObj } from '@storybook/react'++import { playHoverAtFraction, Stage, useReactiveTheme } from '../../story-helpers'+import type { SankeyLinkInput, SankeyNodeInput } from './sankey-data'+import { SankeyChart } from './SankeyChart'++// Agent sessions through an MCP server: which tool ran first, what came next, and how the+// session ended. The same tool appears in several stages, so each stage gets its own node id+// while nodes that share a label share a color.+const STAGES = ['Start', 'First tool', 'Second tool', 'Outcome']++const NODES: SankeyNodeInput[] = [+ { id: 'start', label: 'Sessions' },+ { id: '1:schema', label: 'read-data-schema' },+ { id: '1:sql', label: 'execute-sql' },+ { id: '1:trends', label: 'query-trends' },+ { id: '2:sql', label: 'execute-sql' },+ { id: '2:trends', label: 'query-trends' },+ { id: '2:insight', label: 'insight-create' },+ { id: '2:ended', label: 'Ended' },+ { id: 'completed', label: 'Completed', color: 'var(--data-color-3)' },+ { id: 'error', label: 'Error', color: 'var(--data-color-5)' },+]++const LINKS: SankeyLinkInput[] = [+ { source: 'start', target: '1:schema', value: 54 },+ { source: 'start', target: '1:sql', value: 31 },+ { source: 'start', target: '1:trends', value: 15 },+ { source: '1:schema', target: '2:sql', value: 38 },+ { source: '1:schema', target: '2:trends', value: 16 },+ { source: '1:sql', target: '2:sql', value: 22 },+ { source: '1:sql', target: '2:ended', value: 9 },+ { source: '1:trends', target: '2:insight', value: 11 },+ { source: '1:trends', target: '2:ended', value: 4 },+ { source: '2:sql', target: 'completed', value: 47 },+ { source: '2:sql', target: 'error', value: 13, color: 'var(--data-color-5)' },+ { source: '2:trends', target: 'completed', value: 16 },+ { source: '2:insight', target: 'completed', value: 11 },+ { source: '2:ended', target: 'error', value: 13, color: 'var(--data-color-5)' },+]++const meta: Meta<typeof SankeyChart> = {+ title: 'Charts/SankeyChart',+ component: SankeyChart,+ tags: ['autodocs'],+}+export default meta++type Story = StoryObj<typeof SankeyChart>++export const ToolCallJourneys: Story = {+ render: function Render() {+ const theme = useReactiveTheme()+ return (+ <Stage width={720} height={320}>+ <SankeyChart nodes={NODES} links={LINKS} theme={theme} config={{ columnLabels: STAGES }} />+ </Stage>+ )+ },+}++export const HoveredLink: Story = {+ render: function Render() {+ const theme = useReactiveTheme()+ return (+ <Stage width={720} height={320}>+ <SankeyChart nodes={NODES} links={LINKS} theme={theme} config={{ columnLabels: STAGES }} />+ </Stage>+ )+ },+ play: async ({ canvasElement }) => {+ await playHoverAtFraction(canvasElement, 0.2, 0.3)+ },+}++export const LeftAlignedWithValues: Story = {+ render: function Render() {+ const theme = useReactiveTheme()+ return (+ <Stage width={720} height={320}>+ <SankeyChart+ nodes={NODES}+ links={LINKS}+ theme={theme}+ config={{ nodeAlign: 'left', showNodeValues: true, preserveNodeOrder: true, linkOpacity: 0.25 }}+ />+ </Stage>+ )+ },+}++export const Narrow: Story = {+ render: function Render() {+ const theme = useReactiveTheme()+ return (+ <Stage width={360} height={240}>+ <SankeyChart nodes={NODES} links={LINKS} theme={theme} config={{ columnLabels: STAGES }} />+ </Stage>+ )+ },+}diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsxnew file mode 100644index 000000000000..12dac8f59a6b--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.test.tsx@@ -0,0 +1,168 @@+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 { SankeyChart } from './SankeyChart'++const THEME: ChartTheme = { colors: ['#1f77b4', '#ff7f0e', '#2ca02c'], backgroundColor: '#ffffff' }++const NODES: SankeyNodeInput[] = [+ { id: 'start', label: 'Start' },+ { id: 'a', label: 'Tool A' },+ { id: 'done', label: 'Completed' },+]+const LINKS: SankeyLinkInput[] = [+ { source: 'start', target: 'a', value: 12 },+ { source: 'a', target: 'done', value: 12 },+]++// Mirrors the chart's own layout at the mocked 800x400 wrapper, so a cursor lands on a known node.+function nodeCenter(id: string): { clientX: number; clientY: number } {+ const layout = computeSankeyLayout({+ nodes: NODES,+ links: LINKS,+ plot: { plotLeft: 8, plotTop: 8, plotWidth: 800 - 16, plotHeight: 400 - 16 },+ nodeWidth: 12,+ nodePadding: 8,+ nodeAlign: 'justify',+ preserveNodeOrder: false,+ colorForLabel: () => '#000',+ resolveColor: (c) => c,+ })+ const node = layout.nodes.find((n) => n.id === id)!+ return { clientX: (node.x0 + node.x1) / 2, clientY: (node.y0 + node.y1) / 2 }+}++describe('SankeyChart', () => {+ it('renders node labels and column headers as DOM overlays', () => {+ const { chart } = renderHogChart(+ <SankeyChart+ nodes={NODES}+ links={LINKS}+ theme={THEME}+ config={{ columnLabels: ['Init', '1st tool', 'Outcome', 'unused'], showNodeValues: true }}+ />+ )+ expect(chart.sankeyNodeLabels()).toEqual(['Start 12', 'Tool A 12', 'Completed 12'])+ expect(chart.sankeyColumnLabels()).toEqual(['Init', '1st tool', 'Outcome'])+ 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 () => {+ const onNodeClick = jest.fn()+ const { chart, rerender } = renderHogChart(+ <SankeyChart nodes={NODES} links={LINKS} theme={THEME} onNodeClick={onNodeClick} />,+ { nativeTooltip: true }+ )+ await waitFor(() => {+ fireEvent.mouseMove(chart.element, nodeCenter('a'))+ expect(getHogChartTooltip()?.textContent).toContain('Tool A')+ })+ // The share is of the total inflow, so the only path reads as 100%.+ expect(getHogChartTooltip()?.textContent).toContain('100%')+ fireEvent.click(chart.element)+ expect(onNodeClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'a', value: 12 }))++ rerender(+ <SankeyChart+ nodes={NODES}+ links={LINKS}+ theme={{ ...THEME, colors: [...THEME.colors] }}+ onNodeClick={onNodeClick}+ />+ )+ expect(getHogChartTooltip()?.textContent).toContain('Tool A')++ onNodeClick.mockClear()+ rerender(+ <SankeyChart+ nodes={NODES}+ links={LINKS}+ theme={THEME}+ onNodeClick={onNodeClick}+ config={{ nodeWidth: 24 }}+ />+ )+ await waitFor(() => expect(getHogChartTooltip()).toBeNull())+ fireEvent.click(chart.element)+ expect(onNodeClick).not.toHaveBeenCalled()+ })++ it('shows the tooltip on a first tap and fires onNodeClick on the second', async () => {+ const onNodeClick = jest.fn()+ const { chart } = renderHogChart(+ <SankeyChart nodes={NODES} links={LINKS} theme={THEME} onNodeClick={onNodeClick} />,+ { 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 down = Object.assign(new MouseEvent('pointerdown', { bubbles: true }), { pointerType: 'touch' })+ fireEvent(chart.element, down)+ fireEvent.click(chart.element, nodeCenter('a'))+ }+ tap()+ await waitFor(() => expect(getHogChartTooltip()?.textContent).toContain('Tool A'))+ expect(onNodeClick).not.toHaveBeenCalled()+ tap()+ expect(onNodeClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'a' }))+ })++ it('fires the click on the first tap when the tooltip is disabled', () => {+ const onNodeClick = jest.fn()+ const { chart } = renderHogChart(+ <SankeyChart+ nodes={NODES}+ links={LINKS}+ theme={THEME}+ onNodeClick={onNodeClick}+ config={{ tooltip: { enabled: false } }}+ />+ )+ const down = Object.assign(new MouseEvent('pointerdown', { bubbles: true }), { pointerType: 'touch' })+ fireEvent(chart.element, down)+ fireEvent.click(chart.element, nodeCenter('a'))++ expect(onNodeClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'a' }))+ })++ it('ignores hover and clicks from an interactive overlay child', async () => {+ const onNodeClick = jest.fn()+ const { chart } = renderHogChart(+ <SankeyChart nodes={NODES} links={LINKS} theme={THEME} onNodeClick={onNodeClick}>+ <button data-hog-charts-interactive-overlay>overlay</button>+ </SankeyChart>,+ { nativeTooltip: true }+ )+ await waitFor(() => {+ fireEvent.mouseMove(chart.element, nodeCenter('a'))+ expect(getHogChartTooltip()?.textContent).toContain('Tool A')+ })+ const overlay = chart.element.querySelector('[data-hog-charts-interactive-overlay]')!+ fireEvent.mouseMove(overlay, nodeCenter('a'))+ await waitFor(() => expect(getHogChartTooltip()).toBeNull())+ fireEvent.click(overlay, nodeCenter('a'))+ expect(onNodeClick).not.toHaveBeenCalled()+ })++ it.each([+ {+ name: 'a link endpoint',+ 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 }) => {+ jest.spyOn(console, 'error').mockImplementation(() => {})+ const onError = jest.fn()+ const { container, rerender } = render(+ <SankeyChart nodes={NODES} links={LINKS} theme={THEME} onError={onError} {...broken} />+ )+ expect(onError).toHaveBeenCalled()+ expect(container.textContent).toContain('Something went wrong')++ rerender(<SankeyChart nodes={NODES} links={LINKS} theme={THEME} onError={onError} />)+ expect(container.textContent).not.toContain('Something went wrong')+ })+})diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsxnew file mode 100644index 000000000000..61d75907c46a--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx@@ -0,0 +1,270 @@+import React, { useCallback, useMemo } from 'react'++import { ChartHoverContext, ChartLayoutContext } from '../../core/chart-context'+import type { ChartHoverContextValue, ChartLayoutContextValue } from '../../core/chart-context'+import { ChartShell, useCanvasBounds } from '../../core/chart-shell'+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import { resolveCssColor } from '../../core/color-utils'+import { useChartCanvas } from '../../core/hooks/useChartCanvas'+import { useChartDraw } from '../../core/hooks/useChartDraw'+import { applyMarginOverride } from '../../core/hooks/useChartMargins'+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 { 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 { SankeyColumnLabels } from './SankeyColumnLabels'+import { SankeyNodeLabels } from './SankeyNodeLabels'+import type { SankeyChartProps, SankeyTooltipContext } from './types'+import { useSankeyInteraction } from './useSankeyInteraction'++const DEFAULT_NODE_WIDTH = 12+const DEFAULT_NODE_PADDING = 8+const DEFAULT_LINK_OPACITY = 0.4+const HOVER_ANIMATION_MS = 150+const BASE_MARGINS: ChartMargins = { top: 8, right: 8, bottom: 8, left: 8 }+/** Room for the column header row above the plot. */+const COLUMN_LABEL_HEIGHT = 18+const DEFAULT_LABEL_COLOR = 'rgba(0, 0, 0, 0.7)'++const NO_SCALES: ChartScales = { x: () => undefined, y: () => 0, yTicks: () => [] }++/** Changes whenever the layout could validate differently, so a corrected graph clears the error. */+function graphKey(+ nodes: SankeyNodeInput<unknown>[],+ links: SankeyLinkInput<unknown>[],+ config: SankeyChartProps['config']+): string {+ // Structured serialization: ids are free-form strings, so a delimiter inside one must not collide.+ return JSON.stringify([+ nodes.map((node) => node.id),+ links.map(({ source, target, value }) => [source, target, value]),+ [config?.nodeWidth, config?.nodePadding, config?.nodeAlign, config?.preserveNodeOrder],+ ])+}++/** Used when `theme.colors` is empty, as `Heatmap` does for its accent. */+const FALLBACK_NODE_COLOR = '#1d4aff'++export function SankeyChart<NodeMeta = unknown, LinkMeta = NodeMeta>({+ onError,+ ...rest+}: SankeyChartProps<NodeMeta, LinkMeta>): React.ReactElement {+ return (+ <ChartErrorBoundary onError={onError} resetKey={graphKey(rest.nodes, rest.links, rest.config)}>+ <SankeyChartInner {...rest} />+ </ChartErrorBoundary>+ )+}++function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({+ nodes,+ links,+ theme,+ config,+ tooltip,+ onNodeClick,+ onLinkClick,+ className,+ dataAttr,+ children,+}: Omit<SankeyChartProps<NodeMeta, LinkMeta>, 'onError'>): React.ReactElement {+ const {+ nodeWidth = DEFAULT_NODE_WIDTH,+ nodePadding = DEFAULT_NODE_PADDING,+ nodeAlign = 'justify',+ preserveNodeOrder = false,+ columnLabels,+ showNodeLabels = true,+ showNodeValues = false,+ linkOpacity: configuredLinkOpacity = DEFAULT_LINK_OPACITY,+ valueFormatter = defaultValueFormatter,+ tooltip: tooltipConfig,+ margins: marginsOverride,+ } = config ?? {}+ const linkOpacity = Number.isFinite(configuredLinkOpacity)+ ? Math.min(1, Math.max(0, configuredLinkOpacity))+ : DEFAULT_LINK_OPACITY+ const showTooltip = tooltipConfig?.enabled !== false+ const hasColumnLabels = !!columnLabels && columnLabels.length > 0++ const margins = useMemo<ChartMargins>(() => {+ const computed = hasColumnLabels+ ? { ...BASE_MARGINS, top: BASE_MARGINS.top + COLUMN_LABEL_HEIGHT }+ : BASE_MARGINS+ return marginsOverride ? applyMarginOverride(computed, marginsOverride) : computed+ }, [hasColumnLabels, marginsOverride])++ const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({ margins })++ // `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.+ const paletteKey = theme.colors.join('\n')++ // Nodes that share a label share a palette slot, so the same tool in two columns keeps one hue.+ const colorForLabel = useMemo(() => {+ const palette = paletteKey.split('\n')+ const slots = new Map<string, string>()+ for (const node of nodes) {+ if (node.color) {+ continue+ }+ const label = node.label ?? node.id+ if (!slots.has(label)) {+ slots.set(label, palette[slots.size % palette.length] || FALLBACK_NODE_COLOR)+ }+ }+ return (label: string): string => slots.get(label) ?? (palette[0] || FALLBACK_NODE_COLOR)+ }, [nodes, paletteKey])++ const layout = useMemo<SankeyChartLayout<NodeMeta, LinkMeta>>(+ () =>+ computeSankeyLayout<NodeMeta, LinkMeta>({+ nodes,+ links,+ plot: dimensions ?? { plotLeft: 0, plotTop: 0, plotWidth: 0, plotHeight: 0 },+ nodeWidth,+ nodePadding,+ nodeAlign,+ preserveNodeOrder,+ colorForLabel,+ resolveColor: resolveCssColor,+ }),+ [nodes, links, dimensions, nodeWidth, nodePadding, nodeAlign, preserveNodeOrder, colorForLabel]+ )++ // The shared draw loop keys repaints on `scales` identity, so wrap the layout in one.+ const scales = useMemo<ChartScales | null>(+ () => (dimensions ? { ...NO_SCALES, _private: { __sankey: layout, linkOpacity } } : null),+ [dimensions, layout, linkOpacity]+ )++ const { hoverIndex, hoverPosition, tooltipCtx, handlers } = useSankeyInteraction<NodeMeta, LinkMeta>({+ layout,+ canvasRef,+ wrapperRef,+ showTooltip,+ onNodeClick,+ onLinkClick,+ })++ const drawStatic = useCallback(+ ({ ctx: drawCtx }: ChartDrawArgs) =>+ drawSankey(drawCtx, layout as SankeyChartLayout<unknown, unknown>, { linkOpacity }),+ [layout, linkOpacity]+ )+ // 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 => {+ if (cached?.index !== index) {+ const untyped = layout as SankeyChartLayout<unknown, unknown>+ cached = { index, flow: sankeyActiveFlow(untyped, hoverIndexToHit(untyped, index)) }+ }+ return cached.flow+ }+ }, [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]+ )++ useChartDraw({+ ctx,+ overlayCtx,+ dimensions,+ scales,+ series: [],+ labels: [],+ hoverIndex,+ hoverPosition,+ theme,+ drawStatic,+ drawHover,+ hoverAnimationMs: HOVER_ANIMATION_MS,+ })++ const renderTooltip = useMemo(+ () =>+ tooltip ??+ ((tooltipContext: SankeyTooltipContext<NodeMeta, LinkMeta>): React.ReactNode => (+ <PieTooltip ctx={tooltipContext} valueFormatter={valueFormatter} />+ )),+ [tooltip, valueFormatter]+ )++ const canvasBounds = useCanvasBounds(canvasRef)+ const layoutValue = useMemo<ChartLayoutContextValue | null>(() => {+ if (!scales || !dimensions) {+ return null+ }+ return {+ scales,+ dimensions,+ labels: [],+ series: [],+ theme,+ resolvePositionValue: defaultResolveValue,+ canvasBounds,+ axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },+ yGutters: [],+ }+ }, [scales, dimensions, theme, canvasBounds])+ const sankeyValue = useMemo<SankeyLayoutContextValue<NodeMeta, LinkMeta>>(+ () => ({ layout, canvasBounds }),+ [layout, canvasBounds]+ )+ const hoverValue = useMemo<ChartHoverContextValue>(() => ({ hoverIndex }), [hoverIndex])++ const ariaLabel = `Sankey chart with ${layout.nodes.length} nodes and ${layout.links.length} links`+ const labelColor = theme.axisColor ?? DEFAULT_LABEL_COLOR+ const clickable = hoverIndex >= 0 && !!(onNodeClick || onLinkClick)++ return (+ <ChartLayoutContext.Provider value={layoutValue}>+ <SankeyLayoutContext.Provider value={sankeyValue as SankeyLayoutContextValue}>+ <ChartHoverContext.Provider value={hoverValue}>+ <ChartShell+ wrapperRef={wrapperRef}+ canvasRef={canvasRef}+ overlayCanvasRef={overlayCanvasRef}+ className={className}+ dataAttr={dataAttr}+ pointer={clickable}+ ariaLabel={ariaLabel}+ handlers={handlers}+ showOverlay={!!dimensions}+ >+ {hasColumnLabels ? <SankeyColumnLabels labels={columnLabels} color={labelColor} /> : null}+ {showNodeLabels ? (+ <SankeyNodeLabels+ color={labelColor}+ showValues={showNodeValues}+ valueFormatter={valueFormatter}+ />+ ) : null}+ {children}+ {tooltipCtx && showTooltip ? (+ <Tooltip+ context={tooltipCtx}+ renderTooltip={renderTooltip as never}+ placement={tooltipConfig?.placement ?? 'cursor'}+ />+ ) : null}+ </ChartShell>+ </ChartHoverContext.Provider>+ </SankeyLayoutContext.Provider>+ </ChartLayoutContext.Provider>+ )+}diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsxnew file mode 100644index 000000000000..5d3474ea6662--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyColumnLabels.tsx@@ -0,0 +1,55 @@+import React from 'react'++import { useSankeyLayout } from './sankey-context'++const LABEL_STYLE_BASE: React.CSSProperties = {+ position: 'absolute',+ pointerEvents: 'none',+ top: 0,+ fontSize: 10,+ lineHeight: 1.2,+ textTransform: 'uppercase',+ letterSpacing: '0.04em',+ whiteSpace: 'nowrap',+}++export interface SankeyColumnLabelsProps {+ labels: string[]+ color: string+}++/** 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 {+ const { layout } = useSankeyLayout()+ const lastColumn = layout.columnCount - 1+ return (+ <>+ {Array.from({ length: layout.columnCount }, (_, column) => {+ const x = layout.columnX[column]+ const label = labels[column]+ if (!label || x === undefined) {+ return null+ }+ let placement: React.CSSProperties+ 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%)' }+ }+ return (+ <div+ key={column}+ data-attr="hog-chart-sankey-column-label"+ style={{ ...LABEL_STYLE_BASE, ...placement, color }}+ >+ {label}+ </div>+ )+ })}+ </>+ )+}diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsxnew file mode 100644index 000000000000..c6a59502d4ba--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyNodeLabels.tsx@@ -0,0 +1,53 @@+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++const LABEL_STYLE_BASE: React.CSSProperties = {+ position: 'absolute',+ pointerEvents: 'none',+ fontSize: LABEL_FONT_SIZE,+ lineHeight: 1.2,+ whiteSpace: 'nowrap',+ transform: 'translateY(-50%)',+}++export interface SankeyNodeLabelsProps {+ 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)++ 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>+ )+ })}+ </>+ )+}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.tsnew file mode 100644index 000000000000..d0841cf27f3b--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.test.ts@@ -0,0 +1,97 @@+import { drawSankeyHover, sankeyActiveFlow } from './draw-sankey'+import { computeSankeyLayout } from './sankey-data'++const BACKGROUND = 'hsl(235deg 8% 15%)'++function layoutOf(secondLinkValue = 10): ReturnType<typeof computeSankeyLayout> {+ return computeSankeyLayout({+ nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],+ links: [+ { source: 'a', target: 'b', value: 10 },+ { source: 'a', target: 'c', value: secondLinkValue },+ ],+ plot: { plotLeft: 0, plotTop: 0, plotWidth: 600, plotHeight: 300 },+ nodeWidth: 10,+ nodePadding: 8,+ nodeAlign: 'justify',+ preserveNodeOrder: false,+ colorForLabel: () => '#ff0000',+ resolveColor: (c) => c,+ })+}++/** Records stroke colors and filled rects. Like a browser canvas it only accepts colors it can parse. */+function recordingCtx(serialize: Record<string, string>): {+ ctx: CanvasRenderingContext2D+ strokes: string[]+ fills: string[]+} {+ const strokes: string[] = []+ const fills: string[] = []+ let fill = '#000000'+ let stroke = '#000000'+ const ctx = {+ globalAlpha: 1,+ lineWidth: 1,+ get fillStyle(): string {+ return fill+ },+ set fillStyle(value: string) {+ fill = serialize[value] ?? (value.startsWith('#') ? value : fill)+ },+ get strokeStyle(): string {+ return stroke+ },+ set strokeStyle(value: string) {+ stroke = value+ },+ beginPath: () => {},+ moveTo: () => {},+ bezierCurveTo: () => {},+ save: () => {},+ restore: () => {},+ fillRect: () => fills.push(fill),+ stroke: () => strokes.push(stroke),+ } as unknown as CanvasRenderingContext2D+ return { ctx, strokes, fills }+}++describe('drawSankeyHover', () => {+ it.each([+ ['serialized by the canvas', { [BACKGROUND]: '#202023' }, 10, 2],+ ['rejected by the canvas', {}, 10, 1],+ ['zero-valued inactive ribbon', { [BACKGROUND]: '#202023' }, 0, 1],+ ])(+ 'dims an inactive ribbon only when it carries flow and the background parses: %s',+ (_name, serialize, secondLinkValue, expectedStrokes) => {+ const layout = layoutOf(secondLinkValue)+ const { ctx, strokes } = recordingCtx(serialize)+ drawSankeyHover(ctx, layout, sankeyActiveFlow(layout, { kind: 'link', index: 0 }), {+ linkOpacity: 0.4,+ backgroundColor: BACKGROUND,+ progress: 1,+ })++ // A usable background dims the inactive ribbon to an opaque mix; otherwise only the active+ // ribbon is repainted and the static layer keeps the inactive one as it was.+ expect(strokes).toHaveLength(expectedStrokes)+ expect(strokes).not.toContain(BACKGROUND)+ expect(strokes).not.toContain('#202023')+ }+ )++ it('leaves a transparent ribbon and node to the static layer instead of mixing NaN channels', () => {+ const layout = layoutOf()+ 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 }), {+ linkOpacity: 0.4,+ backgroundColor: BACKGROUND,+ progress: 1,+ })++ expect(strokes).toHaveLength(1)+ expect(fills).toHaveLength(2)+ })+})diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.ts b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.tsnew file mode 100644index 000000000000..752dd89b94d5--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/draw-sankey.ts@@ -0,0 +1,165 @@+import { color as d3Color } from 'd3-color'++import { mixColors } from '../../core/color-utils'+import type { SankeyChartLayout, SankeyHit, SankeyLinkDatum, SankeyNodeDatum } from './sankey-data'++export interface DrawSankeyOptions {+ linkOpacity: number+}++/** 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. */+const HOVER_DIM_AMOUNT = 0.55+const HOVER_HIGHLIGHT_TARGET = '#ffffff'+const HOVER_HIGHLIGHT_AMOUNT = 0.15+const HOVER_DIM_TARGET_FALLBACK = '#ffffff'++function traceLink(ctx: CanvasRenderingContext2D, link: SankeyLinkDatum): void {+ const x0 = link.source.x1+ const x1 = link.target.x0+ const xm = (x0 + x1) / 2+ ctx.beginPath()+ ctx.moveTo(x0, link.y0)+ ctx.bezierCurveTo(xm, link.y0, xm, link.y1, x1, link.y1)+}++function strokeLink(ctx: CanvasRenderingContext2D, link: SankeyLinkDatum, color: string, opacity: number): void {+ // A zero-valued link carries no flow, so the 1px floor below must not draw it.+ if (link.value === 0) {+ return+ }+ traceLink(ctx, link)+ ctx.save()+ ctx.globalAlpha *= opacity+ ctx.strokeStyle = color+ // A sub-pixel ribbon disappears against the node it leaves; keep every flow visible.+ ctx.lineWidth = Math.max(1, link.width)+ ctx.stroke()+ ctx.restore()+}++function fillNode(ctx: CanvasRenderingContext2D, node: SankeyNodeDatum, color: string): void {+ ctx.fillStyle = color+ 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 {+ if (!hit) {+ return null+ }+ const links = new Set<SankeyLinkDatum>()+ const nodes = new Set<SankeyNodeDatum>()+ if (hit.kind === 'node') {+ const node = layout.nodes[hit.index]+ nodes.add(node)+ for (const link of layout.links) {+ if (link.source === node || link.target === node) {+ links.add(link)+ nodes.add(link.source)+ nodes.add(link.target)+ }+ }+ } else {+ const link = layout.links[hit.index]+ links.add(link)+ nodes.add(link.source)+ nodes.add(link.target)+ }+ return { hit, links, nodes }+}++function isMixable(parsed: ReturnType<typeof d3Color> | null): boolean {+ const rgb = parsed?.rgb()+ return !!rgb && Number.isFinite(rgb.r) && Number.isFinite(rgb.g) && Number.isFinite(rgb.b)+}++/** A color `mixColors` can interpolate, or `null`. d3-color cannot parse modern CSS syntax such as+ * `hsl(235deg 8% 15%)` or `oklch(...)`, so those go through the canvas, which serializes any color+ * it accepts to hex or rgba. An invalid color leaves `fillStyle` unchanged, so two different+ * sentinels tell it apart from a valid one. */+function parseableColor(ctx: CanvasRenderingContext2D, color: string): string | null {+ if (isMixable(d3Color(color))) {+ return color+ }+ const previous = ctx.fillStyle+ const read = (sentinel: string): string => {+ ctx.fillStyle = sentinel+ ctx.fillStyle = color+ return String(ctx.fillStyle)+ }+ const first = read('#000000')+ const second = read('#ffffff')+ ctx.fillStyle = previous+ 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(+ 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)+ 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.+ for (const link of layout.links) {+ if (activeLinks.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)+ }+ }+ for (const link of activeLinks) {+ const opacity = options.linkOpacity + (HOVER_LINK_OPACITY - options.linkOpacity) * options.progress+ strokeLink(ctx, link, link.color, opacity)+ }+ // Nodes go last so a ribbon that skips a column never paints over the node it passes behind.+ for (const node of layout.nodes) {+ if (!activeNodes.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+ const color = highlightBase+ ? mixColors(highlightBase, HOVER_HIGHLIGHT_TARGET, HOVER_HIGHLIGHT_AMOUNT * options.progress)+ : node.color+ fillNode(ctx, node, color)+ }+ return true+}diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-context.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-context.tsnew file mode 100644index 000000000000..5bf240a490db--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-context.ts@@ -0,0 +1,25 @@+import { createContext, useContext } from 'react'++import type { SankeyChartLayout } from './sankey-data'++/** Layout-stable values exposed to Sankey overlays (node labels, column headers, custom+ * decorations). Identity does not change on hover. */+export interface SankeyLayoutContextValue<NodeMeta = unknown, LinkMeta = NodeMeta> {+ layout: SankeyChartLayout<NodeMeta, LinkMeta>+ /** Returns the current canvas bounding rect, or null if the canvas is unmounted. */+ canvasBounds: () => DOMRect | null+}++export const SankeyLayoutContext = createContext<SankeyLayoutContextValue | null>(null)++/** Subscribes to the Sankey layout. Throws if used outside a `<SankeyChart>`. */+export function useSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>(): SankeyLayoutContextValue<+ NodeMeta,+ LinkMeta+> {+ const ctx = useContext(SankeyLayoutContext)+ if (!ctx) {+ throw new Error('useSankeyLayout must be used inside <SankeyChart>')+ }+ return ctx as SankeyLayoutContextValue<NodeMeta, LinkMeta>+}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.tsnew file mode 100644index 000000000000..fa00de8775af--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.test.ts@@ -0,0 +1,180 @@+import { 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 }++const NODES: SankeyNodeInput[] = [+ { id: 'start' },+ { id: 'a', label: 'Tool A' },+ { id: 'b', label: 'Tool B' },+ { id: 'done', label: 'Completed' },+]+const LINKS: SankeyLinkInput[] = [+ { source: 'start', target: 'a', value: 30 },+ { source: 'start', target: 'b', value: 10 },+ { source: 'a', target: 'done', value: 30 },+ { source: 'b', target: 'done', value: 10 },+]++function layoutOf(+ overrides: Partial<ComputeSankeyLayoutOptions<unknown>> = {}+): ReturnType<typeof computeSankeyLayout> {+ return computeSankeyLayout({+ nodes: NODES,+ links: LINKS,+ plot: PLOT,+ nodeWidth: 10,+ nodePadding: 8,+ nodeAlign: 'justify',+ preserveNodeOrder: false,+ colorForLabel: () => '#111111',+ resolveColor: (c) => c,+ ...overrides,+ })+}++describe('computeSankeyLayout', () => {+ it('places nodes in columns by depth and sums flow into node values', () => {+ const layout = layoutOf()+ const byId = Object.fromEntries(layout.nodes.map((n) => [n.id, n]))+ expect(byId.start.column).toBe(0)+ expect(byId.a.column).toBe(1)+ expect(byId.b.column).toBe(1)+ expect(byId.done.column).toBe(2)+ expect(layout.columnCount).toBe(3)+ expect(byId.start.value).toBe(40)+ 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)+ })++ it('places a flow that ends early by alignment: justify, left, and right', () => {+ const links: SankeyLinkInput[] = [...LINKS, { source: 'start', target: 'ended', value: 5 }]+ const nodes: SankeyNodeInput[] = [...NODES, { id: 'ended', label: 'Ended' }]+ const columnOf = (align: 'justify' | 'left' | 'right', id: string): number | undefined =>+ layoutOf({ nodes, links, nodeAlign: align }).nodes.find((n) => n.id === id)?.column+ expect(columnOf('justify', 'ended')).toBe(2)+ expect(columnOf('left', 'ended')).toBe(1)+ // Right alignment counts from the sink, so the source stays first and the early end moves last.+ expect([columnOf('right', 'start'), columnOf('right', 'a'), columnOf('right', 'ended')]).toEqual([0, 1, 2])+ })++ 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)' }],+ colorForLabel: (label) => (label === 'Tool A' ? '#aaaaaa' : '#bbbbbb'),+ resolveColor: (c) => (c.startsWith('var(') ? '#00ff00' : c),+ })+ const byId = Object.fromEntries(layout.nodes.map((n) => [n.id, n]))+ expect(byId.a.color).toBe('#aaaaaa')+ expect(byId.done.color).toBe('#00ff00')+ const aToDone = layout.links.find((l) => l.source.id === 'a' && l.target.id === 'done')+ expect(aToDone?.color).toBe('#aaaaaa')+ })++ it('caps node width by the column count, not the node count', () => {+ const targets = Array.from({ length: 200 }, (_, i): SankeyNodeInput => ({ id: `t${i}` }))+ const dense = layoutOf({+ nodes: [{ id: 'start' }, ...targets],+ links: targets.map((target) => ({ source: 'start', target: target.id, value: 1 })),+ })+ expect(dense.columnCount).toBe(2)+ expect(dense.nodeWidth).toBe(10)+ })++ 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(+ 'missing node: start -> nope'+ )+ })++ it.each([+ ['a zero nodeWidth', { nodeWidth: 0 }, 'nodeWidth'],+ ['a NaN nodeWidth', { nodeWidth: NaN }, 'nodeWidth'],+ ['a negative nodePadding', { nodePadding: -1 }, 'nodePadding'],+ ])('throws on %s so the error boundary reports it', (_name, overrides, message) => {+ expect(() => layoutOf(overrides)).toThrow(message)+ })++ it('returns an empty layout when all link values are zero', () => {+ const layout = layoutOf({ links: [{ source: 'start', target: 'a', value: 0 }] })+ expect(layout.nodes).toHaveLength(0)+ expect(layout.total).toBe(0)+ })++ it('measures the total from the nodes fed by no flow when an earlier link is zero', () => {+ const layout = layoutOf({+ links: [+ { source: 'start', target: 'a', value: 0 },+ { source: 'a', target: 'done', value: 10 },+ ],+ })+ expect(layout.nodes.length).toBeGreaterThan(0)+ expect(layout.total).toBe(10)+ })+})++describe('sankeyHitAt', () => {+ const layout = layoutOf()+ const node = (id: string): NonNullable<(typeof layout.nodes)[number]> => layout.nodes.find((n) => n.id === id)!++ it('resolves a node box, a ribbon between columns, and empty space', () => {+ const start = node('start')+ const nodeHit = sankeyHitAt(layout, { x: (start.x0 + start.x1) / 2, y: (start.y0 + start.y1) / 2 })+ expect(nodeHit).toEqual({ kind: 'node', index: layout.nodes.indexOf(start) })++ const aToDone = layout.links.findIndex((l) => l.source.id === 'a' && l.target.id === 'done')+ const link = layout.links[aToDone]+ // Mid-ribbon, the curve passes through the average of its end y values.+ const linkHit = sankeyHitAt(layout, {+ x: (link.source.x1 + link.target.x0) / 2,+ y: (link.y0 + link.y1) / 2,+ })+ expect(linkHit).toEqual({ kind: 'link', index: aToDone })++ expect(sankeyHitAt(layout, { x: -50, y: -50 })).toBeNull()+ })++ it('hits a long, thin ribbon between coarse curve samples', () => {+ const thin = layoutOf({+ nodes: [{ id: 'start' }, { id: 'a' }, { id: 'b' }],+ links: [+ { source: 'start', target: 'a', value: 1000 },+ { source: 'start', target: 'b', value: 1 },+ ],+ })+ const index = thin.links.findIndex((l) => l.target.id === 'b')+ const link = thin.links[index]+ expect(link.width).toBeLessThan(1)++ // Halfway between two of 24 evenly spaced samples, where a fixed sample count misses by ~18px.+ const t = 0.5 + 1 / 48+ const cursor = { x: bezierX(link.source.x1, link.target.x0, t), y: bezierY(link.y0, link.y1, t) }+ expect(sankeyHitAt(thin, cursor)).toEqual({ kind: 'link', index })+ })++ it('does not hit a zero-value ribbon', () => {+ const withZero = layoutOf({+ nodes: [{ id: 'start' }, { id: 'a' }, { id: 'b' }],+ links: [+ { source: 'start', target: 'a', value: 30 },+ { source: 'start', target: 'b', value: 0 },+ ],+ })+ const index = withZero.links.findIndex((l) => l.target.id === 'b')+ const link = withZero.links[index]+ const cursor = { x: (link.source.x1 + link.target.x0) / 2, y: (link.y0 + link.y1) / 2 }+ expect(sankeyHitAt(withZero, cursor)).toBeNull()+ })++ it('hits a zero-value node across the 1px the draw code floors it to', () => {+ const withOrphan = layoutOf({ nodes: [...NODES, { id: 'orphan' }], links: LINKS })+ const orphan = withOrphan.nodes.find((n) => n.id === 'orphan')!+ expect(orphan.y1 - orphan.y0).toBe(0)++ // Probe inside the floored band but outside the raw box, so dropping the floor fails here.+ const hit = sankeyHitAt(withOrphan, { x: (orphan.x0 + orphan.x1) / 2, y: orphan.y0 + 0.5 })+ expect(hit).toEqual({ kind: 'node', index: withOrphan.nodes.indexOf(orphan) })+ })+})diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.tsnew file mode 100644index 000000000000..38145503bfb1--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-data.ts@@ -0,0 +1,372 @@+import { sankeyCenter, sankeyJustify, sankeyLayout, sankeyLeft, sankeyRight } from './sankey-layout'++/** A node of the flow graph. `id` must be unique; a node that occurs at several stages of a+ * flow (the same tool called twice in a row) needs one node per stage, so prefix the id with the+ * stage. Nodes with the same `label` share a palette color, so the repeated tool still reads+ * as one thing. */+export interface SankeyNodeInput<Meta = unknown> {+ id: string+ /** Display label. Defaults to `id`. */+ label?: string+ /** CSS color (hex, rgb, or `var(--…)`, resolved by the chart). Omit to pick a palette color+ * by label. */+ color?: string+ /** Consumer data handed back through tooltips and click handlers. */+ meta?: Meta+}++/** A directed flow from `source` to `target` (both node ids). The graph must be acyclic. */+export interface SankeyLinkInput<Meta = unknown> {+ source: string+ target: string+ value: number+ /** CSS color for the ribbon. Defaults to the source node's color. */+ color?: string+ /** Consumer data handed back through tooltips and click handlers. */+ meta?: Meta+}++/** How nodes spread across columns when a flow ends early. Mirrors d3-sankey's alignments. */+export type SankeyNodeAlign = 'left' | 'right' | 'center' | 'justify'++export interface SankeyNodeDatum<Meta = unknown> {+ id: string+ label: string+ color: string+ meta?: Meta+ column: number+ /** Sum of the larger side's link values (in or out). */+ value: number+ x0: number+ x1: number+ y0: number+ y1: number+}++/** A laid-out link: the input plus the ribbon geometry. `y0` is the centerline y at the source+ * edge, `y1` at the target edge; `width` is the ribbon thickness. */+export interface SankeyLinkDatum<NodeMeta = unknown, LinkMeta = NodeMeta> {+ source: SankeyNodeDatum<NodeMeta>+ target: SankeyNodeDatum<NodeMeta>+ value: number+ color: string+ meta?: LinkMeta+ y0: number+ y1: number+ width: number+}++export interface SankeyChartLayout<NodeMeta = unknown, LinkMeta = NodeMeta> {+ nodes: SankeyNodeDatum<NodeMeta>[]+ links: SankeyLinkDatum<NodeMeta, LinkMeta>[]+ columnCount: number+ /** Pixel x of each column's left edge, so overlays can place column headers. */+ columnX: number[]+ /** Total flow entering the graph: the summed value of the nodes with no incoming link.+ * Tooltips report each node and link as a share of this. */+ total: number+ nodeWidth: number+}++export interface SankeyPlotBox {+ plotLeft: number+ plotTop: number+ plotWidth: number+ plotHeight: number+}++export interface ComputeSankeyLayoutOptions<NodeMeta, LinkMeta = NodeMeta> {+ nodes: readonly SankeyNodeInput<NodeMeta>[]+ links: readonly SankeyLinkInput<LinkMeta>[]+ plot: SankeyPlotBox+ nodeWidth: number+ nodePadding: number+ nodeAlign: SankeyNodeAlign+ preserveNodeOrder: boolean+ colorForLabel: (label: string) => string+ /** Applied to every color before it reaches the canvas, so `var(--…)` inputs resolve. */+ resolveColor: (color: string) => string+}++interface LayoutNodeProps {+ id: string+ label: string+ color: string+ meta?: unknown+ [key: string]: unknown+}++interface LayoutLinkProps {+ source: string | LayoutNodeProps+ target: string | LayoutNodeProps+ value: number+ color?: string+ meta?: unknown+ [key: string]: unknown+}++const ALIGNMENTS = {+ left: sankeyLeft,+ right: sankeyRight,+ center: sankeyCenter,+ justify: sankeyJustify,+}++export function defaultValueFormatter(value: number): string {+ return value.toLocaleString()+}++export const EMPTY_SANKEY_LAYOUT: SankeyChartLayout<never> = {+ nodes: [],+ links: [],+ columnCount: 0,+ columnX: [],+ total: 0,+ nodeWidth: 0,+}++/** 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. */+function longestPathLength(+ nodes: readonly SankeyNodeInput<unknown>[],+ links: readonly SankeyLinkInput<unknown>[]+): number {+ const incoming = new Map<string, number>(nodes.map((node) => [node.id, 0]))+ const outgoing = new Map<string, string[]>()+ for (const link of links) {+ incoming.set(link.target, (incoming.get(link.target) ?? 0) + 1)+ const targets = outgoing.get(link.source)+ if (targets) {+ targets.push(link.target)+ } else {+ outgoing.set(link.source, [link.target])+ }+ }+ const depth = new Map<string, number>()+ 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) {+ ready.push(target)+ }+ }+ }+ return longest+}++/** Lays the graph out inside `plot`. Pure: safe to call from a memo or a test. Throws when a link+ * names a missing node or the graph has a cycle, so a consumer bug surfaces through the chart's+ * error boundary instead of drawing nothing. Returns `EMPTY_SANKEY_LAYOUT` when the graph has no+ * flow (all link values are zero). */+export function computeSankeyLayout<NodeMeta = unknown, LinkMeta = NodeMeta>({+ nodes,+ links,+ plot,+ nodeWidth,+ nodePadding,+ nodeAlign,+ preserveNodeOrder,+ 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>+ }++ const nodeIds = new Set<string>()+ for (const node of nodes) {+ if (nodeIds.has(node.id)) {+ throw new Error(`duplicate Sankey node id: ${node.id}`)+ }+ nodeIds.add(node.id)+ }+ for (const link of links) {+ if (!Number.isFinite(link.value) || link.value < 0) {+ throw new Error(`Sankey link value must be a finite non-negative number: ${link.value}`)+ }+ if (!nodeIds.has(link.source) || !nodeIds.has(link.target)) {+ throw new Error(`Sankey link refers to a missing node: ${link.source} -> ${link.target}`)+ }+ }+ if (!Number.isFinite(nodeWidth) || nodeWidth <= 0) {+ throw new Error(`Sankey nodeWidth must be a finite number above 0: ${nodeWidth}`)+ }+ 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))++ // 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 }+ })+ const engineLinks: LayoutLinkProps[] = links.map((link) => ({+ source: link.source,+ target: link.target,+ value: link.value,+ color: link.color,+ meta: link.meta,+ }))++ const graph = sankeyLayout<LayoutNodeProps, LayoutLinkProps>()+ .nodeId((node) => node.id)+ .nodeAlign(ALIGNMENTS[nodeAlign])+ .nodeSort(preserveNodeOrder ? null : undefined)+ .nodeWidth(effectiveNodeWidth)+ .nodePadding(nodePadding)+ .extent([+ [plot.plotLeft, plot.plotTop],+ [plot.plotLeft + plot.plotWidth, plot.plotTop + plot.plotHeight],+ ])({ nodes: engineNodes, links: engineLinks })++ const datumByIndex = new Map<number, SankeyNodeDatum<NodeMeta>>()+ const outNodes = graph.nodes.map((node): SankeyNodeDatum<NodeMeta> => {+ const datum: SankeyNodeDatum<NodeMeta> = {+ id: node.id,+ label: node.label,+ color: node.color,+ meta: node.meta as NodeMeta | undefined,+ column: node.layer,+ value: node.value,+ x0: node.x0,+ x1: node.x1,+ y0: node.y0,+ y1: node.y1,+ }+ datumByIndex.set(node.index, datum)+ return datum+ })++ const outLinks = graph.links.map((link): SankeyLinkDatum<NodeMeta, LinkMeta> => {+ const source = datumByIndex.get(link.source.index)!+ const target = datumByIndex.get(link.target.index)!+ return {+ source,+ target,+ value: link.value,+ color: link.color ? resolveColor(link.color) : source.color,+ meta: link.meta as LinkMeta | undefined,+ y0: link.y0,+ y1: link.y1,+ width: link.width,+ }+ })++ 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)+ 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.+ const total = graph.nodes+ .filter((node) => node.targetLinks.every((link) => link.value === 0))+ .reduce((sum, node) => sum + node.value, 0)++ // The layout engine produces NaN coordinates when there is no flow at all.+ if (links.every((link) => link.value === 0)) {+ return EMPTY_SANKEY_LAYOUT as SankeyChartLayout<NodeMeta, LinkMeta>+ }++ return { nodes: outNodes, links: outLinks, columnCount, columnX, total, nodeWidth: effectiveNodeWidth }+}++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+ * covers the cursor, else `null`. Ribbons are the cubic curves the canvas draws (control points+ * at the horizontal midpoint), so the test follows the painted shape exactly. */+export function sankeyHitAt(+ layout: SankeyChartLayout<unknown, unknown>,+ cursor: { x: number; y: number }+): SankeyHit | null {+ for (let i = 0; i < layout.nodes.length; i++) {+ const node = layout.nodes[i]+ const nodeHeight = Math.max(1, node.y1 - node.y0)+ const y0 = node.y0+ const y1 = y0 + nodeHeight+ if (cursor.x >= node.x0 && cursor.x <= node.x1 && cursor.y >= y0 && cursor.y <= y1) {+ return { kind: 'node', index: i }+ }+ }+ let best: { index: number; distance: number } | null = null+ for (let i = 0; i < layout.links.length; i++) {+ const link = layout.links[i]+ if (link.value === 0) {+ continue+ }+ const startX = link.source.x1+ const endX = link.target.x0+ if (cursor.x < startX || cursor.x > endX || endX <= startX) {+ continue+ }+ const halfWidth = Math.max(link.width, 1) / 2+ if (cursor.y < Math.min(link.y0, link.y1) - halfWidth || cursor.y > Math.max(link.y0, link.y1) + halfWidth) {+ continue+ }+ const distance = bezierDistance(startX, endX, link.y0, link.y1, cursor)+ if (distance <= halfWidth && (!best || distance < best.distance)) {+ best = { index: i, distance }+ }+ }+ return best ? { kind: 'link', index: best.index } : null+}++const MIN_CURVE_SAMPLES = 24+const MAX_CURVE_SAMPLES = 4096++function bezierDistance(x0: number, x1: number, y0: number, y1: number, cursor: { x: number; y: number }): number {+ // Each coordinate moves at most 1.5x its span per unit of t, so this count keeps adjacent+ // samples within 1px and a thin ribbon cannot fall between them.+ const samples = Math.min(+ MAX_CURVE_SAMPLES,+ Math.max(MIN_CURVE_SAMPLES, Math.ceil(1.5 * (Math.abs(x1 - x0) + Math.abs(y1 - y0))))+ )+ let best = Infinity+ for (let step = 0; step <= samples; step++) {+ const t = step / samples+ const distance = Math.hypot(bezierX(x0, x1, t) - cursor.x, bezierY(y0, y1, t) - cursor.y)+ best = Math.min(best, distance)+ }+ return best+}++/** x(t) of the ribbon centerline, with both control points at the horizontal midpoint. */+export function bezierX(x0: number, x1: number, t: number): number {+ const xm = (x0 + x1) / 2+ const u = 1 - t+ return u * u * u * x0 + 3 * u * u * t * xm + 3 * u * t * t * xm + t * t * t * x1+}++/** y(t) of the ribbon centerline: the control points share the end points' y, so the curve eases+ * from `y0` to `y1`. */+export function bezierY(y0: number, y1: number, t: number): number {+ const u = 1 - t+ return u * u * u * y0 + 3 * u * u * t * y0 + 3 * u * t * t * y1 + t * t * t * y1+}++/** Encodes a hit into the single `hoverIndex` the shared draw loop expects: nodes first, then+ * links offset by the node count. */+export function hitToHoverIndex(layout: SankeyChartLayout<unknown, unknown>, hit: SankeyHit | null): number {+ if (!hit) {+ return -1+ }+ return hit.kind === 'node' ? hit.index : layout.nodes.length + hit.index+}++export function hoverIndexToHit(layout: SankeyChartLayout<unknown, unknown>, hoverIndex: number): SankeyHit | null {+ if (hoverIndex < 0) {+ return null+ }+ if (hoverIndex < layout.nodes.length) {+ return { kind: 'node', index: hoverIndex }+ }+ const linkIndex = hoverIndex - layout.nodes.length+ return linkIndex < layout.links.length ? { kind: 'link', index: linkIndex } : null+}diff --git a/frontend/src/vendor/d3/sankey.ts b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.tssimilarity index 94%rename from frontend/src/vendor/d3/sankey.tsrename to packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.tsindex e15e17a504b2..a1ab2335eee0 100644--- a/frontend/src/vendor/d3/sankey.ts+++ b/packages/quill/packages/charts/src/charts/SankeyChart/sankey-layout.ts@@ -8,14 +8,14 @@* versions of the d3 modules we actually use.*/-import { Link, linkHorizontal } from 'd3'-import { max, min, sum } from 'd3'+import { max, min, sum } from 'd3-array'+import { type Link, linkHorizontal } from 'd3-shape'// ---- Public types -----export interface SankeyExtraProperties {- [key: string]: any-}+/** Consumer fields carried on nodes and links. Any object type qualifies; the layout adds its own+ * geometry fields on top. */+export type SankeyExtraProperties = objectexport type SankeyNode<N extends SankeyExtraProperties, L extends SankeyExtraProperties> = N & {sourceLinks: Array<SankeyLink<N, L>>@@ -47,7 +47,9 @@ export interface SankeyGraph<N extends SankeyExtraProperties, L extends SankeyExlinks: Array<SankeyLink<N, L>>}-export type SankeyInputGraph = { nodes: any[]; links: any[] }+/** Input graph. Link `source`/`target` may be node ids (resolved through `nodeId`) or node+ * objects; the layout mutates both arrays in place, so pass copies of data you keep. */+export type SankeyInputGraph = { nodes: object[]; links: object[] }export interface SankeyLayout<N extends SankeyExtraProperties, L extends SankeyExtraProperties> {(graph: SankeyInputGraph): SankeyGraph<N, L>@@ -91,7 +93,7 @@ export function targetDepth(d: SankeyLink<{}, {}>): number {}export function sankeyRight(node: SankeyNode<{}, {}>, n: number): number {- return n - 1 - node.depth+ return n - 1 - node.height}export function sankeyLeft(node: SankeyNode<{}, {}>): number {@@ -125,7 +127,7 @@ function horizontalTarget<N extends SankeyExtraProperties, L extends SankeyExtra}export function sankeyLinkHorizontal<N extends SankeyExtraProperties, L extends SankeyExtraProperties>(): Link<- any,+ unknown,SankeyLink<N, L>,[number, number]> {@@ -188,9 +190,11 @@ function computeLinkBreadths<N extends SankeyExtraProperties, L extends SankeyEx// ---- Main sankey factory -----export default function sankey<- N extends SankeyExtraProperties = any,- L extends SankeyExtraProperties = any,+export function sankeyLayout<+ N extends SankeyExtraProperties = { id: string },+ // Laid-out links replace `source`/`target` with node objects, so the default must not type them+ // as strings.+ L extends SankeyExtraProperties = SankeyExtraProperties,>(): SankeyLayout<N, L> {let x0 = 0,y0 = 0,@@ -203,10 +207,10 @@ export default function sankey<let id: (d: SankeyNode<N, L>) => string | number = (d) => d.indexlet align: (node: SankeyNode<N, L>, n: number) => number = sankeyJustifylet sort: ((a: SankeyNode<N, L>, b: SankeyNode<N, L>) => number) | null | undefined- let nodesFn: (graph: SankeyInputGraph) => SankeyNode<N, L>[] = (graph) => graph.nodes- let linksFn: (graph: SankeyInputGraph) => SankeyLink<N, L>[] = (graph) => graph.links+ 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>[]- let sankeyLayout: SankeyLayout<N, L>+ let self: SankeyLayout<N, L>function layout(graph: SankeyInputGraph): SankeyGraph<N, L> {const g = { nodes: nodesFn(graph), links: linksFn(graph) }@@ -232,7 +236,7 @@ export default function sankey<): ((graph: SankeyInputGraph) => SankeyNode<N, L>[]) | SankeyLayout<N, L> {if (fn) {nodesFn = typeof fn === 'function' ? fn : () => fn- return sankeyLayout+ return self}return nodesFn}@@ -245,7 +249,7 @@ export default function sankey<): ((graph: SankeyInputGraph) => SankeyLink<N, L>[]) | SankeyLayout<N, L> {if (fn) {linksFn = typeof fn === 'function' ? fn : () => fn- return sankeyLayout+ return self}return linksFn}@@ -257,7 +261,7 @@ export default function sankey<): ((node: SankeyNode<N, L>) => string | number) | SankeyLayout<N, L> {if (fn) {id = fn- return sankeyLayout+ return self}return id}@@ -269,7 +273,7 @@ export default function sankey<): ((node: SankeyNode<N, L>, n: number) => number) | SankeyLayout<N, L> {if (fn) {align = fn- return sankeyLayout+ return self}return align}@@ -283,7 +287,7 @@ export default function sankey<): ((a: SankeyNode<N, L>, b: SankeyNode<N, L>) => number) | undefined | null | SankeyLayout<N, L> {if (arguments.length) {sort = fn- return sankeyLayout+ return self}return sort}@@ -293,7 +297,7 @@ export default function sankey<function nodeWidthAccessor(width?: number): number | SankeyLayout<N, L> {if (width !== undefined) {dx = width- return sankeyLayout+ return self}return dx}@@ -303,7 +307,7 @@ export default function sankey<function nodePaddingAccessor(padding?: number): number | SankeyLayout<N, L> {if (padding !== undefined) {dy = py = padding- return sankeyLayout+ return self}return dy}@@ -315,7 +319,7 @@ export default function sankey<x0 = y0 = 0x1 = size[0]y1 = size[1]- return sankeyLayout+ return self}return [x1 - x0, y1 - y0]}@@ -330,7 +334,7 @@ export default function sankey<y0 = extent[0][1]x1 = extent[1][0]y1 = extent[1][1]- return sankeyLayout+ return self}return [[x0, y0],@@ -338,7 +342,7 @@ export default function sankey<] satisfies [[number, number], [number, number]]}- sankeyLayout = Object.assign(layout, {+ self = Object.assign(layout, {update,nodes: nodesAccessor,links: linksAccessor,@@ -620,5 +624,5 @@ export default function sankey<return y}- return sankeyLayout+ return self}diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts b/packages/quill/packages/charts/src/charts/SankeyChart/types.tsnew file mode 100644index 000000000000..59fc9d715cf1--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts@@ -0,0 +1,62 @@+import type React from 'react'++import type { ChartMargins, ChartTheme, TooltipContext } from '../../core/types'+import type { SankeyLinkDatum, SankeyLinkInput, SankeyNodeAlign, SankeyNodeDatum, SankeyNodeInput } from './sankey-data'++export type SankeyTooltipHit<NodeMeta = unknown, LinkMeta = NodeMeta> =+ | { kind: 'node'; node: SankeyNodeDatum<NodeMeta> }+ | { kind: 'link'; link: SankeyLinkDatum<NodeMeta, LinkMeta> }++/** Tooltip context for a Sankey hover: the base `TooltipContext` (one `seriesData` row for the+ * hovered node or ribbon) plus the resolved `hit` and the graph `total` for share math. */+export type SankeyTooltipContext<NodeMeta = unknown, LinkMeta = NodeMeta> = TooltipContext<NodeMeta | LinkMeta> & {+ hit: SankeyTooltipHit<NodeMeta, LinkMeta>+ total: number+}++export interface SankeyChartConfig {+ /** Node rectangle width in px. Defaults to 12. */+ nodeWidth?: number+ /** Vertical gap between nodes in one column, in px. Defaults to 8. */+ nodePadding?: number+ /** Column placement for flows that end early. `justify` (default) pushes terminal nodes to the+ * last column; `left` keeps every node at its own depth, which is the right choice when the+ * columns are stages (first tool, second tool, …). */+ nodeAlign?: SankeyNodeAlign+ /** Keep nodes in input order within each column instead of ordering them to untangle ribbons. */+ preserveNodeOrder?: boolean+ /** Header text for each column, left to right. Reserves room above the plot. */+ columnLabels?: string[]+ /** Defaults to true. */+ showNodeLabels?: boolean+ /** Append the node's value to its label. Defaults to false. */+ showNodeValues?: boolean+ /** Resting ribbon opacity, 0..1. Defaults to 0.4. */+ linkOpacity?: number+ /** Formats values in node labels and the default tooltip. Defaults to `toLocaleString`. */+ valueFormatter?: (value: number) => string+ tooltip?: {+ /** Show the tooltip on hover. Defaults to true. */+ enabled?: boolean+ /** Where the tooltip sits, as on the cartesian charts. Defaults to `cursor`; `follow-data`+ * 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. */+ margins?: Partial<ChartMargins>+}++export interface SankeyChartProps<NodeMeta = unknown, LinkMeta = NodeMeta> {+ nodes: SankeyNodeInput<NodeMeta>[]+ links: SankeyLinkInput<LinkMeta>[]+ theme: ChartTheme+ config?: SankeyChartConfig+ tooltip?: (ctx: SankeyTooltipContext<NodeMeta, LinkMeta>) => React.ReactNode+ onNodeClick?: (node: SankeyNodeDatum<NodeMeta>) => void+ onLinkClick?: (link: SankeyLinkDatum<NodeMeta, LinkMeta>) => void+ className?: string+ dataAttr?: string+ /** Overlays rendered above the canvas. Read the layout with `useSankeyLayout()`. */+ children?: React.ReactNode+ onError?: (error: Error, info: React.ErrorInfo) => void+}diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts b/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.tsnew file mode 100644index 000000000000..77066c9e06eb--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SankeyChart/useSankeyInteraction.ts@@ -0,0 +1,215 @@+import React, { useCallback, useEffect, useMemo } from 'react'++import { originatesInInteractiveOverlay } from '../../core/hooks/useChartInteraction'+import { useLatest } from '../../core/hooks/useLatest'+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 { SankeyTooltipContext, SankeyTooltipHit } from './types'++interface UseSankeyInteractionOptions<NodeMeta, LinkMeta> {+ layout: SankeyChartLayout<NodeMeta, LinkMeta>+ canvasRef: React.RefObject<HTMLCanvasElement>+ wrapperRef: React.RefObject<HTMLDivElement>+ showTooltip: boolean+ onNodeClick?: (node: SankeyNodeDatum<NodeMeta>) => void+ onLinkClick?: (link: SankeyLinkDatum<NodeMeta, LinkMeta>) => void+}++interface UseSankeyInteractionResult<NodeMeta, LinkMeta> {+ hoverIndex: number+ hoverPosition: { x: number; y: number } | null+ tooltipCtx: SankeyTooltipContext<NodeMeta, LinkMeta> | null+ handlers: {+ onMouseMove: (e: React.MouseEvent<HTMLDivElement>) => void+ onMouseLeave: () => void+ onClick: (e: React.MouseEvent<HTMLDivElement>) => void+ onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => void+ }+}++function resolveHit<NodeMeta, LinkMeta>(+ layout: SankeyChartLayout<NodeMeta, LinkMeta>,+ hit: SankeyHit+): SankeyTooltipHit<NodeMeta, LinkMeta> {+ return hit.kind === 'node'+ ? { kind: 'node', node: layout.nodes[hit.index] }+ : { kind: 'link', link: layout.links[hit.index] }+}++function buildTooltipCtx<NodeMeta, LinkMeta>(+ layout: SankeyChartLayout<NodeMeta, LinkMeta>,+ hit: SankeyHit,+ cursor: { x: number; y: number } | null,+ canvasBounds: DOMRect+): SankeyTooltipContext<NodeMeta, LinkMeta> {+ const resolved = resolveHit(layout, hit)+ const label =+ resolved.kind === 'node' ? resolved.node.label : `${resolved.link.source.label} → ${resolved.link.target.label}`+ const value = resolved.kind === 'node' ? resolved.node.value : resolved.link.value+ const color = resolved.kind === 'node' ? resolved.node.color : resolved.link.color+ const meta: NodeMeta | LinkMeta | undefined = resolved.kind === 'node' ? resolved.node.meta : resolved.link.meta+ const anchor =+ resolved.kind === 'node'+ ? { x: resolved.node.x1, y: (resolved.node.y0 + resolved.node.y1) / 2 }+ : {+ x: (resolved.link.source.x1 + resolved.link.target.x0) / 2,+ y: (resolved.link.y0 + resolved.link.y1) / 2,+ }+ // One synthetic series row keeps the shared tooltip plumbing (equivalence checks, the+ // default renderer fallback) working on a chart that has no series.+ const series: Series<NodeMeta | LinkMeta> = { key: `${hit.kind}:${hit.index}`, label, data: [value], color, meta }+ const fraction = layout.total > 0 ? value / layout.total : 0+ return {+ dataIndex: hitToHoverIndex(layout, hit),+ label,+ seriesData: [{ series, value, color, fraction }],+ position: anchor,+ hoverPosition: cursor,+ canvasBounds,+ isPinned: false,+ hit: resolved,+ total: layout.total,+ }+}++export function useSankeyInteraction<NodeMeta = unknown, LinkMeta = NodeMeta>({+ layout,+ canvasRef,+ wrapperRef,+ showTooltip,+ onNodeClick,+ onLinkClick,+}: UseSankeyInteractionOptions<NodeMeta, LinkMeta>): UseSankeyInteractionResult<NodeMeta, LinkMeta> {+ type Ctx = SankeyTooltipContext<NodeMeta, LinkMeta>+ const layoutRef = useLatest(layout)++ const rebuildPinnedCtx = useCallback(+ (prev: TooltipContext<NodeMeta | LinkMeta>): Ctx | null => {+ const hit = hoverIndexToHit(layoutRef.current, prev.dataIndex)+ if (!hit) {+ return null+ }+ const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()+ return buildTooltipCtx(layoutRef.current, hit, prev.hoverPosition, canvasBounds)+ },+ [layoutRef, canvasRef]+ )++ const { hoverIndex, hoverPosition, tooltipCtx, isPinned, setHover, setTooltipCtx, clearTooltip } =+ useTooltipLifecycle<NodeMeta | LinkMeta>({+ wrapperRef,+ rebuildPinnedCtx,+ rebuildDeps: [layout],+ })++ useEffect(() => {+ if (!isPinned) {+ clearTooltip()+ }+ }, [layout, isPinned, clearTooltip])++ // Hidden content must not survive to reappear when tooltips are switched back on.+ useEffect(() => {+ if (!showTooltip) {+ setTooltipCtx(null)+ }+ }, [showTooltip, setTooltipCtx])++ const hoverIndexRef = useLatest(hoverIndex)++ const showHit = useCallback(+ (hit: SankeyHit, cursor: { x: number; y: number }) => {+ setHover(hitToHoverIndex(layoutRef.current, hit), cursor)+ if (!showTooltip) {+ setTooltipCtx(null)+ return+ }+ const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()+ setTooltipCtx(buildTooltipCtx(layoutRef.current, hit, cursor, canvasBounds))+ },+ [layoutRef, showTooltip, setHover, setTooltipCtx, canvasRef]+ )++ const onMouseMove = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ const current = layoutRef.current+ if (current.nodes.length === 0) {+ 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)+ if (!hit) {+ clearTooltip()+ return+ }+ showHit(hit, cursor)+ },+ [layoutRef, showHit, clearTooltip]+ )++ const onMouseLeave = useCallback(() => {+ clearTooltip()+ }, [clearTooltip])++ // 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.+ const { lastPointerTypeRef, tapDownTooltipIndexRef, onPointerDown } = useTapTracking(tooltipCtx)++ const onClick = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ if (originatesInInteractiveOverlay(e)) {+ return+ }+ 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)+ if (lastPointerTypeRef.current === 'touch') {+ hit = sankeyHitAt(current, cursor)+ if (!hit) {+ clearTooltip()+ return+ }+ if (hitToHoverIndex(current, hit) !== tapDownTooltipIndexRef.current) {+ showHit(hit, cursor)+ if (showTooltip) {+ return+ }+ }+ }+ if (!hit) {+ return+ }+ const resolved = resolveHit(current, hit)+ if (resolved.kind === 'node') {+ onNodeClick?.(resolved.node)+ } else {+ onLinkClick?.(resolved.link)+ }+ },+ [+ layoutRef,+ hoverIndexRef,+ lastPointerTypeRef,+ tapDownTooltipIndexRef,+ clearTooltip,+ showHit,+ showTooltip,+ onNodeClick,+ onLinkClick,+ ]+ )++ const handlers = useMemo(+ () => ({ onMouseMove, onMouseLeave, onClick, onPointerDown }),+ [onMouseMove, onMouseLeave, onClick, onPointerDown]+ )++ // The lifecycle stores the base context; every value it holds was built by `buildTooltipCtx`,+ // so the extra Sankey fields are present.+ return { hoverIndex, hoverPosition, tooltipCtx: tooltipCtx as Ctx | null, handlers }+}diff --git a/packages/quill/packages/charts/src/core/ChartErrorBoundary.tsx b/packages/quill/packages/charts/src/core/ChartErrorBoundary.tsxindex 02d9e6c93be9..95f104647947 100644--- a/packages/quill/packages/charts/src/core/ChartErrorBoundary.tsx+++ b/packages/quill/packages/charts/src/core/ChartErrorBoundary.tsx@@ -4,6 +4,7 @@ interface ChartErrorBoundaryProps {children: React.ReactNodefallback?: React.ReactNodeonError?: (error: Error, info: React.ErrorInfo) => void+ resetKey?: unknown}interface ChartErrorBoundaryState {@@ -33,6 +34,12 @@ export class ChartErrorBoundary extends React.Component<ChartErrorBoundaryProps,this.props.onError?.(error, info)}+ override componentDidUpdate(prevProps: ChartErrorBoundaryProps): void {+ if (this.state.hasError && prevProps.resetKey !== this.props.resetKey) {+ this.setState({ hasError: false })+ }+ }+override render(): React.ReactNode {if (this.state.hasError) {return (diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.tsindex f9127205e239..1908b8c238ee 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts@@ -1,4 +1,4 @@-import React, { useCallback, useMemo, useRef } from 'react'+import React, { useCallback, useMemo } from 'react'import { findClosestSeriesKey } from '../../overlays/tooltipUtils'import {@@ -22,6 +22,7 @@ import type {} from '../types'import { useDragToZoom } from './useDragToZoom'import { useLatest } from './useLatest'+import { useTapTracking } from './useTapTracking'import { useTooltipLifecycle } from './useTooltipLifecycle'function originatesInElement(e: React.SyntheticEvent, selector: string): boolean {@@ -40,7 +41,7 @@ function originatesInTooltip(e: React.SyntheticEvent): boolean {* 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. */-function originatesInInteractiveOverlay(e: React.SyntheticEvent): boolean {+export function originatesInInteractiveOverlay(e: React.SyntheticEvent): boolean {return originatesInElement(e, '[data-hog-charts-interactive-overlay]')}@@ -353,24 +354,7 @@ export function useChartInteraction<Meta = unknown>({clearTooltip()}, [isPinned, clearTooltip])- // Touch support state. Touch devices fire no mousemove before a tap, so hover state is- // absent (or stale) when the tap's click arrives; the click handler must resolve the tapped- // point itself. `lastPointerTypeRef` tells it whether the click came from a touch, and- // `tapDownTooltipIndexRef` records which point's tooltip was showing when the gesture- // started. Both are captured at pointerdown because a tap's compatibility mouse events- // (mouseover/mousemove/mousedown) fire after pointerup, which means by click time the- // tooltip state may already reflect this very tap.- const tooltipCtxRef = useLatest(tooltipCtx)- const lastPointerTypeRef = useRef<string>('mouse')- const tapDownTooltipIndexRef = useRef<number>(-1)-- const onPointerDown = useCallback(- (e: React.PointerEvent<HTMLDivElement>) => {- lastPointerTypeRef.current = e.pointerType- tapDownTooltipIndexRef.current = tooltipCtxRef.current?.dataIndex ?? -1- },- [tooltipCtxRef]- )+ const { lastPointerTypeRef, tapDownTooltipIndexRef, onPointerDown } = useTapTracking(tooltipCtx)const onClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {@@ -489,6 +473,8 @@ export function useChartInteraction<Meta = unknown>({unpin,shouldSwallowClick,hoverIndexRef,+ lastPointerTypeRef,+ tapDownTooltipIndexRef,hoverPositionRef,wrapClickData,scales,diff --git a/packages/quill/packages/charts/src/core/hooks/useTapTracking.ts b/packages/quill/packages/charts/src/core/hooks/useTapTracking.tsnew file mode 100644index 000000000000..40b09e24c5a8--- /dev/null+++ b/packages/quill/packages/charts/src/core/hooks/useTapTracking.ts@@ -0,0 +1,32 @@+import type { MutableRefObject } from 'react'+import React, { useCallback, useRef } from 'react'++import { useLatest } from './useLatest'++export interface TapTracking {+ lastPointerTypeRef: MutableRefObject<string>+ /** The `dataIndex` of the tooltip that was visible when the gesture started, or -1. */+ tapDownTooltipIndexRef: MutableRefObject<number>+ onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => void+}++// Touch devices fire no mousemove before a tap, so a click handler has to resolve the tapped+// point itself and needs to know whether the click came from a touch. Both refs are captured at+// pointerdown because a tap's compatibility mouse events fire after pointerup, so by click time+// the tooltip may already reflect this very tap. Read the visible tooltip, not the hover: hover+// can outlive a tooltip that was just hidden.+export function useTapTracking(tooltipCtx: { dataIndex: number } | null): TapTracking {+ const tooltipCtxRef = useLatest(tooltipCtx)+ const lastPointerTypeRef = useRef<string>('mouse')+ const tapDownTooltipIndexRef = useRef<number>(-1)++ const onPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ lastPointerTypeRef.current = e.pointerType+ tapDownTooltipIndexRef.current = tooltipCtxRef.current?.dataIndex ?? -1+ },+ [tooltipCtxRef]+ )++ return { lastPointerTypeRef, tapDownTooltipIndexRef, onPointerDown }+}diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.mdindex 97562ebaec00..cdec9f04bbc5 100644--- a/packages/quill/packages/charts/src/docs/chart-types.md+++ b/packages/quill/packages/charts/src/docs/chart-types.md@@ -87,6 +87,31 @@ A 2D density grid: `xLabels` by `yLabels` (row 0 at the bottom), `cells[row][colLog ramp by default; `colorScale: 'linear'` to opt out.A single-cell tooltip resolves from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }`, and `onBrush` reports row and column index ranges.+## SankeyChart++Flow between stages: `nodes: { id, label?, color?, meta? }[]` and `links: { source, target, value, color?, meta? }[]`, where `source` and `target` are node ids.+There is no `series` or `labels`.++- Node ids must be unique. The graph must be acyclic, every link must name existing nodes, and link values must be finite and non-negative; the layout throws otherwise, and the chart's error boundary reports it through `onError`.+ A node that recurs at several stages (the same tool called twice) needs one id per stage, so prefix ids with the stage.+- Nodes that share a `label` share a palette color, so a repeated tool keeps one hue across columns.+ A link without `color` takes its source node's color.+ `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.+ 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.+ `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).+ `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.+- Custom overlays read `useSankeyLayout()` for the positioned `nodes`, `links`, `columnX`, and `total`.+- 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.+## SparklineAn axis-less preset over `LineChart` (default, gradient-filled line) or stacked bars via `type: 'bar'`.diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex eca71fa81035..41993fcb728b 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -117,6 +117,41 @@ export type { RadialSlicePayload } from './core/hooks/useRadialInteraction'export { ProportionBar } from './charts/ProportionBar/ProportionBar'export type { ProportionBarConfig, ProportionBarProps } from './charts/ProportionBar/ProportionBar'+// Sankey+export { SankeyChart } from './charts/SankeyChart/SankeyChart'+export type {+ SankeyChartConfig,+ SankeyChartProps,+ SankeyTooltipContext,+ SankeyTooltipHit,+} from './charts/SankeyChart/types'+export type {+ SankeyChartLayout,+ SankeyLinkDatum,+ SankeyLinkInput,+ SankeyNodeAlign,+ SankeyNodeDatum,+ SankeyNodeInput,+} from './charts/SankeyChart/sankey-data'+export { useSankeyLayout } from './charts/SankeyChart/sankey-context'+export type { SankeyLayoutContextValue } from './charts/SankeyChart/sankey-context'+// The layout engine on its own, for hosts that draw their own SVG (user paths).+export {+ sankeyCenter,+ sankeyJustify,+ sankeyLayout,+ sankeyLeft,+ sankeyLinkHorizontal,+ sankeyRight,+} from './charts/SankeyChart/sankey-layout'+export type {+ SankeyGraph,+ SankeyInputGraph,+ SankeyLayout,+ SankeyLink,+ SankeyNode,+} from './charts/SankeyChart/sankey-layout'+// Chart context (for custom overlay children)export { useChart, useChartHover, useChartLayout } from './core/chart-context'export type { BaseChartContext, ChartHoverContextValue, ChartLayoutContextValue } from './core/chart-context'@@ -210,8 +245,4 @@ export { ChartLegend } from './components/Legend/ChartLegend'export type { ChartLegendProps } from './components/Legend/ChartLegend'export { legendItemsFromSeries } from './components/Legend/legendItemsFromSeries'export { useChartLegend, applyHiddenSeries } from './components/Legend/useChartLegend'-export type {- ChartLegendRenderProps,- ChartLegendState,- LegendItemControls,-} from './components/Legend/useChartLegend'+export type { ChartLegendRenderProps, ChartLegendState, LegendItemControls } from './components/Legend/useChartLegend'diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.tsindex 3e3436290f5d..e18579d6a171 100644--- a/packages/quill/packages/charts/src/testing/accessor.ts+++ b/packages/quill/packages/charts/src/testing/accessor.ts@@ -91,14 +91,18 @@ export interface HogChart<Meta = unknown> {/** Series name labels currently rendered by a slope chart (post-collision-avoidance). */slopeSeriesLabels(): string[]/** Legend rows in this chart's render scope — label plus the row's secondary text (a slope- * chart's change, a proportion bar's `share · value`), or null when the row has none. Empty when- * the legend is hidden. */+ * chart's change, a proportion bar's `share · value`), or null when none. Empty when the+ * legend is hidden. */legendItems(): LegendItemSummary[]/** @deprecated Use `legendItems()`, which reads any chart's legend. */slopeLegendItems(): LegendItemSummary[]/** Click the legend row with this label. `additive` holds ⌘/Ctrl, which toggles that one series* instead of isolating it. Throws when no legend row has the label. */clickLegendItem(label: string, options?: { additive?: boolean }): void+ /** Node labels rendered by a Sankey chart, in layout order. */+ sankeyNodeLabels(): string[]+ /** Column headers rendered by a Sankey chart, left to right. */+ sankeyColumnLabels(): string[]/** Annotation badges currently rendered. */annotationBadges(): HTMLElement[]/** Fire a `mouseMove` over the data point at `index`. Only available when the chart was@@ -248,6 +252,14 @@ export function getHogChart<Meta = unknown>(fireEvent.click(row, { metaKey: additive })})},+ sankeyNodeLabels: () =>+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-sankey-node-label"]')).map(+ (el) => el.textContent ?? ''+ ),+ sankeyColumnLabels: () =>+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-sankey-column-label"]')).map(+ (el) => el.textContent ?? ''+ ),annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),hoverAtIndex(index: number): void {if (totalLabels === undefined) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9f323d3410a2..2dfcb405e182 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2076,6 +2076,9 @@ importers:'@floating-ui/react':specifier: ^0.27.19+ '@types/d3-shape':+ specifier: ^3.1.6+ version: 3.1.8d3-array:specifier: ^3.2.4version: 3.2.4@@ -2122,9 +2125,6 @@ importers:'@types/d3-scale':specifier: ^4.0.8version: 4.0.9- '@types/d3-shape':- specifier: ^3.1.6- version: 3.1.8'@types/jest':specifier: 'catalog:'version: 29.5.14diff --git a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsxindex 50d6a7bfc0c1..d1468a47a0dd 100644--- a/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx+++ b/products/mcp_analytics/frontend/clustering/ClusterJourneySankey.tsx@@ -1,41 +1,37 @@import { useMemo } from 'react'-import { Tooltip } from '@posthog/lemon-ui'-import type { ChartTheme } from '@posthog/quill-charts'+import { SankeyChart } from '@posthog/quill-charts'+import type {+ ChartTheme,+ SankeyChartConfig,+ SankeyLinkInput,+ SankeyNodeInput,+ SankeyTooltipContext,+} from '@posthog/quill-charts'import { useChartTheme } from 'lib/charts/hooks'-import sankey, { sankeyLeft, sankeyLinkHorizontal } from '~/vendor/d3/sankey'--import type { MCPIntentClusterJourneyApi, MCPIntentClusterJourneyPathApi } from '../generated/api.schemas'+import type { MCPIntentClusterJourneyApi } from '../generated/api.schemas'+import {+ buildJourneyGraph,+ describeJourneyPath,+ JOURNEY_COLUMN_LABELS,+ type JourneyLinkMeta,+ type JourneyNodeKind,+ type JourneyNodeMeta,+} from './clusterJourneyGraph'+import { JourneyTooltip } from './JourneyTooltip'import { ERROR_SERIES, PRIMARY_SERIES, seriesColor } from './seriesColors'-const WIDTH = 720-const HEIGHT = 300-const COLUMN_LABELS = ['Init', '1st tool', '2nd tool', '3rd tool', '4th tool', 'Outcome']-const ENDED_LABEL = 'Ended'--type NodeKind = 'init' | 'tool' | 'ended' | 'completed' | 'error'--interface JourneyNode {- name: string- column: number- kind: NodeKind-}--interface JourneyLink {- source: number- target: number- value: number- outcome: 'completed' | 'error'+// Flows that end early stay in their own stage column instead of being pushed to the outcome.+const CHART_CONFIG: SankeyChartConfig = {+ columnLabels: JOURNEY_COLUMN_LABELS,+ nodeAlign: 'left',+ preserveNodeOrder: true,+ linkOpacity: 0.45,}-function describePath(path: MCPIntentClusterJourneyPathApi): string {- const labels = path.steps.map((step) => step ?? ENDED_LABEL)- return labels.filter((label, idx) => label !== ENDED_LABEL || idx === labels.indexOf(ENDED_LABEL)).join(' → ')-}--function nodeFill(kind: NodeKind, theme: ChartTheme): string {+function nodeFill(kind: JourneyNodeKind, theme: ChartTheme): string {switch (kind) {case 'init':return 'var(--muted)'@@ -51,63 +47,15 @@ function nodeFill(kind: NodeKind, theme: ChartTheme): string {}}-function buildGraph(paths: readonly MCPIntentClusterJourneyPathApi[]): {- nodes: JourneyNode[]- links: JourneyLink[]-} {- const nodeIndex = new Map<string, number>()- const nodes: JourneyNode[] = []-- const getNode = (column: number, name: string, kind: NodeKind): number => {- const key = `${column}::${name}`- const existing = nodeIndex.get(key)- if (existing !== undefined) {- return existing- }- const idx = nodes.length- nodeIndex.set(key, idx)- nodes.push({ name, column, kind })- return idx- }-- const linkMap = new Map<string, JourneyLink>()- const initIdx = getNode(0, 'Init', 'init')-- for (const path of paths) {- const columns: { name: string; kind: NodeKind }[] = [{ name: 'Init', kind: 'init' }]- for (const step of path.steps) {- if (step === null) {- columns.push({ name: ENDED_LABEL, kind: 'ended' })- } else {- columns.push({ name: step, kind: 'tool' })- }- }- columns.push({- name: path.outcome === 'error' ? 'Error' : 'Completed',- kind: path.outcome === 'error' ? 'error' : 'completed',- })-- for (let i = 0; i < columns.length - 1; i++) {- const sourceCol = i === 0 ? 0 : i- const targetCol = sourceCol + 1- const src = sourceCol === 0 ? initIdx : getNode(sourceCol, columns[i].name, columns[i].kind)- const tgt = getNode(targetCol, columns[i + 1].name, columns[i + 1].kind)- const linkKey = `${src}->${tgt}::${path.outcome}`- const existing = linkMap.get(linkKey)- if (existing) {- existing.value += path.count- } else {- linkMap.set(linkKey, {- source: src,- target: tgt,- value: path.count,- outcome: path.outcome === 'error' ? 'error' : 'completed',- })- }- }+// Shares divide by every session in the cluster, not just the displayed top paths, so a subset never reads as 100%.+function makeJourneyTooltip(+ totalSessions: number+): (ctx: SankeyTooltipContext<JourneyNodeMeta, JourneyLinkMeta>) => JSX.Element {+ return function JourneyTooltipAdapter({+ hit,+ }: SankeyTooltipContext<JourneyNodeMeta, JourneyLinkMeta>): JSX.Element {+ return <JourneyTooltip hit={hit} totalSessions={totalSessions} />}-- return { nodes, links: Array.from(linkMap.values()) }}interface Props {@@ -116,28 +64,26 @@ interface Props {export function ClusterJourneySankey({ journey }: Props): JSX.Element | null {const theme = useChartTheme()- const graph = useMemo(() => (journey ? buildGraph(journey.paths) : { nodes: [], links: [] }), [journey])- const layout = useMemo(() => {- if (graph.nodes.length === 0 || graph.links.length === 0) {+ const graph = useMemo(() => {+ if (!journey) {return null}- // d3-sankey mutates the inputs, so deep-copy before passing.- const layoutFn = sankey<JourneyNode, JourneyLink>()- .nodeWidth(18)- .nodePadding(10)- .nodeAlign(sankeyLeft)- .extent([- [4, 14],- [WIDTH - 4, HEIGHT - 14],- ])- return layoutFn({- nodes: graph.nodes.map((n) => ({ ...n })),- links: graph.links.map((l) => ({ ...l })),- })- }, [graph])-- if (!journey || !layout) {+ const built = buildJourneyGraph(journey.paths)+ const nodes: SankeyNodeInput<JourneyNodeMeta>[] = built.nodes.map((node) => ({+ ...node,+ color: nodeFill(node.meta?.kind ?? 'tool', theme),+ }))+ const links: SankeyLinkInput<JourneyLinkMeta>[] = built.links.map((link) => ({+ ...link,+ color: seriesColor(theme, link.meta?.outcome === 'error' ? ERROR_SERIES : PRIMARY_SERIES),+ }))+ return { nodes, links }+ }, [journey, theme])++ const tooltip = useMemo(() => makeJourneyTooltip(journey?.total_sessions ?? 0), [journey?.total_sessions])++ if (!journey || !graph || !graph.links.some((link) => link.value > 0)) {return (<div className="bg-surface-secondary rounded p-4 text-xs text-muted">Not enough session data yet to plot a journey. Recompute after more sessions are summarised.@@ -145,106 +91,27 @@ export function ClusterJourneySankey({ journey }: Props): JSX.Element | null {)}- const linkGen = sankeyLinkHorizontal<JourneyNode, JourneyLink>()-return (<div className="flex flex-col gap-2"><div className="text-xs text-muted">{journey.total_sessions} session{journey.total_sessions === 1 ? '' : 's'} · top {journey.paths.length}{' '}path{journey.paths.length === 1 ? '' : 's'}</div>- <div className="overflow-x-auto">- <svg width={WIDTH} height={HEIGHT} className="block">- <g>- {COLUMN_LABELS.map((label, idx) => {- const colWidth = (WIDTH - 8) / COLUMN_LABELS.length- const x = 4 + colWidth * idx + colWidth / 2- return (- <text- key={label}- x={x}- y={10}- textAnchor="middle"- className="fill-[var(--muted)]"- fontSize={9}- >- {label}- </text>- )- })}- </g>- <g>- {layout.links.map((link, idx) => {- const path = linkGen(link) ?? ''- const stroke = seriesColor(theme, link.outcome === 'error' ? ERROR_SERIES : PRIMARY_SERIES)- const sourceName = (link.source as unknown as JourneyNode).name- const targetName = (link.target as unknown as JourneyNode).name- const pct =- journey.total_sessions > 0- ? Math.round((link.value / journey.total_sessions) * 1000) / 10- : 0- return (- <Tooltip- key={idx}- title={- <div className="flex flex-col gap-0.5">- <span className="font-semibold">- {sourceName} → {targetName}- </span>- <span>- {link.value} session{link.value === 1 ? '' : 's'} ({pct}%)- </span>- <span className="text-muted">- Outcome: {link.outcome === 'error' ? 'error' : 'completed'}- </span>- </div>- }- >- <path- d={path}- fill="none"- // eslint-disable-next-line react/forbid-dom-props- style={{- stroke,- strokeOpacity: 0.45,- strokeWidth: Math.max(1, link.width),- }}- />- </Tooltip>- )- })}- </g>- <g>- {layout.nodes.map((node, idx) => (- <g key={idx}>- <rect- x={node.x0}- y={node.y0}- width={node.x1 - node.x0}- height={Math.max(1, node.y1 - node.y0)}- rx={2}- // eslint-disable-next-line react/forbid-dom-props- style={{ fill: nodeFill(node.kind, theme) }}- />- <text- x={node.x0 + (node.x1 - node.x0) / 2}- y={node.y1 + 10}- textAnchor="middle"- className="fill-[var(--text-primary)]"- fontSize={10}- >- <tspan>{node.name}</tspan>- </text>- </g>- ))}- </g>- </svg>+ <div className="flex h-[300px] w-full">+ <SankeyChart+ nodes={graph.nodes}+ links={graph.links}+ theme={theme}+ config={CHART_CONFIG}+ tooltip={tooltip}+ dataAttr="mcp-cluster-journey-sankey"+ /></div>{journey.leak ? (<div className="text-xs text-muted leading-relaxed"><span className="text-danger font-medium">Biggest leak:</span>{' '}<span>- {describePath(journey.leak)} drains{' '}+ {describeJourneyPath(journey.leak)} drains{' '}<span className="font-medium">{journey.leak.count} session{journey.leak.count === 1 ? '' : 's'}</span>{' '}diff --git a/products/mcp_analytics/frontend/clustering/JourneyTooltip.tsx b/products/mcp_analytics/frontend/clustering/JourneyTooltip.tsxnew file mode 100644index 000000000000..3b4509828c0e--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/JourneyTooltip.tsx@@ -0,0 +1,48 @@+import { TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'+import type { SankeyTooltipContext } from '@posthog/quill-charts'++import type { JourneyLinkMeta, JourneyNodeMeta } from './clusterJourneyGraph'++interface JourneyTooltipProps {+ hit: SankeyTooltipContext<JourneyNodeMeta, JourneyLinkMeta>['hit']+ totalSessions: number+}++function formatShare(fraction: number): string {+ return `${Math.round(fraction * 1000) / 10}%`+}++function outcomeLabel(outcome: JourneyLinkMeta['outcome'] | undefined): string | null {+ if (!outcome) {+ return null+ }+ return outcome === 'error' ? 'Error' : 'Completed'+}++export function JourneyTooltip({ hit, totalSessions }: JourneyTooltipProps): JSX.Element {+ const { title, value, color, outcome } =+ hit.kind === 'node'+ ? { title: hit.node.label, value: hit.node.value, color: hit.node.color, outcome: undefined }+ : {+ title: `${hit.link.source.label} → ${hit.link.target.label}`,+ value: hit.link.value,+ color: hit.link.color,+ outcome: hit.link.meta?.outcome,+ }+ const share = totalSessions > 0 ? value / totalSessions : 0+ const outcomeText = outcomeLabel(outcome)++ return (+ <TooltipSurface data-attr="mcp-cluster-journey-sankey-tooltip">+ <div className="flex items-center gap-2 mb-1">+ <TooltipSwatch color={color} />+ <span className="font-semibold">{title}</span>+ </div>+ <div className="flex items-center gap-2">+ <strong>{value.toLocaleString()}</strong>+ {share > 0 ? <span className="opacity-70">({formatShare(share)})</span> : null}+ </div>+ {outcomeText ? <div className="text-xs text-muted mt-1">{outcomeText}</div> : null}+ </TooltipSurface>+ )+}diff --git a/products/mcp_analytics/frontend/clustering/clusterJourneyGraph.test.ts b/products/mcp_analytics/frontend/clustering/clusterJourneyGraph.test.tsnew file mode 100644index 000000000000..cc6ab670954a--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/clusterJourneyGraph.test.ts@@ -0,0 +1,52 @@+import type { MCPIntentClusterJourneyPathApi } from '../generated/api.schemas'+import { buildJourneyGraph, describeJourneyPath } from './clusterJourneyGraph'++const PATHS: MCPIntentClusterJourneyPathApi[] = [+ { steps: ['schema', 'sql', null], outcome: 'completed', count: 20 },+ { steps: ['schema', 'sql', null], outcome: 'error', count: 5 },+ { steps: ['sql', null, null], outcome: 'error', count: 3 },+]++describe('buildJourneyGraph', () => {+ it('keeps one node per stage and one link per outcome between the same nodes', () => {+ const graph = buildJourneyGraph(PATHS)+ // The same tool at two stages is two nodes; Ended repeats per column it fills.+ expect(graph.nodes.map((n) => n.id)).toEqual([+ '0::init::Init',+ '1::tool::schema',+ '2::tool::sql',+ '3::ended::Ended',+ '4::completed::Completed',+ '4::error::Error',+ '1::tool::sql',+ '2::ended::Ended',+ ])+ const schemaToSql = graph.links.filter((l) => l.source === '1::tool::schema' && l.target === '2::tool::sql')+ expect(schemaToSql.map((l) => [l.meta?.outcome, l.value])).toEqual([+ ['completed', 20],+ ['error', 5],+ ])+ const intoError = graph.links.filter((l) => l.target === '4::error::Error')+ expect(intoError.reduce((sum, l) => sum + l.value, 0)).toBe(8)+ })++ it('keeps a tool named Ended separate from a missing step', () => {+ const graph = buildJourneyGraph([+ { steps: ['Ended', null], outcome: 'completed', count: 2 },+ { steps: [null, null], outcome: 'completed', count: 3 },+ ])++ const firstStage = graph.nodes.filter((node) => node.label === 'Ended' && node.id.startsWith('1::'))+ expect(firstStage.map((node) => [node.meta?.kind, node.id])).toEqual([+ ['tool', '1::tool::Ended'],+ ['ended', '1::ended::Ended'],+ ])+ expect(graph.links.filter((link) => link.target === '1::tool::Ended').map((link) => link.value)).toEqual([2])+ expect(graph.links.filter((link) => link.target === '1::ended::Ended').map((link) => link.value)).toEqual([3])+ })++ it('describes a leak path with one Ended for its padding and keeps a tool named Ended', () => {+ expect(describeJourneyPath({ steps: ['sql', null, null], outcome: 'error', count: 1 })).toBe('sql → Ended')+ expect(describeJourneyPath({ steps: ['Ended', null, null], outcome: 'error', count: 1 })).toBe('Ended → Ended')+ })+})diff --git a/products/mcp_analytics/frontend/clustering/clusterJourneyGraph.ts b/products/mcp_analytics/frontend/clustering/clusterJourneyGraph.tsnew file mode 100644index 000000000000..23ca53f50034--- /dev/null+++ b/products/mcp_analytics/frontend/clustering/clusterJourneyGraph.ts@@ -0,0 +1,77 @@+import type { SankeyLinkInput, SankeyNodeInput } from '@posthog/quill-charts'++import type { MCPIntentClusterJourneyPathApi } from '../generated/api.schemas'++export const JOURNEY_COLUMN_LABELS = ['Init', '1st tool', '2nd tool', '3rd tool', '4th tool', 'Outcome']+export const ENDED_LABEL = 'Ended'++export type JourneyNodeKind = 'init' | 'tool' | 'ended' | 'completed' | 'error'+export type JourneyOutcome = 'completed' | 'error'++export interface JourneyNodeMeta {+ kind: JourneyNodeKind+}++export interface JourneyLinkMeta {+ outcome: JourneyOutcome+}++export interface JourneyGraph {+ nodes: SankeyNodeInput<JourneyNodeMeta>[]+ links: SankeyLinkInput<JourneyLinkMeta>[]+}++function outcomeOf(path: MCPIntentClusterJourneyPathApi): JourneyOutcome {+ return path.outcome === 'error' ? 'error' : 'completed'+}++/**+ * Turns the top paths of a cluster into a stage-per-column flow graph. Every path spans the same+ * number of columns: Init, one column per step (a step that never happened is `Ended`), then the+ * outcome. Node ids carry the column and kind so the same tool at two stages is two nodes, and links are+ * split by outcome so error flows keep their own ribbon.+ */+export function buildJourneyGraph(paths: readonly MCPIntentClusterJourneyPathApi[]): JourneyGraph {+ const nodes = new Map<string, SankeyNodeInput<JourneyNodeMeta>>()+ const links = new Map<string, SankeyLinkInput<JourneyLinkMeta>>()++ const nodeId = (column: number, label: string, kind: JourneyNodeKind): string => {+ const id = `${column}::${kind}::${label}`+ if (!nodes.has(id)) {+ nodes.set(id, { id, label, meta: { kind } })+ }+ return id+ }++ for (const path of paths) {+ const outcome = outcomeOf(path)+ const stages: { label: string; kind: JourneyNodeKind }[] = [{ label: 'Init', kind: 'init' }]+ for (const step of path.steps) {+ stages.push(step === null ? { label: ENDED_LABEL, kind: 'ended' } : { label: step, kind: 'tool' })+ }+ stages.push(outcome === 'error' ? { label: 'Error', kind: 'error' } : { label: 'Completed', kind: 'completed' })++ for (let column = 0; column < stages.length - 1; column++) {+ const source = nodeId(column, stages[column].label, stages[column].kind)+ const target = nodeId(column + 1, stages[column + 1].label, stages[column + 1].kind)+ const key = `${source}->${target}::${outcome}`+ const existing = links.get(key)+ if (existing) {+ existing.value += path.count+ } else {+ links.set(key, { source, target, value: path.count, meta: { outcome } })+ }+ }+ }++ return { nodes: Array.from(nodes.values()), links: Array.from(links.values()) }+}++/** The tools a path ran, then one `Ended` for the missing steps that pad it. A tool that happens+ * to be named `Ended` still shows. */+export function describeJourneyPath(path: MCPIntentClusterJourneyPathApi): string {+ const firstMissing = path.steps.findIndex((step) => step == null)+ return path.steps+ .flatMap((step, idx) => (step != null ? [step] : idx === firstMissing ? [ENDED_LABEL] : []))+ .join(' → ')+}diff --git a/products/product_analytics/frontend/insights/paths/renderPaths.ts b/products/product_analytics/frontend/insights/paths/renderPaths.tsindex 5420b1058ac8..073c26f9d22c 100644--- a/products/product_analytics/frontend/insights/paths/renderPaths.ts+++ b/products/product_analytics/frontend/insights/paths/renderPaths.ts@@ -1,11 +1,18 @@import * as d3 from 'd3'import { RefObject } from 'react'+import {+ sankeyJustify,+ sankeyLayout,+ sankeyLinkHorizontal,+ type SankeyLink,+ type SankeyLayout,+} from '@posthog/quill-charts'+import { D3Selector } from 'lib/hooks/useD3'import { stripHTTP } from 'lib/utils/url'import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'-import sankey, { sankeyJustify, sankeyLinkHorizontal, type SankeyLink, type SankeyLayout } from '~/vendor/d3/sankey'// eslint-disable-next-line import/no-cycleimport { FALLBACK_CANVAS_WIDTH } from './Paths'@@ -31,7 +38,7 @@ const createCanvas = (canvasRef: RefObject<HTMLDivElement>, width: number, heigh}const createSankeyGenerator = (width: number, height: number): SankeyLayout<PathNodeData, {}> => {- return sankey<PathNodeData, {}>()+ return sankeyLayout<PathNodeData, {}>().nodeId((d) => d.name).nodeAlign(sankeyJustify).nodeSort(null)