: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): list only the nearest series in the tooltip (#125544)
Ben White5dc6bd68adb7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5e73bb27b73c..70e8a59cd1af 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1160,10 +1160,14 @@ snapshots:hash: v1.k794b7964.0f7ca12d746131e726f6881382a7d391a7214a88e39d8e135087449bb0b4ed69.ZEImHZD3E7-mSQxPwxjG1O_4UWkDTqblU_3lQvy-E5Ecomponents-hogcharts-defaulttooltip--per-series-formatter-with-total--light:hash: v1.k794b7964.2e9fecca7aa1311448b8afd3567711cb15fc33248dacc6289fbcc72cf1989c46.FfrOaN6SSHXMj7QCPCbkxNQmNnAf_183hbcdD9EE9RA+ components-hogcharts-defaulttooltip--single-series-mode--dark:+ hash: v1.k794b7964.a5e070d178ecf524a3deb9c2c4e3152fdb606ebe1664700b6fa0833893636a37.iH_9iTrRUowrkCdZpnnRVmEhriDNId1Mp9lxQ_dIRy4+ components-hogcharts-defaulttooltip--single-series-mode--light:+ hash: v1.k794b7964.4ac04589238aeb129c6e5d2aad800486c4d8b93b281f57fa7c2e1b229291293e.G2QIXhB7KIxLFlrQgbQtm635POAPyAaqF1OxGHM4rJMcomponents-hogcharts-defaulttooltip--total-excludes-overlay--dark:- hash: v1.k794b7964.78dba2ce9675adb353e1e02d08852fae239ee216226147366a463c8f5b3674ea.knCuOE2QwspGcEHABBanNA1tvAqrm2uXVM1yPD5A1G0+ hash: v1.k794b7964.067ff310ca166b654eea4576ed04dbe33ba6717e267bd2adefb652b743c17796.Dtffg1E4NJewWCpUJjawx-SbmlqinegRoLp_q980pnwcomponents-hogcharts-defaulttooltip--total-excludes-overlay--light:- hash: v1.k794b7964.e021d56bfc9c1aabc8d7bc66574af9014cd609a8eff91c6229e90e9269d7bf30.CwqmkYC7eS-QlnU3JQ6TQu3y9Ce4xeQKj5ybiJTl3is+ hash: v1.k794b7964.4b857c2cbf30a4f4b5cdb85ccfe0e9e244201ca9c43c612c15dc1ec0243bd6b6.asECa3fYimu_F85yECEVIO57qvrRVe2jXvyj90sBB2scomponents-hogcharts-funnelchart--few-steps-clustered--dark:hash: v1.k794b7964.482c407ebd0ccaf1aae8aff3034c90582e9bb549bb55c3e991f48cc3162f2d60.hjzAcq7YylD5DwBQkLr4PP1T0h_pMgduQYTOSQTxjwgcomponents-hogcharts-funnelchart--few-steps-clustered--light:diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsxindex bf5b7129bc6b..1e33b236d87e 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx@@ -4,6 +4,7 @@ import { useChartLayout } from '../../core/chart-context'import type { ChartTheme, Series, TimeScale } from '../../core/types'import { ReferenceLine } from '../../overlays/ReferenceLine'import { dimensions as testDimensions, getChart, rawDrag, renderChart } from '../../testing'+import { createDefaultTooltipAccessor } from '../../testing/tooltip'import { LineChart } from './LineChart'function legendButtons(container: HTMLElement): HTMLButtonElement[] {@@ -335,6 +336,18 @@ describe('LineChart', () => {expect(tooltip.isPinned).toBe(true)})+ it.each([+ ['all', 2],+ ['single', 1],+ ] as const)('lists %s rows with config.tooltip.mode', async (mode, rowCount) => {+ const { chart } = renderChart(+ <LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { mode } }} />+ )+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ expect(createDefaultTooltipAccessor(tooltip.element).rows()).toHaveLength(rowCount)+ })+it('does not crash on hover for overlay series', async () => {const series: Series[] = [{ key: 'a', label: 'A', data: [10, 20, 30] },diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 9ef90bdc6c62..317fc3bf4be1 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -408,8 +408,10 @@ export interface TooltipConfig extends Pick<DefaultTooltipProps, 'labelRenderer'showTotal?: booleantotalLabel?: stringtotalFormatter?: (value: number) => string- /** Sort series rows by value descending so the highest value appears at the top. */- sortedByValue?: boolean+ /** Sort series rows by value: `true` or `'desc'` highest first, `'asc'` lowest first. */+ sortedByValue?: boolean | 'asc' | 'desc'+ /** `single` lists only the series closest to the cursor. Defaults to `all`. */+ mode?: 'all' | 'single'/** Bar charts only. `bar` (the default) tooltips only inside a painted bar. `band` tooltips* anywhere in the hovered band, so a one-pixel bar or a zero bucket still reports its value. */hitArea?: 'bar' | 'band'diff --git a/packages/quill/packages/charts/src/docs/tooltips.md b/packages/quill/packages/charts/src/docs/tooltips.mdindex 112809fab791..d88c66b3265d 100644--- a/packages/quill/packages/charts/src/docs/tooltips.md+++ b/packages/quill/packages/charts/src/docs/tooltips.md@@ -6,11 +6,12 @@ Other charts, such as scatter and pie, provide specialized tooltips; check their## Behavior: `config.tooltip`-`TooltipConfig` (see the JSDoc in `core/types.ts`) sets `enabled`, `pinnable`, `placement`, `resolveClickToNearestSeries`, and `hitArea`.+`TooltipConfig` (see the JSDoc in `core/types.ts`) sets `enabled`, `pinnable`, `placement`, `resolveClickToNearestSeries`, `hitArea`, and `mode`.- `placement: 'cursor'` is the library default through `DEFAULT_CHART_CONFIG`; `follow-data` tracks the highest point at the hovered x and `top` pins the panel to the top edge.- `pinnable` lets a click pin the panel. An unpinned tooltip is `pointer-events: none`, so row clicks only land once it is pinned.- `resolveClickToNearestSeries` (default false) makes a click on a pinnable multi-series chart resolve the series nearest the cursor and fire `onPointClick` directly instead of pinning first. Use it only where the target series is visually unambiguous by position (funnel breakdown areas, one per breakdown value). Leave it off where series overlap and a wrong guess is costly (trend lines).+- `mode: 'single'` lists only the series under the cursor. See [`DefaultTooltip` props](#defaulttooltip-props).- `hitArea` applies to bar charts. `bar` (default) needs the cursor over the painted bar, so the empty space above a short bar shows nothing. `band` accepts anywhere in the hovered band. `Sparkline` uses `band` because a sparkline bar can be one pixel tall and a zero bucket has no bar to aim at.## Formatting without a render prop@@ -28,7 +29,8 @@ Usable from a custom `tooltip` render prop by spreading the context: `<DefaultTo- `labelRenderer(entry)` overrides how each row's label renders (default: the series label). Use it for richer labels such as breakdown-value pills. Rows share one grid (swatch, label, value), so a renderer that pushes part of its label right lines up as a column down the tooltip.- `showHeader` (default true) toggles the header row. Pass false where there is no meaningful header (pie slices, aggregated single-column bars).- `showTotal` appends a row summing the visible series. It excludes `overlay` series (goal lines) and series with `visibility.total: false` (a percentage column beside counts; the row itself still renders), and is suppressed when fewer than two summable series remain. `totalFormatter` defaults to `valueFormatter` applied with the first summable row's entry; `totalLabel` defaults to `'Total'`.-- `sortedByValue` sorts rows by value descending.+- `sortedByValue` sorts rows by value: `true` or `'desc'` puts the highest first, `'asc'` the lowest.+- `mode: 'single'` lists only the series closest to the cursor: the nearest line, or the hovered segment of a stacked bar. Overlay series such as trend lines are skipped, as the hover dot skips them. A pinned tooltip lists every row. So does a tooltip with no series under the cursor, or whose series under the cursor is hidden from the tooltip.- `hideZeroRows` drops rows whose value is exactly `0` (lifecycle statuses absent for a period).- `onRowClick(entry)` makes each row clickable. The tooltip must be pinned for clicks to land. Use it for a per-series drill-down (the persons modal).- `footer` renders arbitrary content below all rows, after a divider. Useful for "click to inspect" hints.diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsxindex 9a7ac1dfc61c..a01fb819dad2 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsx@@ -109,3 +109,31 @@ export const TotalExcludesOverlay: Story = {await playHoverAtFraction(canvasElement, 0.5)},}++/** `config.tooltip.mode: 'single'` lists only the series nearest the cursor, here the middle line.+ * `sortedByValue: 'asc'` would order a full list lowest first. */+export const SingleSeriesMode: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'p50', label: 'p50', color: '', data: [120, 140, 130, 160, 150, 170, 155] },+ { key: 'p90', label: 'p90', color: '', data: [220, 260, 240, 300, 280, 320, 290] },+ { key: 'p99', label: 'p99', color: '', data: [400, 460, 430, 520, 480, 560, 510] },+ ]+ return (+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>+ <Stage>+ <LineChart+ series={series}+ labels={DAYS}+ config={{ ...CONFIG, tooltip: { mode: 'single' } }}+ theme={theme}+ />+ </Stage>+ </div>+ )+ },+ play: async ({ canvasElement }) => {+ await playHoverAtFraction(canvasElement, 0.5, 0.55)+ },+}diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsxindex cc3c03a31a08..e1cb746868f5 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx@@ -262,6 +262,38 @@ describe('DefaultTooltip', () => {expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['High', 'Low'])})+ // Alpha (10) sits below Beta (25), as on a real chart, so value order and pixel order disagree.+ it.each<[string, TooltipProps, Partial<TooltipContext>, string[]]>([+ ['sortedByValue: true puts the highest value first', { sortedByValue: true }, {}, ['Beta', 'Alpha']],+ ["sortedByValue: 'asc' puts the lowest value first", { sortedByValue: 'asc' }, {}, ['Alpha', 'Beta']],+ [+ "mode: 'single' lists only the row closest to the cursor",+ { mode: 'single' },+ { hoverPosition: { x: 0, y: 290 } },+ ['Alpha'],+ ],+ [+ "mode: 'single' lists the hovered stacked segment over the closest row",+ { mode: 'single' },+ { hoverPosition: { x: 0, y: 40 }, hoveredSeriesKey: 'a' },+ ['Alpha'],+ ],+ ["mode: 'single' lists every row without a cursor", { mode: 'single' }, {}, ['Beta', 'Alpha']],+ [+ "mode: 'single' lists every row when pinned",+ { mode: 'single' },+ { hoverPosition: { x: 0, y: 290 }, isPinned: true },+ ['Beta', 'Alpha'],+ ],+ ])('%s', (_, props, ctxOverrides, expectedRows) => {+ const withYPixel: TooltipContext['seriesData'] = [+ { ...TWO_SERIES[0], yPixel: 300 },+ { ...TWO_SERIES[1], yPixel: 40 },+ ]+ renderTooltip(props, withYPixel, ctxOverrides)+ expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(expectedRows)+ })+it('marks the row whose yPixel is closest to the cursor with data-closest', () => {const withYPixel: TooltipContext['seriesData'] = [{ series: { key: 'a', label: 'Alpha', data: [] }, value: 5, color: '#000', yPixel: 40 },diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsxindex 7fc010afb6d8..6f1385318816 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx@@ -36,8 +36,13 @@ export interface DefaultTooltipProps<Meta = unknown> extends TooltipContext<Meta/** Formats the total value. Defaults to the `valueFormatter` (applied with the first summable* row's entry) or `toLocaleString`. */totalFormatter?: (value: number) => React.ReactNode- /** Sort series rows by value descending so the highest value appears at the top. */- sortedByValue?: boolean+ /** Sort series rows by value. `true` or `'desc'` puts the highest value at the top, `'asc'` the+ * lowest. Unsorted rows follow the series' vertical order on the plot. */+ sortedByValue?: boolean | 'asc' | 'desc'+ /** `single` lists only the series closest to the cursor (the hovered segment on a stacked bar).+ * It lists every row when the tooltip is pinned or no series is under the cursor. Defaults to+ * `all`. */+ mode?: 'all' | 'single'/** Hide rows whose value is exactly 0 — useful when a zero means the series is absent rather than measured. */hideZeroRows?: boolean/** Make each series row clickable, firing with the row's `seriesData` entry. The tooltip must@@ -53,6 +58,7 @@ export function DefaultTooltip<Meta = unknown>({seriesData,hoverPosition,hoveredSeriesKey,+ isPinned,valueFormatter,labelFormatter,labelRenderer,@@ -61,21 +67,29 @@ export function DefaultTooltip<Meta = unknown>({totalLabel = 'Total',totalFormatter,sortedByValue,+ mode = 'all',hideZeroRows,onRowClick,footer,}: DefaultTooltipProps<Meta>): React.ReactElement {const format = valueFormatter ?? ((value: number): React.ReactNode => value.toLocaleString())const visible = hideZeroRows ? seriesData.filter((s) => s.value !== 0) : seriesData- const rows = sortedByValue- ? [...visible].sort((a, b) => b.value - a.value)- : visible[0]?.yPixel != null- ? [...visible].sort((a, b) => (a.yPixel ?? Infinity) - (b.yPixel ?? Infinity))- : visible- const summable = rows.filter((s) => !s.series.overlay && s.series.visibility?.total !== false)const closestKey =hoveredSeriesKey ??- (hoverPosition != null && rows.length > 1 ? findClosestSeriesKey(rows, hoverPosition.y) : null)+ (hoverPosition != null && visible.length > 1 ? findClosestSeriesKey(visible, hoverPosition.y) : null)+ // A pinned tooltip lists every row, so the other series stay inspectable and clickable.+ const closestRow =+ mode === 'single' && !isPinned && closestKey != null+ ? visible.find((s) => s.series.key === closestKey)+ : undefined+ const rows = closestRow+ ? [closestRow]+ : sortedByValue+ ? [...visible].sort((a, b) => (sortedByValue === 'asc' ? a.value - b.value : b.value - a.value))+ : visible[0]?.yPixel != null+ ? [...visible].sort((a, b) => (a.yPixel ?? Infinity) - (b.yPixel ?? Infinity))+ : visible+ const summable = rows.filter((s) => !s.series.overlay && s.series.visibility?.total !== false)const renderTotal = showTotal && summable.length > 1const total = summable.reduce((acc, s) => acc + s.value, 0)const formatTotal = totalFormatter ?? ((value: number): React.ReactNode => format(value, summable[0]))diff --git a/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts b/packages/quill/packages/charts/src/overlays/tooltipUtils.test.tsindex 2e04ace72e31..8a4760f5d68c 100644--- a/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts+++ b/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts@@ -25,6 +25,11 @@ describe('findClosestSeriesKey', () => {expect(findClosestSeriesKey([row('a', 50), row('b', 200), row('c', 110)], 100)).toBe('c')})+ it('skips overlay series, matching the hover dot', () => {+ const trend = { series: { key: 'trend', overlay: true }, yPixel: 100 }+ expect(findClosestSeriesKey([row('a', 150), trend], 100)).toBe('a')+ })+it('handles a single series', () => {expect(findClosestSeriesKey([row('x', 300)], 100)).toBe('x')})diff --git a/packages/quill/packages/charts/src/overlays/tooltipUtils.ts b/packages/quill/packages/charts/src/overlays/tooltipUtils.tsindex 9f31a9f043a6..d341e5e58b16 100644--- a/packages/quill/packages/charts/src/overlays/tooltipUtils.ts+++ b/packages/quill/packages/charts/src/overlays/tooltipUtils.ts@@ -5,12 +5,13 @@* exact regardless of segment size differences — no midpoint dead-zones at boundaries.** When only `yPixel` is present (line dots, non-stacked bars), falls back to closest by distance.+ * The distance pass skips `overlay` series (trend lines, moving averages), as the hover dot does.* Distance ties go to the last tied row: equal-valued lines sit exactly on top of each other and* paint in array order, so the last one is the visible line. This matches the hover dot's own* tie-breaking, keeping the highlighted tooltip row and the dot on the same series.*/export function findClosestSeriesKey(- rows: Array<{ series: { key: string }; yPixel?: number; yPixelBottom?: number }>,+ rows: Array<{ series: { key: string; overlay?: boolean }; yPixel?: number; yPixelBottom?: number }>,cursorY: number): string | null {// Range containment pass — exact for stacked segments.@@ -27,7 +28,7 @@ export function findClosestSeriesKey(let bestKey: string | null = nulllet bestDist = Infinityfor (const s of rows) {- if (s.yPixel == null) {+ if (s.yPixel == null || s.series.overlay) {continue}const dist = Math.abs(s.yPixel - cursorY)