: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): add FunnelChart to quill-charts (#67658)
Sam Penningtonacab6be6cffc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5f20932e40ec..4c67a06b4d06 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -668,6 +668,22 @@ snapshots:hash: v1.k794b7964.fb81cb2f84f1c695d9bf3410b3e007dfb0c8835c7d5559782549eb512d4de370.NyKEsje9NjASsmSair_05neuK4jjxTnDau697twbsEUcomponents-hogcharts-defaulttooltip--total-excludes-overlay--light:hash: v1.k794b7964.0ef742f50f4f5cebd2c50b24b514c90a101012d53f3cb61e3b461f5ff0864d9c.h-i6FX0wnz_8r7gxr3pus1F2U1i-hcsuXZQ8drcM35E+ components-hogcharts-funnelchart--few-steps-clustered--dark:+ hash: v1.k794b7964.6170144d425938e59b03d0c3eec88b144de8588d4c6fce87e7acfd901d5d7ca9.1UE57suDraSRRMxP3WWADNvzS71pv4FWv3l_5uW52kY+ components-hogcharts-funnelchart--few-steps-clustered--light:+ hash: v1.k794b7964.5e7de7c0da3e9e5f2c9b94b6b64171b787e98156eda776fdec5b8dbfd50f01da.hrBFs_eOlhKYWdGFKwmlfrQ0sEpeBwEJSE-lZSphibc+ components-hogcharts-funnelchart--multiple-variants--dark:+ hash: v1.k794b7964.c181c8c6bc7ea5781c2274be6f99acb63d7112e2ab71dce8d8712041c1813ae8.YCPgDDYLEmPkXRm6JHywEYgYS_mNnPOoejLBOAibA0Q+ components-hogcharts-funnelchart--multiple-variants--light:+ hash: v1.k794b7964.10ce6fa42dc4e8412a821731188e71e69e9df1f806d755b42a903f0f259ad4f7.Hp47gZD9hiS28slLtzl6C_lG9yF9yA8rv9lQb_uy8W8+ components-hogcharts-funnelchart--single-series--dark:+ hash: v1.k794b7964.8136c5bfb7c2a18371844cd7a45b137dc3d370710e509b3d897713128b7af070.0JJam2Iw0KYdEDPvO6qoxBF0APaBz1YAclikQTF6Li4+ components-hogcharts-funnelchart--single-series--light:+ hash: v1.k794b7964.4e42a2b211d9f45405ea8d54c8d6d88c9b1baa7d42fa8d311ca9af29c1e093e8.YuR6d8ueW0hVPHY2giOTPQQHzVsadrsVILGTImSUX_Y+ components-hogcharts-funnelchart--with-step-footer--dark:+ hash: v1.k794b7964.c14c5f1138464e78ff0eb8423db2caab871c81e6a523734c154b63b5a3c05bd6.qbFArRbm4iHI18T08hWXVMZC69S5dkQ5cQ5VoCSgVmw+ components-hogcharts-funnelchart--with-step-footer--light:+ hash: v1.k794b7964.03968d655b2ee1d4993ab6c3c19755623f8e37118c5a165bf2e48e6f4452e971.eKZ1yGNS6PiIf_9dy5m3yFNFf4pWA95vzKdma9W0J5gcomponents-hogcharts-highlightedrange--mirroring-drag-selection--dark:hash: v1.k794b7964.64a7d4555eda0a387b3b7b159397ed36aec00739db9ca101281ace1d84ea742e.t3Qju4H0HxPL1ROhKqavpuowJ_DeePAa0O0r5eIHeBscomponents-hogcharts-highlightedrange--mirroring-drag-selection--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex e5d208373c63..d89b9af8f24d 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -8,6 +8,7 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) || BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars; end-cap rounding via top-level `barCornerRadius` (the same key across the time-series/combo configs) |+| FunnelChart | Funnel steps as grouped vertical bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent-of-first-step (0–100) || ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped' \| 'percent'` (percent stacks bar series to 100%; a line/area series needs its own `yAxisId: 'right'` axis — one sharing the bars' axis can't plot raw values against their [0,1] scale) || TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis || TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes |@@ -79,6 +80,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, renderItem }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. `config.legend.renderItem(defaultNode, item)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change). Long labels clip with an ellipsis only when they run out of the space actually available — there is no fixed max width. A vertical legend bounds each row to its column and truncates at the column edge; a horizontal legend caps each row at an equal share of the line floored at 180px (flexbox wraps before it shrinks, so without a cap one long label would take a whole line instead of clipping) — many series pack into tidy 180px columns while a few series with room to spare, or a lone series, show unclipped whenever they fit. The full text is always exposed via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at 45% width but never more than 240px), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.+- `FunnelChart` is a thin wrapper over grouped `BarChart` that owns the funnel look (hatched `track`, rounded + shadowed bars, percent value axis). `steps` is a `string[]` of display labels — duplicates are fine, bands are keyed by step index internally. Each `Series.data[stepIndex]` is the conversion from the first step as a percent (0–100); `funnelFromCounts` builds the single-series case from raw `{ label, count }` steps (zero basis yields 0, not NaN). `onStepClick` replaces `onPointClick` and reports `{ stepIndex, converted }` — `converted: false` means the hatched drop-off track above the bar was clicked. `stepFooter(stepIndex)` renders per-step content in a row below the plot, pixel-aligned under each step's bars (and hides the built-in step labels); use it for step legends richer than an axis label. Config: `hideStepLabels`, `hideValueAxis`, `barCornerRadius`, `bandPadding`, `maxBandRange` (cluster a 2–3 step funnel instead of stretching it), plus the usual `tooltip`/`legend`/`margins`.- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped' | 'percent'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.stories.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.stories.tsxnew file mode 100644index 000000000000..7d806bdad54b--- /dev/null+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.stories.tsx@@ -0,0 +1,97 @@+import { Meta, StoryObj } from '@storybook/react'++import type { Series } from '../../core/types'+import { Stage, useReactiveTheme } from '../../story-helpers'+import { funnelFromCounts } from './funnel-data'+import { FunnelChart } from './FunnelChart'++const STEPS = ['Visited signup', 'Created account', 'Started trial', 'Invited teammate']++const SINGLE = funnelFromCounts([+ { label: STEPS[0], count: 12840 },+ { label: STEPS[1], count: 7921 },+ { label: STEPS[2], count: 4102 },+ { label: STEPS[3], count: 1289 },+])++// Multi-variant comparison: every variant starts at 100% (the first step is the basis).+const VARIANT_STEPS = ['Viewed pricing', 'Started checkout']+const VARIANT_SERIES: Series[] = [+ { key: 'control', label: 'control', data: [100, 22.4] },+ { key: 'test', label: 'test', data: [100, 27.9] },+]++const meta: Meta = { title: 'Components/HogCharts/FunnelChart', parameters: { layout: 'centered' } }+export default meta++type Story = StoryObj<{}>++export const SingleSeries: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={640}>+ <FunnelChart steps={SINGLE.steps} series={SINGLE.series} theme={theme} />+ </Stage>+ )+ },+}++export const MultipleVariants: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={520}>+ <FunnelChart+ steps={VARIANT_STEPS}+ series={VARIANT_SERIES}+ theme={theme}+ onStepClick={({ stepIndex, series, converted }) =>+ alert(`${converted ? 'Converted' : 'Dropped off'} · step ${stepIndex + 1} · ${series.label}`)+ }+ />+ </Stage>+ )+ },+}++export const WithStepFooter: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const counts = [12840, 7921, 4102, 1289]+ return (+ <Stage width={720} height={340}>+ <FunnelChart+ steps={SINGLE.steps}+ series={SINGLE.series}+ theme={theme}+ stepFooter={(stepIndex) => (+ <div className="text-xs leading-tight">+ <div className="font-semibold truncate" title={SINGLE.steps[stepIndex]}>+ {stepIndex + 1}. {SINGLE.steps[stepIndex]}+ </div>+ <div>{counts[stepIndex].toLocaleString()} users</div>+ <div>{SINGLE.series[0].data[stepIndex].toFixed(1)}% of total</div>+ </div>+ )}+ />+ </Stage>+ )+ },+}++export const FewStepsClustered: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={640}>+ <FunnelChart+ steps={VARIANT_STEPS}+ series={VARIANT_SERIES}+ theme={theme}+ config={{ maxBandRange: 320, legend: { show: true, interactive: false } }}+ />+ </Stage>+ )+ },+}diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsxnew file mode 100644index 000000000000..1c8ad8d67de6--- /dev/null+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx@@ -0,0 +1,124 @@+import { fireEvent, waitFor } from '@testing-library/react'++import type { ChartTheme, Series } from '../../core/types'+import { createDefaultTooltipAccessor, renderHogChart } from '../../testing'+import { dimensions } from '../../testing/jsdom'+import { funnelFromCounts } from './funnel-data'+import { FunnelChart, type FunnelStepClickData } from './FunnelChart'++const THEME: ChartTheme = {+ colors: ['#1f77b4', '#ff7f0e'],+ backgroundColor: '#ffffff',+ gridColor: '#eeeeee',+ crosshairColor: '#888888',+}++const STEPS = ['Exposure', 'Purchase']+const SERIES: Series[] = [+ { key: 'control', label: 'control', data: [100, 22] },+ { key: 'test', label: 'test', data: [100, 28] },+]++describe('FunnelChart', () => {+ it('keeps steps with the same display name on separate bands', () => {+ // Bands are keyed by step index; keying by name would collapse both `Pageview`+ // steps into one d3 band slot and the funnel would lose a step.+ const { chart } = renderHogChart(+ <FunnelChart+ steps={['Pageview', 'Pageview']}+ series={[{ key: 'all', label: 'All', data: [100, 40] }]}+ theme={THEME}+ />+ )+ expect(chart.xTicks()).toEqual(['Pageview', 'Pageview'])+ })++ it('formats the value axis as percentages by default', () => {+ const { chart } = renderHogChart(<FunnelChart steps={STEPS} series={SERIES} theme={THEME} />)+ const ticks = chart.yTicks()+ expect(ticks.length).toBeGreaterThan(0)+ expect(ticks.every((tick) => tick.endsWith('%'))).toBe(true)+ })++ it('tooltip header shows the step name and value is formatted as X.XX%', async () => {+ // nativeTooltip preserves config-level formatters (valueFormatter / labelFormatter);+ // the default renderHogChart path intercepts the tooltip prop and bypasses them.+ const { chart } = renderHogChart(<FunnelChart steps={STEPS} series={SERIES} theme={THEME} />, {+ nativeTooltip: true,+ })+ const step = dimensions.plotWidth / STEPS.length+ // Hover at step-index 1 band center — same x as the onStepClick test, lands in control's sub-band.+ const hoverX = dimensions.plotLeft + step * 1.3+ const hoverY = dimensions.plotTop + dimensions.plotHeight / 2+ await waitFor(() => {+ fireEvent.mouseMove(chart.element, { clientX: hoverX, clientY: hoverY })+ const tooltipEl = document.querySelector('[data-hog-charts-tooltip]') as HTMLElement | null+ expect(tooltipEl?.querySelector('[data-attr="hog-chart-tooltip-label"]')?.textContent?.trim()).toBeTruthy()+ })+ const tooltipEl = document.querySelector('[data-hog-charts-tooltip]') as HTMLElement+ const tooltip = createDefaultTooltipAccessor(tooltipEl)+ // labelFormatter maps band index "2" → steps[1] = "Purchase"+ expect(tooltip.label()).toBe('Purchase')+ // formatPercent: 22 → "22%" (parseFloat(22.toFixed(2)) = 22)+ expect(tooltip.value('control')).toBe('22%')+ })++ it.each([+ // Cursor near the plot top at step 2 is in the hatched track above the short bar.+ { area: 'drop-off track', clientYOffset: 2, converted: false },+ // Cursor near the baseline is inside the bar fill.+ { area: 'bar fill', clientYOffset: dimensions.plotHeight - 2, converted: true },+ ])('onStepClick maps a click on the $area to converted=$converted', ({ clientYOffset, converted }) => {+ const onStepClick = jest.fn()+ const { chart } = renderHogChart(+ <FunnelChart steps={STEPS} series={SERIES} theme={THEME} onStepClick={onStepClick} />+ )+ const step = dimensions.plotWidth / STEPS.length+ fireEvent.mouseMove(chart.element, {+ clientX: dimensions.plotLeft + step * 1.3,+ clientY: dimensions.plotTop + clientYOffset,+ })+ fireEvent.click(chart.element)+ const click: FunnelStepClickData = onStepClick.mock.calls[0][0]+ expect(click.stepIndex).toBe(1)+ expect(click.converted).toBe(converted)+ })++ it('renders one step-footer cell per step and hides the axis step labels', async () => {+ const { chart } = renderHogChart(+ <FunnelChart+ steps={STEPS}+ series={SERIES}+ theme={THEME}+ stepFooter={(stepIndex) => <span>{STEPS[stepIndex]}</span>}+ />+ )+ // Footer cells mount once the chart commits its measured band geometry.+ await waitFor(() => {+ const cells = document.querySelectorAll('[data-attr="hog-funnel-step-footer-cell"]')+ expect(cells).toHaveLength(STEPS.length)+ })+ expect(chart.xTicks()).toHaveLength(0)+ })++ it.each<[string, { label: string; count: number }[], number[]]>([+ [+ 'zero basis collapses to 0 instead of NaN',+ [+ { label: 'a', count: 0 },+ { label: 'b', count: 5 },+ ],+ [0, 0],+ ],+ [+ 'counts convert to percent of the first step',+ [+ { label: 'a', count: 200 },+ { label: 'b', count: 50 },+ ],+ [100, 25],+ ],+ ])('funnelFromCounts: %s', (_name, counts, expected) => {+ expect(funnelFromCounts(counts).series[0].data).toEqual(expected)+ })+})diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsxnew file mode 100644index 000000000000..b807748f1f69--- /dev/null+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx@@ -0,0 +1,261 @@+import React, { useCallback, useEffect, useMemo, useState } from 'react'++import { useChartLayout } from '../../core/chart-context'+import type {+ BarChartConfig,+ BarsConfig,+ ChartLegendConfig,+ ChartMargins,+ ChartTheme,+ PointClickData,+ Series,+ TooltipConfig,+ TooltipContext,+} from '../../core/types'+import { BarChart } from '../BarChart/BarChart'++/** Inner gap between variant bars as a fraction of a step's band slot. */+export const FUNNEL_BAND_PADDING = 0.1++const FUNNEL_BAR_SHADOW: BarsConfig['shadow'] = { color: 'rgba(0,0,0,0.15)', blur: 6, offsetY: -2 }+const DEFAULT_CORNER_RADIUS = 10++export interface FunnelChartConfig {+ /** Tooltip behaviour + built-in content formatting. Defaults to `top` placement with a+ * percent value formatter and step names in the header. */+ tooltip?: TooltipConfig+ /** Built-in legend with click-to-toggle series visibility. Hidden by default. */+ legend?: ChartLegendConfig+ animateHover?: boolean | number+ margins?: Partial<ChartMargins>+ /** Show horizontal grid lines at value-axis ticks. Defaults to true. */+ showGrid?: boolean+ /** Corner radius of the bar tops. Defaults to 10. */+ barCornerRadius?: number+ /** Hide the built-in step-name labels under the plot. Implied when `stepFooter` is set —+ * the footer row replaces the axis labels. */+ hideStepLabels?: boolean+ /** Hide the percent value axis. */+ hideValueAxis?: boolean+ /** Truncate long step-name labels to this px width (ellipsis + hover reveal). */+ maxCategoryLabelWidth?: number+ /** Inner gap between variant bars as a fraction of the band slot. Defaults to {@link FUNNEL_BAND_PADDING}. */+ bandPadding?: number+ /** Cap (px) on the band-axis range — clusters steps at the start of the plot instead of+ * stretching a 2–3 step funnel across the full width. */+ maxBandRange?: number+}++export interface FunnelStepClickData<Meta = unknown> extends PointClickData<Meta> {+ /** Index into `steps` of the clicked band. Same value as `dataIndex`, named for funnel call sites. */+ stepIndex: number+ /** True when the filled (converted) portion of a bar was clicked; false for the hatched+ * drop-off track above it. */+ converted: boolean+}++/** Pixel box of one step's bars, relative to the chart wrapper. */+interface StepBand {+ left: number+ width: number+}++export interface FunnelChartProps<Meta = unknown> {+ /** Step display labels, in order. Duplicates are fine — bands are keyed by step index+ * internally, so two steps sharing an event name keep separate slots. */+ steps: string[]+ /** One series per variant (a single series without a breakdown); `data[stepIndex]` is the+ * conversion from the first step as a percent (0–100). The hatched track drawn behind each+ * bar covers the remainder up to 100%. See `funnelFromCounts` for the raw-counts case. */+ series: Series<Meta>[]+ theme: ChartTheme+ config?: FunnelChartConfig+ /** Custom tooltip content. Omit for the built-in tooltip with percent formatting. */+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode+ /** Click on a bar (converted) or its drop-off track. Replaces `onPointClick`. */+ onStepClick?: (data: FunnelStepClickData<Meta>) => void+ /** Per-step content rendered in a row below the plot, horizontally aligned under each+ * step's bars — for step legends richer than an axis label. Hides the built-in step labels. */+ stepFooter?: (stepIndex: number) => React.ReactNode+ dataAttr?: string+ className?: string+ children?: React.ReactNode+ onError?: (error: Error, info: React.ErrorInfo) => void+}++function formatPercent(value: number): string {+ return `${parseFloat(value.toFixed(2))}%`+}++/** Reports each band's pixel box up to the wrapper so the step-footer row can align its cells+ * under the bars without duplicating the chart's band math. Renders nothing. */+function StepBandProbe({ onBands }: { onBands: (bands: StepBand[]) => void }): null {+ const { scales, labels } = useChartLayout()+ const bands = useMemo(+ () =>+ labels.map((label): StepBand => {+ const center = scales.x(label) ?? 0+ const width = scales.extent?.(label) ?? 0+ return { left: center - width / 2, width }+ }),+ [scales, labels]+ )+ useEffect(() => onBands(bands), [bands, onBands])+ return null+}++function StepFooterRow({+ bands,+ stepFooter,+}: {+ bands: StepBand[]+ stepFooter: (stepIndex: number) => React.ReactNode+}): React.ReactElement {+ // One gutter column before each band column, so cells sit in normal flow (the row grows to+ // the tallest cell) while staying pixel-aligned with the bars above.+ const columns: string[] = []+ let cursor = 0+ for (const band of bands) {+ columns.push(`${Math.max(0, band.left - cursor)}px`, `${band.width}px`)+ cursor = band.left + band.width+ }+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div+ className="grid shrink-0"+ style={{ gridTemplateColumns: columns.join(' ') }}+ data-attr="hog-funnel-step-footer"+ >+ {bands.map((_, stepIndex) => (+ // eslint-disable-next-line react/forbid-dom-props+ <div+ key={stepIndex}+ className="min-w-0"+ style={{ gridColumn: 2 * stepIndex + 2, gridRow: 1 }}+ data-attr="hog-funnel-step-footer-cell"+ >+ {stepFooter(stepIndex)}+ </div>+ ))}+ </div>+ )+}++/** Funnel steps as grouped vertical bars — each step a band, each variant a bar valued by its+ * conversion from the first step, with a hatched track behind it covering the drop-off remainder.+ * A thin wrapper over {@link BarChart}; overlays compose as children the same way. */+export function FunnelChart<Meta = unknown>({+ steps,+ series,+ theme,+ config,+ tooltip,+ onStepClick,+ stepFooter,+ dataAttr,+ className,+ children,+ onError,+}: FunnelChartProps<Meta>): React.ReactElement {+ const {+ tooltip: tooltipConfig,+ legend,+ animateHover,+ margins,+ showGrid = true,+ barCornerRadius = DEFAULT_CORNER_RADIUS,+ hideStepLabels,+ hideValueAxis,+ maxCategoryLabelWidth,+ bandPadding,+ maxBandRange,+ } = config ?? {}+ const hasStepFooter = stepFooter != null++ // Band labels are 1-based step indices so steps sharing a name don't collapse onto one+ // d3 band slot; formatters map them back to the display label.+ const bandLabels = useMemo(() => steps.map((_, stepIndex) => `${stepIndex + 1}`), [steps])+ const stepLabelFromBand = useCallback((band: string): string => steps[Number(band) - 1] ?? band, [steps])++ const barConfig = useMemo<BarChartConfig>(+ () => ({+ barLayout: 'grouped',+ showGrid,+ animateHover,+ margins,+ hideXAxis: hideStepLabels || hasStepFooter,+ hideYAxis: hideValueAxis,+ maxCategoryLabelWidth,+ xTickFormatter: stepLabelFromBand,+ yTickFormatter: (value) => `${Math.round(value)}%`,+ barCornerRadius,+ legend,+ tooltip: {+ placement: 'top',+ valueFormatter: formatPercent,+ labelFormatter: stepLabelFromBand,+ ...tooltipConfig,+ },+ bars: {+ track: true,+ shadow: FUNNEL_BAR_SHADOW,+ bandPadding: bandPadding ?? FUNNEL_BAND_PADDING,+ maxBandRange,+ },+ }),+ [+ showGrid,+ animateHover,+ margins,+ hideStepLabels,+ hasStepFooter,+ hideValueAxis,+ maxCategoryLabelWidth,+ stepLabelFromBand,+ legend,+ tooltipConfig,+ barCornerRadius,+ bandPadding,+ maxBandRange,+ ]+ )++ const handlePointClick = useMemo(+ () =>+ onStepClick+ ? (data: PointClickData<Meta>): void =>+ onStepClick({ ...data, stepIndex: data.dataIndex, converted: !data.inTrackArea })+ : undefined,+ [onStepClick]+ )++ const [bands, setBands] = useState<StepBand[] | null>(null)++ const chart = (+ <BarChart<Meta>+ series={series}+ labels={bandLabels}+ theme={theme}+ config={barConfig}+ tooltip={tooltip}+ onPointClick={handlePointClick}+ className={className}+ dataAttr={dataAttr}+ onError={onError}+ >+ {hasStepFooter && <StepBandProbe onBands={setBands} />}+ {children}+ </BarChart>+ )++ if (!stepFooter) {+ return chart+ }++ return (+ <div className="flex flex-col flex-1 min-h-0">+ <div className="flex-1 min-h-0">{chart}</div>+ {bands && bands.length > 0 && <StepFooterRow bands={bands} stepFooter={stepFooter} />}+ </div>+ )+}diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/funnel-data.ts b/packages/quill/packages/charts/src/charts/FunnelChart/funnel-data.tsnew file mode 100644index 000000000000..c182ef8eb327--- /dev/null+++ b/packages/quill/packages/charts/src/charts/FunnelChart/funnel-data.ts@@ -0,0 +1,42 @@+import type { Series } from '../../core/types'++export const RATE_TO_PERCENT = 100++/** Conversion of a step's count against a basis count, as a 0..1 rate. A zero or absent basis+ * yields 0 (rather than dividing by zero) so the bar collapses instead of rendering NaN. */+export function funnelConversionRate(count: number, basisCount: number): number {+ return basisCount > 0 ? count / basisCount : 0+}++export interface FunnelStepCount {+ label: string+ count: number+}++export interface FunnelFromCountsOptions {+ key?: string+ label?: string+ color?: string+}++/** Builds the `steps` + single-`series` pair for a no-breakdown funnel from raw step counts,+ * with each step valued as its conversion from the first step (percent, 0–100). Multi-variant+ * funnels resolve their own per-variant percentages and pass+ * `Series[]` directly. */+export function funnelFromCounts(+ steps: FunnelStepCount[],+ options: FunnelFromCountsOptions = {}+): { steps: string[]; series: Series[] } {+ const firstCount = steps[0]?.count ?? 0+ return {+ steps: steps.map((step) => step.label),+ series: [+ {+ key: options.key ?? 'funnel-conversion',+ label: options.label ?? 'Conversion',+ color: options.color,+ data: steps.map((step) => funnelConversionRate(step.count, firstCount) * RATE_TO_PERCENT),+ },+ ],+ }+}diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex 8b6dbbd5aa9c..b4294c8160a4 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -1,6 +1,10 @@// Componentsexport { BarChart } from './charts/BarChart/BarChart'export type { BarChartProps } from './charts/BarChart/BarChart'+export { FunnelChart, FUNNEL_BAND_PADDING } from './charts/FunnelChart/FunnelChart'+export type { FunnelChartConfig, FunnelChartProps, FunnelStepClickData } from './charts/FunnelChart/FunnelChart'+export { funnelConversionRate, funnelFromCounts, RATE_TO_PERCENT } from './charts/FunnelChart/funnel-data'+export type { FunnelFromCountsOptions, FunnelStepCount } from './charts/FunnelChart/funnel-data'export { LineChart } from './charts/LineChart/LineChart'export type { LineChartProps } from './charts/LineChart/LineChart'export { ComboChart } from './charts/ComboChart/ComboChart'