: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(insights): SQL tooltip improvements + persons modal date navigation (#66157)
Sam Pennington1ade2a06149d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex da8366fac595..9772aaca475a 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-Vf0qrq6Qcomponents-hogcharts-defaulttooltip--per-series-formatter-with-total--dark:- hash: v1.k794b7964.f84c6d590af37262d4f4fd8fbaebfb9e2492af1eb7acf3c8704ff451f4ca9c71.tTB7BDNDofqyzbfrBcZd6TNmUAeS2jNpY_txIc2UiZk+ hash: v1.k794b7964.bc81bacecf93313ceead33c7eadadbc36f3f6239f95f1e5405f5be64f96f20e3.kUs6tYMWSqbPUuPy6-LkQu2g38aenMaT3sdN0D22B70components-hogcharts-defaulttooltip--per-series-formatter-with-total--light:- hash: v1.k794b7964.8e2664634344165a186e53bfd800398abccf8f8a97323ff24ce2ac86b532ee9d.O7wLPrG3BCr55c3pCRiyhrND_NRNVjVab1zQh38BNeM+ hash: v1.k794b7964.3c1e3c311bae5101469e22cafc7f74d5ad41cf0f54bf7714df633c13ef3f08d3.2GwpmmJTaORM9mri-C_bdwxT74v-M5vKDkAV6SHrpy0components-hogcharts-defaulttooltip--total-excludes-overlay--dark:- hash: v1.k794b7964.586cbc343561fe2ea416c4e8a15661d80f0dc0e6602c4c4505fb763a960e3fec.wnr2iqA9493GIdPtZgO3pqa1uiD9pZcM3L01W8_FZ-Q+ hash: v1.k794b7964.1c7feb24fd91fd2f9f6e58bd4b7a6dd99df9557d54b538aef053721d78a6646e.XZwirTspatNnGmM_0BAvAZsS0p5CDZDRndxtlcvUahocomponents-hogcharts-defaulttooltip--total-excludes-overlay--light:- hash: v1.k794b7964.cf566924008a871da770d7d0a0b7a2ac6748823639d3d60ca60344770f581a2a.7s92rB7AHoeq-uQd_tSJGFVCn3cU-LQeOQVJ2qyvLWo+ hash: v1.k794b7964.1ed784a5f699a9d97d316433353d8d58fcc579467053dc91e6c809e9d56832fd.cMmuE4gB3CMZZU6KNPeZPwZ_vKuMuD4BskF24IVQOCccomponents-hogcharts-legend--built-in-toggle-bottom--dark:hash: v1.k794b7964.a44913b0e0cdf88b5d0d8960560fa4ce5a663f0b187cdcc5a723d1bb9b653fc6.UksdQY23gh9zRrpzKMZvncH2EPYvXRVmC-_Uw9thCVYcomponents-hogcharts-legend--built-in-toggle-bottom--light:diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsxindex 06b9518defdd..493f83e852f5 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx@@ -143,6 +143,9 @@ export type LineGraphProps = {dashboardId?: stringgoalLines?: GoalLine[]className?: string+ /** Called when the user clicks a data point. Receives the series key, x-axis index, and label.+ * When provided, the SQL chart shows a "click to inspect" hint in the tooltip. */+ onPointClick?: (seriesKey: string, dataIndex: number, label: string) => void}const LegacyLineGraph = ({diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsxindex ce2721eafefb..85e0823c83fc 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.test.tsx@@ -109,7 +109,7 @@ describe('SqlBarGraph', () => {const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)expect(tooltip.value('a')).toBe('3,000')- expect(tooltip.label()).toBe('2025-12-01')+ expect(tooltip.label()).toBe('Dec 1, 2025')expect(tooltip.swatchColors()).toHaveLength(1)})})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsxindex e0153b89106b..20ed143d0275 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx@@ -189,7 +189,7 @@ describe('SqlLineGraph', () => {const tooltip = await sqlChart.hoverTooltip(HOVER, MONTHS.length)expect(tooltip.value('pageviews')).toBe('300')- expect(tooltip.label()).toBe('2025-12-01')+ expect(tooltip.label()).toBe('Dec 1, 2025')expect(tooltip.swatchColors()).toEqual([expect.stringMatching(/^rgb/)])})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsxindex 3123af38408e..9c1a8672bc28 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx@@ -1,11 +1,12 @@import clsx from 'clsx'+import { useCallback } from 'react'-import { TimeSeriesLineChart } from '@posthog/quill-charts'+import { DefaultTooltip, TimeSeriesLineChart, type PointClickData, type TooltipContext } from '@posthog/quill-charts'import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'import { LineGraphProps } from './LineGraph'-import { SqlLineSeriesMeta, buildLineChartConfig } from './sqlLineGraphAdapter'+import { SqlLineSeriesMeta, buildLineChartConfig, formatSqlSeriesValue } from './sqlLineGraphAdapter'import { useSqlChartModel } from './useSqlChartModel'const handleChartError = makeChartErrorHandler('sql-line-chart')@@ -17,8 +18,44 @@ const handleChartError = makeChartErrorHandler('sql-line-chart')* (per-column formatting, total row) is configured in {@link buildLineChartConfig}.*/export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {+ const { onPointClick: onPointClickProp } = propsconst model = useSqlChartModel(props, buildLineChartConfig)+ const onPointClick = useCallback(+ (data: PointClickData<SqlLineSeriesMeta>) => {+ onPointClickProp?.(data.series.key, data.dataIndex, data.label)+ },+ [onPointClickProp]+ )++ // When a click handler is wired, override the config-driven tooltip with a render prop so we+ // can add the inspect hint and sort by value. We pull the formatters off the built config to+ // avoid duplicating the per-column formatting logic.+ const renderTooltip = useCallback(+ (ctx: TooltipContext<SqlLineSeriesMeta>) => {+ if (!model) {+ return null+ }+ const { valueFormatter, labelFormatter, showTotal, totalFormatter } = model.config.tooltip ?? {}+ return (+ <DefaultTooltip+ {...ctx}+ valueFormatter={+ valueFormatter ??+ ((value, entry) =>+ formatSqlSeriesValue(value, (entry.series.meta as SqlLineSeriesMeta | undefined)?.settings))+ }+ labelFormatter={labelFormatter}+ showTotal={showTotal}+ totalFormatter={totalFormatter}+ sortedByValue+ footer="Click to inspect persons"+ />+ )+ },+ [model]+ )+return (<divclassName={clsx(@@ -33,6 +70,8 @@ export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {labels={model.labels}theme={model.theme}config={model.config}+ tooltip={onPointClickProp ? renderTooltip : undefined}+ onPointClick={onPointClickProp ? onPointClick : undefined}onError={handleChartError}/>)}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.tsindex d12f8a792437..c29a34423134 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts@@ -15,6 +15,8 @@ import {createXAxisTickCallback,} from '@posthog/quill-charts'+import { dayjs } from 'lib/dayjs'+import { ChartSettings, GoalLine, YAxisSettings } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'@@ -237,8 +239,6 @@ export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDis// Only pin an explicit color; otherwise let quill assign palette colors by index....(color ? { color } : {}),...(settings?.display?.yAxisPosition === 'right' ? { yAxisId: 'right' } : {}),- // Area fill, but never on a bar — a bar-override on an area-graph chart resolves to- // `type: 'bar'` yet `isAreaSeries` is still true for the whole area graph....(type !== 'bar' && isAreaSeries(visualizationType, settings)? { fill: { opacity: AREA_FILL_OPACITY } }: {}),@@ -286,6 +286,8 @@ export function buildSqlTooltipConfig(return {enabled: true,pinnable: true,+ placement: 'cursor',+ sortedByValue: true,valueFormatter: (value: number, entry: TooltipContext['seriesData'][number]) =>formatSqlSeriesValue(value, (entry.series.meta as SqlLineSeriesMeta | undefined)?.settings),showTotal: chartSettings.showTotalRow !== false,@@ -293,6 +295,21 @@ export function buildSqlTooltipConfig(}}+/** Returns a tooltip label formatter for date/datetime x-axes, or undefined for non-date axes. */+function buildSqlDateLabelFormatter(+ xData: AxisSeries<string>,+ timezone: string+): ((label: string) => string) | undefined {+ const typeName = xData.column.type.name+ if (typeName === 'DATETIME') {+ return (label: string) => dayjs(label).tz(timezone).format('MMM D, HH:mm')+ }+ if (typeName === 'DATE') {+ return (label: string) => dayjs(label).format('MMM D, YYYY')+ }+ return undefined+}+interface BuildConfigArgs {xData: AxisSeries<string>chartSettings: ChartSettings@@ -381,6 +398,7 @@ export function buildLineChartConfig({}: BuildConfigArgs): TimeSeriesLineChartConfig {const leftSeries = seriesForAxis(ySeriesData, 'left')const rightSeries = seriesForAxis(ySeriesData, 'right')+ const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),@@ -404,7 +422,10 @@ export function buildLineChartConfig({trendLines: buildTrendLineConfigs(ySeriesData),legend: buildLegendConfig(chartSettings),valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),- tooltip: buildSqlTooltipConfig(chartSettings, ySeriesData),+ tooltip: {+ ...buildSqlTooltipConfig(chartSettings, ySeriesData),+ ...(labelFormatter ? { labelFormatter } : {}),+ },}}@@ -417,6 +438,7 @@ export function buildBarChartConfig({ySeriesData,}: BuildBarConfigArgs): TimeSeriesBarChartConfig {const barLayout = barLayoutForDisplay(visualizationType, chartSettings)+ const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),@@ -432,7 +454,7 @@ export function buildBarChartConfig({barLayout,legend: buildLegendConfig(chartSettings),valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),- tooltip: { enabled: true, pinnable: true },+ tooltip: { enabled: true, pinnable: true, placement: 'cursor', ...(labelFormatter ? { labelFormatter } : {}) },}}@@ -444,6 +466,8 @@ export function buildComboChartConfig({visualizationType,ySeriesData,}: BuildBarConfigArgs): TimeSeriesComboChartConfig {+ const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)+return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),yAxis: buildYAxisConfig(@@ -455,6 +479,9 @@ export function buildComboChartConfig({barLayout: comboBarLayoutForDisplay(visualizationType),legend: buildLegendConfig(chartSettings),valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),- tooltip: buildSqlTooltipConfig(chartSettings, ySeriesData),+ tooltip: {+ ...buildSqlTooltipConfig(chartSettings, ySeriesData),+ ...(labelFormatter ? { labelFormatter } : {}),+ },}}diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 9ce05aa9bce3..e8f3a422ea68 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -67,8 +67,8 @@ 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`, `showTotal`, `totalLabel`, `totalFormatter`. `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). `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'`. 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 four fields on `config.tooltip` (`{ enabled, pinnable, placement, valueFormatter, showTotal, totalLabel, totalFormatter }`). 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.+- `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.+- 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.- 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.diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsxindex 6884bf723e87..fbadf348c8f2 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx@@ -390,6 +390,7 @@ function BarChartInner<Meta = unknown>({topStackedKeyByAxis={topStackedKeyByAxis}layout={barLayout}isHorizontal={isHorizontal}+ tooltipConfig={config?.tooltip}/>)}onPointClick={onPointClick}diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsxindex 87550e6363bf..b377138887bc 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx@@ -3,7 +3,7 @@ import React from 'react'import type { BarChartPrivate } from '../../core/bar-layout'import { useChartLayout } from '../../core/chart-context'import type { BarScaleSet, StackedBand } from '../../core/scales'-import type { Series, TooltipContext } from '../../core/types'+import type { Series, TooltipConfig, TooltipContext } from '../../core/types'import { DefaultTooltip } from '../../overlays/DefaultTooltip'import {type BarLayout,@@ -22,6 +22,7 @@ export interface BarTooltipProps<Meta> {topStackedKeyByAxis: Map<string, string>layout: BarLayoutisHorizontal: boolean+ tooltipConfig?: TooltipConfig}export function BarTooltip<Meta>({@@ -32,6 +33,7 @@ export function BarTooltip<Meta>({topStackedKeyByAxis,layout,isHorizontal,+ tooltipConfig,}: BarTooltipProps<Meta>): React.ReactElement | null {const { scales, labels } = useChartLayout()const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart@@ -49,9 +51,9 @@ export function BarTooltip<Meta>({if (!narrowed) {return null}- return <>{userTooltip ? userTooltip(narrowed) : DefaultTooltip(narrowed)}</>+ return <>{userTooltip ? userTooltip(narrowed) : <DefaultTooltip {...narrowed} {...tooltipConfig} />}</>}- return <>{userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx)}</>+ return <>{userTooltip ? userTooltip(ctx) : <DefaultTooltip {...ctx} {...tooltipConfig} />}</>}/** Moves the cursor-resolved segment to seriesData[0] and (for sparse-stacked overlap)diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsxindex bacea09aef4d..88aabbe7b35f 100644--- a/packages/quill/packages/charts/src/core/Chart.tsx+++ b/packages/quill/packages/charts/src/core/Chart.tsx@@ -17,7 +17,6 @@ import { useLatest } from './hooks/useLatest'import { useResolvedYFormatter } from './hooks/useResolvedYFormatters'import { useStableResolveValue } from './hooks/useStableResolveValue'import { useYAxisMaps } from './hooks/useYAxisMaps'-import { computeYAxisGutters, type Gutter } from './y-axis-gutters'import type {ChartConfig,ChartDrawArgs,@@ -31,6 +30,7 @@ import type {Series,TooltipContext,} from './types'+import { computeYAxisGutters, type Gutter } from './y-axis-gutters'const DEFAULT_AXIS_COLOR = 'rgba(0, 0, 0, 0.5)'const DEFAULT_HOVER_ANIMATION_MS = 150@@ -128,10 +128,11 @@ export function Chart<Meta = unknown>({yAxes,} = config ?? {}- const { formatters: yAxisFormatters, positions: yAxisPositions, titles: yAxisTitles } = useYAxisMaps(- yAxes,- yAxisLabel- )+ const {+ formatters: yAxisFormatters,+ positions: yAxisPositions,+ titles: yAxisTitles,+ } = useYAxisMaps(yAxes, yAxisLabel)const hoverAnimationMs = resolveHoverAnimationMs(animateHover)const interactionAxis: 'x' | 'y' = axisOrientation === 'horizontal' ? 'y' : 'x'const {@@ -139,9 +140,11 @@ export function Chart<Meta = unknown>({pinnable: pinnableTooltip = false,placement: tooltipPlacement = 'follow-data',valueFormatter: tooltipValueFormatter,+ labelFormatter: tooltipLabelFormatter,showTotal: tooltipShowTotal,totalLabel: tooltipTotalLabel,totalFormatter: tooltipTotalFormatter,+ sortedByValue: tooltipSortedByValue,} = tooltipConfig ?? {}// No render prop: render DefaultTooltip with config.tooltip's formatters (all undefined → bare default).@@ -152,12 +155,22 @@ export function Chart<Meta = unknown>({<DefaultTooltip{...ctx}valueFormatter={tooltipValueFormatter}+ labelFormatter={tooltipLabelFormatter}showTotal={tooltipShowTotal}totalLabel={tooltipTotalLabel}totalFormatter={tooltipTotalFormatter}+ sortedByValue={tooltipSortedByValue}/>)),- [renderTooltipProp, tooltipValueFormatter, tooltipShowTotal, tooltipTotalLabel, tooltipTotalFormatter]+ [+ renderTooltipProp,+ tooltipValueFormatter,+ tooltipLabelFormatter,+ tooltipShowTotal,+ tooltipTotalLabel,+ tooltipTotalFormatter,+ tooltipSortedByValue,+ ])const margins = useChartMargins({diff --git a/packages/quill/packages/charts/src/core/RadialChart.tsx b/packages/quill/packages/charts/src/core/RadialChart.tsxindex 91c7d13c5474..546412281b9e 100644--- a/packages/quill/packages/charts/src/core/RadialChart.tsx+++ b/packages/quill/packages/charts/src/core/RadialChart.tsx@@ -60,7 +60,7 @@ export function RadialChart<Meta = unknown>({buildLayout,drawStatic,drawHover,- tooltip: renderTooltip = DefaultTooltip,+ tooltip: renderTooltipProp,showTooltip = true,onSliceClick,hitOuterSlack = 0,@@ -73,6 +73,13 @@ export function RadialChart<Meta = unknown>({margins: RADIAL_MARGINS,})+ // Wrap DefaultTooltip in a JSX render function so its hooks run inside its own component+ // tree — calling it as a plain function would violate rules-of-hooks.+ const renderTooltip = useMemo<(ctx: TooltipContext<Meta>) => React.ReactNode>(+ () => renderTooltipProp ?? ((ctx: TooltipContext<Meta>) => <DefaultTooltip {...ctx} />),+ [renderTooltipProp]+ )+const coloredSeries = useColoredSeries<Meta>(series, theme)const layout = useMemo(() => {diff --git a/packages/quill/packages/charts/src/core/interaction.ts b/packages/quill/packages/charts/src/core/interaction.tsindex 4f3c6ac808e6..471c2613a546 100644--- a/packages/quill/packages/charts/src/core/interaction.ts+++ b/packages/quill/packages/charts/src/core/interaction.ts@@ -127,17 +127,22 @@ export function buildTooltipContext<Meta = unknown>(// A gap (`data[i]` non-finite) draws no point/bar, so don't fabricate a `0` row for it —// skip it the same way the renderer does.const rawValue = s.data[dataIndex]+ const seriesValueScale = yAxes?.[s.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? yScale+ const px = seriesValueScale(resolvePositionValue(s, dataIndex))+ if (isFinite(px)) {+ valuePixels.push(px)+ }if (s.visibility?.tooltip !== false && rawValue != null && isFinite(rawValue)) {// A per-bar series carries each bar's identity in `bars[i]` — surface it so the tooltip// reads the right color/meta/label rather than the shared series-level ones.const bar = s.bars?.[dataIndex]const entrySeries = bar ? { ...s, meta: bar.meta ?? s.meta, label: bar.label ?? s.label } : s- seriesData.push({ series: entrySeries, value: resolveValue(s, dataIndex), color: barColorAt(s, dataIndex) })- }- const seriesValueScale = yAxes?.[s.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? yScale- const px = seriesValueScale(resolvePositionValue(s, dataIndex))- if (isFinite(px)) {- valuePixels.push(px)+ seriesData.push({+ series: entrySeries,+ value: resolveValue(s, dataIndex),+ color: barColorAt(s, dataIndex),+ yPixel: isFinite(px) ? px : undefined,+ })}}diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex da4936726f78..3902b0fc75d7 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -149,6 +149,8 @@ export interface TooltipContext<Meta = unknown> {value: numbercolor: stringfraction?: number+ /** Canvas y-pixel of this series at the hovered x — used for cursor-proximity sorting. */+ yPixel?: number}[]/** Pixel position (relative to the chart container) for anchoring the tooltip.* `width` (optional) is the horizontal data-extent centered on `x` — bar charts@@ -302,9 +304,14 @@ export interface TooltipConfig {// DefaultTooltipProps for semantics — these mirror it./** Second arg is the row's `seriesData` entry, for per-series formatting. */valueFormatter?: (value: number, entry: TooltipContext['seriesData'][number]) => string+ /** Transforms the raw x-axis label before showing it in the tooltip header — use to convert+ * ISO datetime strings to human-readable dates. */+ labelFormatter?: (label: string) => stringshowTotal?: booleantotalLabel?: stringtotalFormatter?: (value: number) => string+ /** Sort series rows by value descending so the highest value appears at the top. */+ sortedByValue?: boolean}/** How the value axis domain is determined (y for vertical/line/area charts, x for horizontaldiff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsxindex 9956cbe51d6d..e9659d2b1bbd 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx@@ -73,13 +73,13 @@ describe('DefaultTooltip', () => {it('sums the visible series and labels the row', () => {renderTooltip({ showTotal: true }, TWO_SERIES)- screen.getByText('Total:')+ screen.getByText('Total')screen.getByText((35).toLocaleString())})it('uses a custom label and total formatter', () => {renderTooltip({ showTotal: true, totalLabel: 'Sum', totalFormatter: (v) => `$${v}` }, TWO_SERIES)- screen.getByText('Sum:')+ screen.getByText('Sum')screen.getByText('$35')})@@ -106,12 +106,12 @@ describe('DefaultTooltip', () => {it('is suppressed for a single series', () => {renderTooltip({ showTotal: true }, SERIES_DATA)- expect(screen.queryByText('Total:')).toBeNull()+ expect(screen.queryByText('Total')).toBeNull()})it('is suppressed when showTotal is not set', () => {renderTooltip({}, TWO_SERIES)- expect(screen.queryByText('Total:')).toBeNull()+ expect(screen.queryByText('Total')).toBeNull()})it('excludes overlay series from the sum and the summable count', () => {@@ -130,7 +130,7 @@ describe('DefaultTooltip', () => {{ series: { key: 'goal', label: 'Goal', data: [], overlay: true }, value: 30, color: '#222' },]renderTooltip({ showTotal: true }, oneRealOneOverlay)- expect(screen.queryByText('Total:')).toBeNull()+ expect(screen.queryByText('Total')).toBeNull()})})diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsxindex 6ef158258e37..935e6249335c 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx@@ -1,14 +1,23 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import type { TooltipContext } from '../core/types'import { TooltipSurface, TooltipSwatch } from './TooltipSurface'+import { findClosestSeriesKey } from './tooltipUtils'type SeriesDatum<Meta> = TooltipContext<Meta>['seriesData'][number]+// Cap the scroll area to roughly 10 rows before scrolling kicks in.+const ROWS_MAX_HEIGHT = '14rem'+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+ /** 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/** 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. */@@ -18,44 +27,126 @@ 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) => string+ /** Sort series rows by value descending so the highest value appears at the top. */+ sortedByValue?: boolean+ /** Extra content rendered below all rows and the total, separated by a divider. */+ footer?: React.ReactNode}export function DefaultTooltip<Meta = unknown>({label,seriesData,+ hoverPosition,valueFormatter,+ labelFormatter,showTotal,totalLabel = 'Total',totalFormatter,+ sortedByValue,+ footer,}: DefaultTooltipProps<Meta>): React.ReactElement {const format = valueFormatter ?? ((value: number): string => value.toLocaleString())- const summable = seriesData.filter((s) => !s.series.overlay)+ const rows = sortedByValue ? [...seriesData].sort((a, b) => b.value - a.value) : seriesData+ const summable = rows.filter((s) => !s.series.overlay)+ const closestKey = hoverPosition != null ? findClosestSeriesKey(rows, hoverPosition.y) : nullconst renderTotal = showTotal && summable.length > 1const total = summable.reduce((acc, s) => acc + s.value, 0)const formatTotal = totalFormatter ?? ((value: number): string => format(value, summable[0]))+ const scrollContainerRef = useRef<HTMLDivElement>(null)+ const [canScrollUp, setCanScrollUp] = useState(false)+ const [canScrollDown, setCanScrollDown] = useState(false)++ const updateScrollFades = useCallback(() => {+ const el = scrollContainerRef.current+ if (!el) {+ return+ }+ setCanScrollUp(el.scrollTop > 0)+ setCanScrollDown(el.scrollTop + el.clientHeight < el.scrollHeight - 1)+ }, [])++ useEffect(() => {+ updateScrollFades()+ }, [rows, updateScrollFades])++ useEffect(() => {+ if (!closestKey || !scrollContainerRef.current) {+ return+ }+ const container = scrollContainerRef.current+ const el = container.querySelector('[data-closest="true"]') as HTMLElement | null+ 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+ }+ }, [closestKey])++ const maskImage = (() => {+ if (canScrollUp && canScrollDown) {+ return 'linear-gradient(to bottom, transparent, black 20%, black 80%, transparent)'+ }+ if (canScrollUp) {+ return 'linear-gradient(to bottom, transparent, black 20%)'+ }+ if (canScrollDown) {+ return 'linear-gradient(to bottom, black 80%, transparent)'+ }+ return undefined+ })()return (<TooltipSurface>- <div data-attr="hog-chart-tooltip-label" className="font-semibold mb-1">- {label}+ <div data-attr="hog-chart-tooltip-label" className="font-semibold mb-1 opacity-60">+ {labelFormatter ? labelFormatter(label) : label}+ </div>+ <div+ ref={scrollContainerRef}+ onScroll={updateScrollFades}+ style={{+ maxHeight: ROWS_MAX_HEIGHT,+ overflowY: 'auto',+ scrollbarWidth: 'none',+ maskImage,+ WebkitMaskImage: maskImage,+ }}+ >+ {rows.map((s) => {+ const isClosest = s.series.key === closestKey+ 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' : ''}`}+ >+ <TooltipSwatch color={s.color} />+ <span data-attr="hog-chart-tooltip-series" className="flex-1 min-w-0 truncate">+ {s.series.label}+ </span>+ <strong data-attr="hog-chart-tooltip-value">{format(s.value, s)}</strong>+ </div>+ )+ })}</div>- {seriesData.map((s) => (- <div key={s.series.key} data-attr="hog-chart-tooltip-row" className="flex items-center gap-2">- <TooltipSwatch color={s.color} />- <span data-attr="hog-chart-tooltip-series">{s.series.label}:</span>- <strong data-attr="hog-chart-tooltip-value">{format(s.value, s)}</strong>- </div>- ))}{renderTotal && (<divdata-attr="hog-chart-tooltip-total"- className="flex items-center gap-2 mt-1 pt-1 border-t border-current/25 font-semibold"+ className="flex items-center gap-2 mt-2 pt-1 border-t border-current/25">- <span className="w-2" />- <span>{totalLabel}:</span>+ <span className="flex-1 opacity-60">{totalLabel}</span><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>}</TooltipSurface>)}diff --git a/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx b/packages/quill/packages/charts/src/overlays/TooltipSurface.tsxindex 8ffee9008012..102ccc8a893e 100644--- a/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx+++ b/packages/quill/packages/charts/src/overlays/TooltipSurface.tsx@@ -35,7 +35,8 @@ export function TooltipSurface({borderRadius: 'var(--radius-sm, 0.375rem)',// Soft float shadow for separation over dense chart data — the// one intentional addition over quill's flat in-page tooltip.- boxShadow: '0 2px 8px rgb(0 0 0 / 18%)',+ border: '1px solid rgba(255, 255, 255, 0.1)',+ boxShadow: '0 4px 16px rgb(0 0 0 / 40%)',backgroundColor: theme.tooltipBackground ?? TOOLTIP_FALLBACK_BG,color: theme.tooltipColor ?? TOOLTIP_FALLBACK_COLOR,}}diff --git a/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts b/packages/quill/packages/charts/src/overlays/tooltipUtils.test.tsnew file mode 100644index 000000000000..8f7ddb77b8ee--- /dev/null+++ b/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts@@ -0,0 +1,32 @@+import { findClosestSeriesKey } from './tooltipUtils'++const row = (key: string, yPixel?: number): { series: { key: string }; yPixel?: number } => ({+ series: { key },+ yPixel,+})++describe('findClosestSeriesKey', () => {+ it('returns null when no entry has yPixel', () => {+ expect(findClosestSeriesKey([row('a'), row('b')], 100)).toBeNull()+ })++ it('returns the key of the closest series', () => {+ expect(findClosestSeriesKey([row('a', 50), row('b', 200), row('c', 110)], 100)).toBe('c')+ })++ it('handles a single series', () => {+ expect(findClosestSeriesKey([row('x', 300)], 100)).toBe('x')+ })++ it('skips entries without yPixel', () => {+ expect(findClosestSeriesKey([row('a'), row('b', 50), row('c')], 200)).toBe('b')+ })++ it('returns null for an empty array', () => {+ expect(findClosestSeriesKey([], 100)).toBeNull()+ })++ it('prefers the first entry when distances are equal', () => {+ expect(findClosestSeriesKey([row('a', 80), row('b', 120)], 100)).toBe('a')+ })+})diff --git a/packages/quill/packages/charts/src/overlays/tooltipUtils.ts b/packages/quill/packages/charts/src/overlays/tooltipUtils.tsnew file mode 100644index 000000000000..82fb6259c04e--- /dev/null+++ b/packages/quill/packages/charts/src/overlays/tooltipUtils.ts@@ -0,0 +1,20 @@+/** Returns the key of the series whose canvas y-pixel is closest to `cursorY`.+ * Returns `null` when no entry carries `yPixel` data. */+export function findClosestSeriesKey(+ rows: Array<{ series: { key: string }; yPixel?: number }>,+ cursorY: number+): string | null {+ let bestKey: string | null = null+ let bestDist = Infinity+ for (const s of rows) {+ if (s.yPixel == null) {+ continue+ }+ const dist = Math.abs(s.yPixel - cursorY)+ if (dist < bestDist) {+ bestDist = dist+ bestKey = s.series.key+ }+ }+ return bestKey+}diff --git a/packages/quill/packages/charts/src/testing/render.ts b/packages/quill/packages/charts/src/testing/render.tsxsimilarity index 95%rename from packages/quill/packages/charts/src/testing/render.tsrename to packages/quill/packages/charts/src/testing/render.tsxindex 344e0897e324..d073ebd7c32c 100644--- a/packages/quill/packages/charts/src/testing/render.ts+++ b/packages/quill/packages/charts/src/testing/render.tsx@@ -38,7 +38,7 @@ export function renderHogChart<Meta = unknown>(const userTooltip = props.tooltipconst captureTooltip = (ctx: TooltipContext<Meta>): ReactNode => {lastTooltipContext = ctx- return userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx as TooltipContext)+ return userTooltip ? userTooltip(ctx) : <DefaultTooltip {...(ctx as TooltipContext)} />}toRender = React.cloneElement(ui, { tooltip: captureTooltip })}