Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hog-charts): tooltip improvements — animations, stable width, visual ordering, new props (#66523)

Sam Pennington908a5d6dbf53
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 962ab11a1155..7ecc92d682f0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -613,13 +613,13 @@ snapshots:
components-hogcharts-combochart--stacked-bars-and-line--light:
hash: v1.k794b7964.da86914291718262e6fc1aa52483bcca08ac08c9c2fad67c5f877d6cf78151f7.qO61mSB67aOC7auAYE6KLt69LLRyWdM_VM-Vf0qrq6Q
components-hogcharts-defaulttooltip--per-series-formatter-with-total--dark:
- hash: v1.k794b7964.bc81bacecf93313ceead33c7eadadbc36f3f6239f95f1e5405f5be64f96f20e3.kUs6tYMWSqbPUuPy6-LkQu2g38aenMaT3sdN0D22B70
+ hash: v1.k794b7964.124e8c6c02eda1eabc88072323004b4df404b4b539125d0e73b46997b9d365e2.d3YmjVMDPNNbI9yjh1GdBppT3Y6xOmRghIxTJLTUqIg
components-hogcharts-defaulttooltip--per-series-formatter-with-total--light:
- hash: v1.k794b7964.3c1e3c311bae5101469e22cafc7f74d5ad41cf0f54bf7714df633c13ef3f08d3.2GwpmmJTaORM9mri-C_bdwxT74v-M5vKDkAV6SHrpy0
+ hash: v1.k794b7964.43a6bfbd127483522da772b8a1be08ef580fa3aa7dc1c1eea3ec838d38d3d99d.TRRK7ylkXFKeTBSZfgaNJsPVxyoYrQG2vP6cEhfnej8
components-hogcharts-defaulttooltip--total-excludes-overlay--dark:
- hash: v1.k794b7964.1c7feb24fd91fd2f9f6e58bd4b7a6dd99df9557d54b538aef053721d78a6646e.XZwirTspatNnGmM_0BAvAZsS0p5CDZDRndxtlcvUaho
+ hash: v1.k794b7964.11de5c0850da2b4c11b23c5e761daf9747e97188d932debdf7fc6e3f7e57a79b.yfjzwxt0kwNXcAYt66YZq0UwZ7wJ4FNykUoNQXKyB4M
components-hogcharts-defaulttooltip--total-excludes-overlay--light:
- hash: v1.k794b7964.1ed784a5f699a9d97d316433353d8d58fcc579467053dc91e6c809e9d56832fd.cMmuE4gB3CMZZU6KNPeZPwZ_vKuMuD4BskF24IVQOCc
+ hash: v1.k794b7964.5cbfe6cd1728b688fcb8628fc94c304317cb84074e072bb2345179dffade807d.uRlkB5Chn06Zhoeh-QRxv5pfT64ZV_7dbcEGJs6zFCo
components-hogcharts-legend--built-in-toggle-bottom--dark:
hash: v1.k794b7964.a44913b0e0cdf88b5d0d8960560fa4ce5a663f0b187cdcc5a723d1bb9b653fc6.UksdQY23gh9zRrpzKMZvncH2EPYvXRVmC-_Uw9thCVY
components-hogcharts-legend--built-in-toggle-bottom--light:
@@ -703,11 +703,11 @@ snapshots:
components-hogcharts-linechart--hovering-interior--dark:
hash: v1.k794b7964.e00419153bb0750b0e9a6afc8119b1c46a73f8f6d7c98a5228b6c938e6c80123.O3tjnBxlJLi3amxIR6nJDype6f3RmspiZI63eC5CMHs
components-hogcharts-linechart--hovering-interior--light:
- hash: v1.k794b7964.9186ed84789ab03631d38096923a8632d535130057b6f92832decb65178be942.wGuboSulPIhdM2_GiDolvQD1kRpdyhlQuz9PFet_vSY
+ hash: v1.k794b7964.0ba6d470f454d7be136711d8b54d9fa672044b46e1f20f5140c25407219fa0b8.yumvfLO0uFQvQV7Cg-IHtaLNcfJXTCppRZvP2zTR9Rs
components-hogcharts-linechart--hovering-multi-series--dark:
- hash: v1.k794b7964.157939c1c62878808f9cfeffe7d10eb2b2dab6abdc98188102c23fce01e14fbd.FykAEyCz8bzzPkEoYgVpE-FBg4ncwlWAoKDgseFD-bA
+ hash: v1.k794b7964.eb7a2c044defd49850e6400f68e591aa497b607174aa820801cfc6eac88dfb3e.TYhyuMBPmdCN4nWK-rcq3GBJnaIpJCZPGjlaywQpkCc
components-hogcharts-linechart--hovering-multi-series--light:
- hash: v1.k794b7964.2d2effaf2935816c82ddca8e6b46b1245a1c8bc7589c8d63cbae2398060e5001.UZwi1m_dJL4B6q1zWUpCUyEf2qnHxKAs83LEfm7a_Bw
+ hash: v1.k794b7964.cd735ea54997a2736016a288f80eeed95ad8754feba47203132d8d3a1ffbafba.vRo8PIM73e1EF7B3gRRW3JQwOQe41xlR-jlMzwjeGJg
components-hogcharts-linechart--hovering-over-aux-series--dark:
hash: v1.k794b7964.1251a1dc7a11763c51054b76bcc092db995f51208e20e3ffe668690ae763c38b.L0wjl3-x2fOMd9HZpRiQP5GaQLJUBDzhFwkno_qgqdM
components-hogcharts-linechart--hovering-over-aux-series--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 4dc100f2e78b..8e4fccdfd52f 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -67,7 +67,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
```
- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`) compose as children.
-- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.
+- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"). `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.
- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint).
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period).
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
index 5a0aa91f6bea..a78f49b04b09 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
@@ -248,23 +248,25 @@ describe('BarChart', () => {
expect(tooltip.series.b.value).toBe(15)
})
- it('stacked tooltip bubbles the cursor-resolved segment to seriesData[0]', async () => {
- // At index 1: a=20 (bottom of stack), b=15 (on top). Mid-plot lands in b's range.
+ it('stacked tooltip keeps series in declaration order regardless of cursor height', async () => {
+ // At index 1: a=20 (bottom of stack), b=15 (on top). The tooltip lists the whole stack in
+ // declaration order — visual top-to-bottom ordering is handled downstream by DefaultTooltip's
+ // yPixel sort, so seriesData stays declaration-ordered no matter which segment the cursor is over.
const { chart } = renderHogChart(
<BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ barLayout: 'stacked' }} />
)
chart.hoverAtIndex(1)
- const tipB = await chart.waitForTooltip()
- expect(tipB.seriesData[0].series.key).toBe('b')
+ const tipMid = await chart.waitForTooltip()
+ expect(tipMid.seriesData.map((s) => s.series.key)).toEqual(['a', 'b'])
const step = dimensions.plotWidth / LABELS.length
- // Just inside the bottom edge of the plot, well below b's top to land in a's segment.
+ // Move the cursor down into a's segment — the data order must not change (no bubbling).
const NEAR_BOTTOM_OFFSET_PX = 8
fireEvent.mouseMove(chart.element, {
clientX: dimensions.plotLeft + step * 1.5,
clientY: dimensions.plotTop + dimensions.plotHeight - NEAR_BOTTOM_OFFSET_PX,
})
- const tipA = await chart.waitForTooltip()
- expect(tipA.seriesData[0].series.key).toBe('a')
+ const tipLow = await chart.waitForTooltip()
+ expect(tipLow.seriesData.map((s) => s.series.key)).toEqual(['a', 'b'])
})
it('stacked onPointClick routes to the segment whose rect contains the cursor', async () => {
@@ -411,7 +413,7 @@ describe('BarChart', () => {
['mid slice (20 < x < 50)', 30, 'mid', 50],
['big slice (50 < x < 100)', 75, 'big', 100],
])(
- 'tooltip narrows to the visible segment with its own value for cursor in the %s',
+ 'tooltip surfaces the visible segment with its own value for cursor in the %s',
async (_name, valueAtCursor, key, expectedValue) => {
const { chart } = renderHogChart(
<BarChart
@@ -426,8 +428,11 @@ describe('BarChart', () => {
clientY: yMidBand,
})
const tooltip = await chart.waitForTooltip()
- expect(tooltip.seriesData[0].series.key).toBe(key)
- expect(tooltip.seriesData[0].value).toBe(expectedValue)
+ // Rows stay in declaration order (visual ordering is handled by DefaultTooltip),
+ // but the segment under the cursor is revalued to its own dataIndex value rather
+ // than the zero of the band-collapsed cell.
+ const visible = tooltip.seriesData.find((s) => s.series.key === key)
+ expect(visible?.value).toBe(expectedValue)
}
)
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
index b377138887bc..c45a9df139ea 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
@@ -56,8 +56,8 @@ export function BarTooltip<Meta>({
return <>{userTooltip ? userTooltip(ctx) : <DefaultTooltip {...ctx} {...tooltipConfig} />}</>
}
-/** Moves the cursor-resolved segment to seriesData[0] and (for sparse-stacked overlap)
- * re-reads its value at its own dataIndex so it isn't a zero from a band-collapsed cell. */
+/** Filters seriesData to only the segments hit by the cursor, and (for sparse-stacked overlap)
+ * re-reads the visible segment's value at its own dataIndex so it isn't a zero from a band-collapsed cell. */
function narrowSeriesByCursor<Meta>(
ctx: TooltipContext<Meta>,
scales: BarScaleSet,
@@ -109,19 +109,13 @@ function narrowSeriesByCursor<Meta>(
visibleKey = visible.series.key
visibleDataIndex = visible.dataIndex
}
- let filtered = ctx.seriesData.filter((entry) => hits.has(entry.series.key))
- if (isStackedLayout(layout) && filtered.length > 1 && visibleKey) {
- const idx = filtered.findIndex((entry) => entry.series.key === visibleKey)
- if (idx > 0) {
- filtered = [filtered[idx], ...filtered.filter((_, i) => i !== idx)]
- }
- }
+ const filtered = ctx.seriesData.filter((entry) => hits.has(entry.series.key))
// For sparse-stacked overlap ctx.dataIndex is a zero cell for the visible series. Rewrite
// the entry's value (and ctx.dataIndex) to the segment's own index so row clicks route
// correctly downstream.
if (visibleKey != null && visibleDataIndex != null && visibleDataIndex !== ctx.dataIndex) {
const di = visibleDataIndex
- filtered = filtered.map((entry) => {
+ const revalued = filtered.map((entry) => {
if (entry.series.key !== visibleKey) {
return entry
}
@@ -129,7 +123,7 @@ function narrowSeriesByCursor<Meta>(
const value = typeof raw === 'number' && Number.isFinite(raw) ? raw : entry.value
return { ...entry, value }
})
- return { ...ctx, seriesData: filtered, dataIndex: di }
+ return { ...ctx, seriesData: revalued, dataIndex: di }
}
return { ...ctx, seriesData: filtered }
}
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index c85624fa7738..040c0e29e058 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -31,6 +31,7 @@ import type {
Series,
TooltipContext,
} from '../../core/types'
+import { closestHoverSeriesKey } from './closest-hover-series'
// Brand for the private ChartScales._private slot used by LineChart. The base Chart
// and other chart types treat this as opaque; LineChart's drawStatic narrows back to it.
@@ -201,14 +202,28 @@ function LineChartInner<Meta = unknown>({
)
const drawHover = useCallback(
- ({ ctx, scales, series: coloredSeries, labels: drawLabels, hoverIndex, theme }: ChartDrawArgs): boolean => {
+ ({ ctx, scales, series: coloredSeries, labels: drawLabels, hoverIndex, hoverPosition, theme }: ChartDrawArgs): boolean => {
if (hoverIndex < 0) {
return false
}
+ // Find the series whose y-pixel at the hovered index is closest to the cursor so only
+ // that series gets a dot — avoids a column of rings on dense multi-series charts.
+ const closestKey =
+ hoverPosition != null
+ ? closestHoverSeriesKey(
+ coloredSeries,
+ (s) => {
+ const data = stackedData?.get(s.key)?.top ?? s.data
+ return resolveYScaleForSeries(scales, s)(data[hoverIndex])
+ },
+ hoverPosition.y
+ )
+ : null
// Overlays (moving averages, trend lines) and fill-between lower bounds opt out — in
// percent-stack mode the y-domain is [0, 1], so their raw values would ring far off-plot.
// `drawLineHoverPoints` handles those skips; we supply the stacked-top y per series.
- return drawLineHoverPoints(ctx, coloredSeries, theme.backgroundColor ?? '#ffffff', (s) => {
+ const dotSeries = closestKey != null ? coloredSeries.filter((s) => s.key === closestKey) : coloredSeries
+ return drawLineHoverPoints(ctx, dotSeries, theme.backgroundColor ?? '#ffffff', (s) => {
const data = stackedData?.get(s.key)?.top ?? s.data
const x = scales.x(drawLabels[hoverIndex])
if (x == null) {
diff --git a/packages/quill/packages/charts/src/charts/LineChart/closest-hover-series.test.ts b/packages/quill/packages/charts/src/charts/LineChart/closest-hover-series.test.ts
new file mode 100644
index 000000000000..971ffd02e7df
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/LineChart/closest-hover-series.test.ts
@@ -0,0 +1,66 @@
+import type { ResolvedSeries } from '../../core/types'
+import { closestHoverSeriesKey } from './closest-hover-series'
+
+const series = (key: string, overrides: Partial<ResolvedSeries> = {}): ResolvedSeries => ({
+ key,
+ label: key,
+ color: '#000',
+ data: [],
+ ...overrides,
+})
+
+// y-pixels keyed by series.key, so each test controls how far each line sits from the cursor.
+const yPixelFromMap =
+ (map: Record<string, number>) =>
+ (s: ResolvedSeries): number =>
+ map[s.key] ?? NaN
+
+describe('closestHoverSeriesKey', () => {
+ it('picks the series whose y-pixel is nearest the cursor', () => {
+ const result = closestHoverSeriesKey(
+ [series('a'), series('b'), series('c')],
+ yPixelFromMap({ a: 10, b: 100, c: 40 }),
+ 45
+ )
+ expect(result).toBe('c')
+ })
+
+ it('skips excluded, fill-between lower-bound, and overlay series even when they are nearest', () => {
+ // The off-limits series all sit exactly on the cursor; the only eligible one is far away
+ // but must still win.
+ const result = closestHoverSeriesKey(
+ [
+ series('hidden', { visibility: { excluded: true } }),
+ series('lower', { fill: { lowerData: [1, 2, 3] } }),
+ series('trend', { overlay: true }),
+ series('real', {}),
+ ],
+ yPixelFromMap({ hidden: 50, lower: 50, trend: 50, real: 200 }),
+ 50
+ )
+ expect(result).toBe('real')
+ })
+
+ it('ignores series with a non-finite y-pixel (off-plot / collapsed cell)', () => {
+ const result = closestHoverSeriesKey(
+ [series('a'), series('b')],
+ yPixelFromMap({ a: NaN, b: 300 }),
+ 0
+ )
+ expect(result).toBe('b')
+ })
+
+ it('returns null when no series qualifies', () => {
+ const result = closestHoverSeriesKey(
+ [series('only', { overlay: true }), series('nan')],
+ yPixelFromMap({ only: 10, nan: NaN }),
+ 10
+ )
+ expect(result).toBeNull()
+ })
+
+ it('keeps the first series on a distance tie (strict less-than)', () => {
+ const result = closestHoverSeriesKey([series('a'), series('b')], yPixelFromMap({ a: 30, b: 70 }), 50)
+ expect(result).toBe('a')
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/LineChart/closest-hover-series.ts b/packages/quill/packages/charts/src/charts/LineChart/closest-hover-series.ts
new file mode 100644
index 000000000000..12a5a6b37168
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/LineChart/closest-hover-series.ts
@@ -0,0 +1,34 @@
+import type { ResolvedSeries } from '../../core/types'
+
+/**
+ * Of the visible series, the key whose y-pixel at the hovered index sits closest to the cursor —
+ * so a multi-series line chart draws a single hover dot on the line under the cursor instead of a
+ * column of rings across every series.
+ *
+ * Excluded series (legend-hidden), fill-between lower bounds, and overlays (moving averages, trend
+ * lines, goal lines) are never candidates: in percent-stack mode their raw values ring far off-plot,
+ * and they aren't the line the user is pointing at. `yPixelFor` returns a series' y-pixel at the
+ * hovered index; a non-finite y skips that series. Returns null when no series qualifies.
+ */
+export function closestHoverSeriesKey(
+ series: readonly ResolvedSeries[],
+ yPixelFor: (series: ResolvedSeries) => number,
+ cursorY: number
+): string | null {
+ let closestKey: string | null = null
+ let minDist = Infinity
+ for (const s of series) {
+ if (s.visibility?.excluded || s.fill?.lowerData || s.overlay) {
+ continue
+ }
+ const y = yPixelFor(s)
+ if (Number.isFinite(y)) {
+ const dist = Math.abs(y - cursorY)
+ if (dist < minDist) {
+ minDist = dist
+ closestKey = s.key
+ }
+ }
+ }
+ return closestKey
+}
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
index e9659d2b1bbd..862d21f0ddb3 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, screen } from '@testing-library/react'
+import { cleanup, fireEvent, screen } from '@testing-library/react'
import type { TooltipContext } from '../core/types'
import { createDefaultTooltipAccessor, makeOverlayContext, renderOverlayInChart } from '../testing'
@@ -23,7 +23,11 @@ const CANVAS_BOUNDS = {
type TooltipProps = Omit<Parameters<typeof DefaultTooltip>[0], keyof TooltipContext>
-function renderTooltip(props: TooltipProps = {}, seriesData: TooltipContext['seriesData'] = SERIES_DATA): void {
+function renderTooltip(
+ props: TooltipProps = {},
+ seriesData: TooltipContext['seriesData'] = SERIES_DATA,
+ ctxOverrides: Partial<TooltipContext> = {}
+): void {
const ctx: TooltipContext = {
dataIndex: 0,
label: 'When',
@@ -32,6 +36,7 @@ function renderTooltip(props: TooltipProps = {}, seriesData: TooltipContext['ser
hoverPosition: null,
canvasBounds: CANVAS_BOUNDS,
isPinned: false,
+ ...ctxOverrides,
}
renderOverlayInChart(<DefaultTooltip {...ctx} {...props} />, makeOverlayContext(SCALES))
}
@@ -165,4 +170,74 @@ describe('DefaultTooltip', () => {
expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['Visits', 'Goal'])
})
})
+
+ describe('row presentation props', () => {
+ const TWO_SERIES: TooltipContext['seriesData'] = [
+ { series: { key: 'a', label: 'Alpha', data: [] }, value: 10, color: '#000' },
+ { series: { key: 'b', label: 'Beta', data: [] }, value: 25, color: '#111' },
+ ]
+
+ it('renders the header label by default', () => {
+ renderTooltip({})
+ expect(document.querySelector('[data-attr="hog-chart-tooltip-label"]')?.textContent).toBe('When')
+ })
+
+ it('hides the header label when showHeader is false', () => {
+ renderTooltip({ showHeader: false })
+ expect(document.querySelector('[data-attr="hog-chart-tooltip-label"]')).toBeNull()
+ })
+
+ it('labelRenderer overrides each row label', () => {
+ renderTooltip({ labelRenderer: (entry) => `# ${entry.series.label}` }, TWO_SERIES)
+ expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['# Alpha', '# Beta'])
+ })
+
+ it('hideZeroRows drops rows whose value is exactly 0', () => {
+ const withZero: TooltipContext['seriesData'] = [
+ { series: { key: 'a', label: 'Alpha', data: [] }, value: 0, color: '#000' },
+ { series: { key: 'b', label: 'Beta', data: [] }, value: 25, color: '#111' },
+ ]
+ renderTooltip({ hideZeroRows: true }, withZero)
+ expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['Beta'])
+ })
+
+ it('keeps zero-value rows when hideZeroRows is not set', () => {
+ const withZero: TooltipContext['seriesData'] = [
+ { series: { key: 'a', label: 'Alpha', data: [] }, value: 0, color: '#000' },
+ { series: { key: 'b', label: 'Beta', data: [] }, value: 25, color: '#111' },
+ ]
+ renderTooltip({}, withZero)
+ expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['Alpha', 'Beta'])
+ })
+
+ it('onRowClick fires with the clicked row entry', () => {
+ const onRowClick = jest.fn()
+ renderTooltip({ onRowClick }, TWO_SERIES)
+ const rows = document.querySelectorAll<HTMLElement>('[data-attr="hog-chart-tooltip-row"]')
+ fireEvent.click(rows[1])
+ expect(onRowClick).toHaveBeenCalledTimes(1)
+ expect(onRowClick.mock.calls[0][0].series.key).toBe('b')
+ })
+
+ it('sorts rows by yPixel ascending (visual top-to-bottom) when not sortedByValue', () => {
+ const withYPixel: TooltipContext['seriesData'] = [
+ { series: { key: 'low', label: 'Low', data: [] }, value: 5, color: '#000', yPixel: 300 },
+ { series: { key: 'high', label: 'High', data: [] }, value: 5, color: '#111', yPixel: 50 },
+ ]
+ renderTooltip({}, withYPixel)
+ // yPixel 50 sits visually higher on the canvas, so it leads despite being declared second.
+ expect(createDefaultTooltipAccessor(document.body).rows()).toEqual(['High', 'Low'])
+ })
+
+ 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 },
+ { series: { key: 'b', label: 'Beta', data: [] }, value: 5, color: '#111', yPixel: 300 },
+ ]
+ renderTooltip({}, withYPixel, { hoverPosition: { x: 0, y: 290 } })
+ const closest = document.querySelectorAll<HTMLElement>('[data-closest="true"]')
+ expect(closest).toHaveLength(1)
+ expect(closest[0].querySelector('[data-attr="hog-chart-tooltip-series"]')?.textContent).toBe('Beta')
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
index 935e6249335c..c8e7589cb017 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
@@ -13,11 +13,18 @@ export interface DefaultTooltipProps<Meta = unknown> extends TooltipContext<Meta
/** Formats each row's value. Receives the row's `seriesData` entry as a second argument so
* callers can format per-series — e.g. each SQL column with its own currency/duration/percent
* settings — rather than with one global formatter. Defaults to `toLocaleString`. Existing
- * callers that take only `value` keep working (the extra argument is ignored). */
- valueFormatter?: (value: number, entry: SeriesDatum<Meta>) => string
+ * callers that take only `value` keep working (the extra argument is ignored). May return a
+ * node (e.g. a property-formatted value) and not just a string. */
+ valueFormatter?: (value: number, entry: SeriesDatum<Meta>) => React.ReactNode
/** Transforms the header label before display — use to convert raw ISO strings to human-
* readable dates. Defaults to rendering the label as-is. */
- labelFormatter?: (label: string) => string
+ labelFormatter?: (label: string) => React.ReactNode
+ /** Overrides how each row's label renders. Defaults to the series label. Use for richer labels
+ * than a plain string — e.g. breakdown-value pills. */
+ labelRenderer?: (entry: SeriesDatum<Meta>) => React.ReactNode
+ /** Show the header label row. Defaults to true; pass false for charts without a meaningful
+ * header (e.g. pie slices, aggregated single-column bars). */
+ showHeader?: boolean
/** Append a footer row summing the visible series at the hovered point. `overlay` series
* (e.g. goal lines) are excluded from the sum, and the row is suppressed when fewer than two
* summable series remain — a single-series total would just restate the one row. */
@@ -26,9 +33,15 @@ export interface DefaultTooltipProps<Meta = unknown> extends TooltipContext<Meta
totalLabel?: string
/** Formats the total value. Defaults to the `valueFormatter` (applied with the first summable
* row's entry) or `toLocaleString`. */
- totalFormatter?: (value: number) => string
+ totalFormatter?: (value: number) => React.ReactNode
/** Sort series rows by value descending so the highest value appears at the top. */
sortedByValue?: boolean
+ /** 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
+ * be pinned for clicks to land (an unpinned tooltip has `pointer-events: none`). Used to open a
+ * drill-down (e.g. the persons modal) for a specific series. */
+ onRowClick?: (entry: SeriesDatum<Meta>) => void
/** Extra content rendered below all rows and the total, separated by a divider. */
footer?: React.ReactNode
}
@@ -39,19 +52,29 @@ export function DefaultTooltip<Meta = unknown>({
hoverPosition,
valueFormatter,
labelFormatter,
+ labelRenderer,
+ showHeader = true,
showTotal,
totalLabel = 'Total',
totalFormatter,
sortedByValue,
+ hideZeroRows,
+ onRowClick,
footer,
}: DefaultTooltipProps<Meta>): React.ReactElement {
- const format = valueFormatter ?? ((value: number): string => value.toLocaleString())
- const rows = sortedByValue ? [...seriesData].sort((a, b) => b.value - a.value) : seriesData
+ 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)
- const closestKey = hoverPosition != null ? findClosestSeriesKey(rows, hoverPosition.y) : null
+ const closestKey =
+ hoverPosition != null && rows.length > 1 ? findClosestSeriesKey(rows, hoverPosition.y) : null
const renderTotal = showTotal && summable.length > 1
const total = summable.reduce((acc, s) => acc + s.value, 0)
- const formatTotal = totalFormatter ?? ((value: number): string => format(value, summable[0]))
+ const formatTotal = totalFormatter ?? ((value: number): React.ReactNode => format(value, summable[0]))
const scrollContainerRef = useRef<HTMLDivElement>(null)
const [canScrollUp, setCanScrollUp] = useState(false)
const [canScrollDown, setCanScrollDown] = useState(false)
@@ -78,15 +101,19 @@ export function DefaultTooltip<Meta = unknown>({
if (!el) {
return
}
- // Scroll only the tooltip container — scrollIntoView would walk all scroll ancestors.
- const elTop = el.offsetTop
- const elBottom = elTop + el.offsetHeight
- const containerTop = container.scrollTop
- const containerBottom = containerTop + container.clientHeight
- if (elBottom > containerBottom) {
- container.scrollTop = elBottom - container.clientHeight
- } else if (elTop < containerTop) {
- container.scrollTop = elTop
+ // Use getBoundingClientRect so the position is relative to the container's visible area,
+ // not to the nearest positioned ancestor (which may not be the scroll container).
+ const containerRect = container.getBoundingClientRect()
+ const elRect = el.getBoundingClientRect()
+ const elTopInView = elRect.top - containerRect.top
+ const elBottomInView = elRect.bottom - containerRect.top
+ // Scroll before the row enters the mask fade zone (top/bottom 20%), not just when it's
+ // fully off-screen — otherwise the highlighted row can sit in the faded region.
+ const fadeZone = container.clientHeight * 0.2
+ if (elBottomInView > container.clientHeight - fadeZone) {
+ container.scrollTop += elBottomInView - (container.clientHeight - fadeZone)
+ } else if (elTopInView < fadeZone) {
+ container.scrollTop += elTopInView - fadeZone
}
}, [closestKey])
@@ -105,9 +132,11 @@ export function DefaultTooltip<Meta = unknown>({
return (
<TooltipSurface>
- <div data-attr="hog-chart-tooltip-label" className="font-semibold mb-1 opacity-60">
- {labelFormatter ? labelFormatter(label) : label}
- </div>
+ {showHeader && (
+ <div data-attr="hog-chart-tooltip-label" className="font-semibold mb-1 opacity-60">
+ {labelFormatter ? labelFormatter(label) : label}
+ </div>
+ )}
<div
ref={scrollContainerRef}
onScroll={updateScrollFades}
@@ -115,22 +144,33 @@ export function DefaultTooltip<Meta = unknown>({
maxHeight: ROWS_MAX_HEIGHT,
overflowY: 'auto',
scrollbarWidth: 'none',
+ scrollBehavior: 'smooth',
maskImage,
WebkitMaskImage: maskImage,
}}
>
{rows.map((s) => {
const isClosest = s.series.key === closestKey
+ const clickable = onRowClick ? ' cursor-pointer hover:bg-current/10' : ''
+ const labelContent = labelRenderer ? labelRenderer(s) : s.series.label
return (
<div
key={s.series.key}
data-attr="hog-chart-tooltip-row"
data-closest={isClosest ? 'true' : undefined}
- className={`flex items-center gap-2 min-w-0${isClosest ? ' font-semibold' : ''}`}
+ className={`flex items-center gap-2 min-w-0 py-0.5 px-1.5 rounded transition-colors duration-150${isClosest ? ' font-semibold bg-current/[.1]' : ''}${clickable}`}
+ onClick={onRowClick ? () => onRowClick(s) : undefined}
>
<TooltipSwatch color={s.color} />
- <span data-attr="hog-chart-tooltip-series" className="flex-1 min-w-0 truncate">
- {s.series.label}
+ {/* Grid-stack the label so an invisible semibold ghost always reserves
+ the bold width — the visible span toggles weight without reflowing. */}
+ <span className="flex-1 min-w-0 overflow-hidden grid">
+ <span className="font-semibold invisible truncate [grid-area:1/1]" aria-hidden="true">
+ {labelContent}
+ </span>
+ <span data-attr="hog-chart-tooltip-series" className="truncate [grid-area:1/1]">
+ {labelContent}
+ </span>
</span>
<strong data-attr="hog-chart-tooltip-value">{format(s.value, s)}</strong>
</div>
@@ -146,7 +186,9 @@ export function DefaultTooltip<Meta = unknown>({
<strong data-attr="hog-chart-tooltip-value">{formatTotal(total)}</strong>
</div>
)}
- {footer && <div className="mt-1 pt-1 border-t border-current/25 text-xs opacity-60">{footer}</div>}
+ {footer && (
+ <div className="mt-1 pt-1 border-t border-current/25 text-xs opacity-60 text-center">{footer}</div>
+ )}
</TooltipSurface>
)
}
diff --git a/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx b/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx
index 102ccc8a893e..c1435ccc0fe0 100644
--- a/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx
+++ b/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx
@@ -29,7 +29,7 @@ export function TooltipSurface({
width: 'fit-content',
maxWidth: '20rem',
paddingBlock: '0.375rem',
- paddingInline: '0.75rem',
+ paddingInline: '0.5rem',
fontSize: 'var(--text-xs, 0.75rem)',
lineHeight: 1.4,
borderRadius: 'var(--radius-sm, 0.375rem)',