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(sql insights): per-series formatter + total row tooltip (#64683)

Sam Pennington2d1c3ae6c838
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 508dc996feca..79ba7732d774 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -580,6 +580,14 @@ snapshots:
hash: v1.k794b7964.902c9be7688a67190b37eb789707bf2189b13e6c460cef63e1070dfc17196184.gxj4XB703vlholt4Z8TC2bjHVRiWJMMwT3xap2L1Sfg
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.f84c6d590af37262d4f4fd8fbaebfb9e2492af1eb7acf3c8704ff451f4ca9c71.tTB7BDNDofqyzbfrBcZd6TNmUAeS2jNpY_txIc2UiZk
+ components-hogcharts-defaulttooltip--per-series-formatter-with-total--light:
+ hash: v1.k794b7964.8e2664634344165a186e53bfd800398abccf8f8a97323ff24ce2ac86b532ee9d.O7wLPrG3BCr55c3pCRiyhrND_NRNVjVab1zQh38BNeM
+ components-hogcharts-defaulttooltip--total-excludes-overlay--dark:
+ hash: v1.k794b7964.586cbc343561fe2ea416c4e8a15661d80f0dc0e6602c4c4505fb763a960e3fec.wnr2iqA9493GIdPtZgO3pqa1uiD9pZcM3L01W8_FZ-Q
+ components-hogcharts-defaulttooltip--total-excludes-overlay--light:
+ hash: v1.k794b7964.cf566924008a871da770d7d0a0b7a2ac6748823639d3d60ca60344770f581a2a.7s92rB7AHoeq-uQd_tSJGFVCn3cU-LQeOQVJ2qyvLWo
components-hogcharts-legend--horizontal--dark:
hash: v1.k794b7964.748c8221979ca1984c3ef06b0a2d5016e683810a2530a2b7549ff2994484d32d.WlgOW_onzflesCUfetduXiySjbl4uF8oTLxdKf4xYso
components-hogcharts-legend--horizontal--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
index 29e9b7d0b057..d258652edab0 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
@@ -1,10 +1,12 @@
import clsx from 'clsx'
+import { useCallback } from 'react'
-import { ChartLegend, TimeSeriesLineChart } from '@posthog/quill-charts'
+import { ChartLegend, DefaultTooltip, TimeSeriesLineChart, type TooltipContext } from '@posthog/quill-charts'
import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
import { LineGraphProps } from './LineGraph'
+import { SqlLineSeriesMeta, formatSqlSeriesValue } from './sqlLineGraphAdapter'
import { useSqlLineGraph } from './useSqlLineGraph'
const handleChartError = makeChartErrorHandler('sql-line-chart')
@@ -12,11 +14,27 @@ const handleChartError = makeChartErrorHandler('sql-line-chart')
/**
* SQL line/area graph rendered via @posthog/quill-charts, gated behind the
* `product-analytics-quill-sql-charts` flag (see {@link LineGraph}). Handles line, area, and goal
- * lines; everything else falls back to the legacy chart.js path. Tooltip content is quill's
- * DefaultTooltip — the rich InsightTooltip isn't bridged over yet.
+ * lines; everything else falls back to the legacy chart.js path. The tooltip is quill's
+ * DefaultTooltip extended to format each row with its column's own settings and to show a total row.
*/
export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {
const model = useSqlLineGraph(props)
+ const { chartSettings } = props
+ const totalSettings = model?.totalFormatterSettings
+
+ const showTotalRow = chartSettings.showTotalRow !== false
+
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext<SqlLineSeriesMeta>): JSX.Element => (
+ <DefaultTooltip<SqlLineSeriesMeta>
+ {...ctx}
+ valueFormatter={(value, entry) => formatSqlSeriesValue(value, entry.series.meta?.settings)}
+ showTotal={showTotalRow}
+ totalFormatter={(value) => formatSqlSeriesValue(value, totalSettings)}
+ />
+ ),
+ [showTotalRow, totalSettings]
+ )
// Keep the styled container even with no data, matching the legacy path's background shell.
return (
@@ -35,11 +53,12 @@ export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {
onItemClick={model.toggleSeries}
position="top"
>
- <TimeSeriesLineChart
+ <TimeSeriesLineChart<SqlLineSeriesMeta>
series={model.series}
labels={model.labels}
theme={model.theme}
config={model.config}
+ tooltip={renderTooltip}
onError={handleChartError}
/>
</ChartLegend>
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index dc8d0e65ce13..b42de43aacc2 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -12,6 +12,7 @@ import {
canRenderSqlLineGraph,
capYSeriesData,
exceedsMaxSeries,
+ formatSqlSeriesValue,
} from './sqlLineGraphAdapter'
const numericColumn = (name: string, dataIndex: number): AxisSeries<number | null>['column'] => ({
@@ -137,6 +138,31 @@ describe('sqlLineGraphAdapter', () => {
const [series] = buildSeries([breakdownSeries('chrome', [1])], ChartDisplayType.ActionsLineGraph)
expect(series.key).toBe('chrome')
})
+
+ it('threads each series settings through meta for the tooltip', () => {
+ const usd: AxisSeries<number | null>['settings'] = { formatting: { prefix: '$' } }
+ const [withSettings, plain] = buildSeries(
+ [ySeries('revenue', [1], usd), ySeries('count', [2])],
+ ChartDisplayType.ActionsLineGraph
+ )
+ expect(withSettings.meta).toEqual({ settings: usd })
+ expect(plain.meta).toEqual({ settings: {} })
+ })
+ })
+
+ describe('formatSqlSeriesValue', () => {
+ it.each([
+ ['currency prefix', { formatting: { prefix: '$' } }, 1200, '$1200'],
+ ['percent suffix', { formatting: { style: 'percent' as const } }, 42, '42%'],
+ ['unit suffix', { formatting: { suffix: 'ms' } }, 350, '350ms'],
+ ['no settings', undefined, 7, '7'],
+ ])('formats with %s', (_name, settings, value, expected) => {
+ expect(formatSqlSeriesValue(value, settings)).toBe(expected)
+ })
+
+ it('falls back to the raw value when formatting yields null', () => {
+ expect(formatSqlSeriesValue(NaN)).toBe('NaN')
+ })
})
describe('buildLineChartConfig', () => {
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 0849301136bb..bade4f1129c1 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -6,7 +6,7 @@ import { ChartDisplayType } from '~/types'
import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'
-import { AxisSeries, AxisSeriesSettings } from '../../dataVisualizationLogic'
+import { AxisSeries, AxisSeriesSettings, formatDataWithSettings } from '../../dataVisualizationLogic'
import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
import { LineGraphProps } from './LineGraph'
@@ -71,7 +71,13 @@ export function capYSeriesData(yData: LineGraphProps['yData']): SqlLineYSeries[]
return yData.length > MAX_SERIES ? yData.slice(0, MAX_SERIES) : yData
}
-export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDisplayType): Series[] {
+/** Per-series display settings carried into quill's `series.meta` so the tooltip can format each
+ * row with its own column's currency/duration/percent/prefix/suffix settings. */
+export interface SqlLineSeriesMeta {
+ settings?: AxisSeriesSettings
+}
+
+export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDisplayType): Series<SqlLineSeriesMeta>[] {
return yData.map((series, index) => {
const settings = series.settings
const color = settings?.display?.color
@@ -81,6 +87,7 @@ export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDis
label: getSeriesLabel(series),
// null -> NaN so quill draws a gap rather than a zero.
data: series.data.map((value) => (value == null ? NaN : value)),
+ meta: { settings },
// Only pin an explicit color; otherwise let quill assign palette colors by index.
...(color ? { color } : {}),
...(isAreaSeries(visualizationType, settings) ? { fill: { opacity: AREA_FILL_OPACITY } } : {}),
@@ -88,6 +95,11 @@ export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDis
})
}
+/** Formats a tooltip value with a column's display settings. */
+export function formatSqlSeriesValue(value: number, settings?: AxisSeriesSettings): string {
+ return String(formatDataWithSettings(value, settings) ?? value)
+}
+
interface BuildConfigArgs {
xData: AxisSeries<string>
chartSettings: ChartSettings
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
index dc40b097513e..6b4c5d0a467d 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
@@ -14,8 +14,10 @@ import { teamLogic } from 'scenes/teamLogic'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import { AxisSeriesSettings } from '../../dataVisualizationLogic'
import { LineGraphProps } from './LineGraph'
import {
+ SqlLineSeriesMeta,
buildLineChartConfig,
buildSeries,
capYSeriesData,
@@ -24,13 +26,15 @@ import {
} from './sqlLineGraphAdapter'
export interface SqlLineGraphModel {
- series: Series[]
+ series: Series<SqlLineSeriesMeta>[]
labels: string[]
theme: ChartTheme
config: TimeSeriesLineChartConfig
legendItems: LegendItem[]
hiddenKeys: string[]
toggleSeries: (key: string) => void
+ /** Settings of the first (left-axis) series — used to format the tooltip's total row. */
+ totalFormatterSettings?: AxisSeriesSettings
}
export function useSqlLineGraph({
@@ -92,5 +96,14 @@ export function useSqlLineGraph({
return null
}
- return { series, labels: xData.data, theme, config, legendItems, hiddenKeys, toggleSeries }
+ return {
+ series,
+ labels: xData.data,
+ theme,
+ config,
+ legendItems,
+ hiddenKeys,
+ toggleSeries,
+ totalFormatterSettings: ySeriesData[0]?.settings,
+ }
}
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 241685c7b050..f6179b84341d 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -66,6 +66,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`, `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.
- `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, defaultHiddenKeys, onToggleSeries }`). 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. 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/index.ts b/packages/quill/packages/charts/src/index.ts
index 8d708792f13a..64f5c5a0e583 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -107,7 +107,7 @@ export { themeFromCssVars, useChartTheme, DEFAULT_CHART_COLORS } from './core/th
export type { ThemeFromCssOptions } from './core/theme'
// Built-in tooltip (for reference or extension)
-export { DefaultTooltip } from './overlays/DefaultTooltip'
+export { DefaultTooltip, type DefaultTooltipProps } from './overlays/DefaultTooltip'
// Shared tooltip surface — reuse to build custom tooltips with the quill look
export { TooltipSurface, TooltipSwatch } from './overlays/TooltipSurface'
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsx
new file mode 100644
index 000000000000..9a7ac1dfc61c
--- /dev/null
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.stories.tsx
@@ -0,0 +1,111 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { LineChart } from '../charts/LineChart/LineChart'
+import type { LineChartConfig, Series, TooltipContext } from '../core/types'
+import { playHoverAtFraction, Stage, useReactiveTheme } from '../story-helpers'
+import { DefaultTooltip } from './DefaultTooltip'
+
+const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+const CONFIG: LineChartConfig = { showGrid: true, showCrosshair: true }
+
+interface ColumnMeta {
+ /** Suffix appended to this column's values (e.g. a currency or unit). */
+ unit: string
+}
+
+const meta: Meta = { title: 'Components/HogCharts/DefaultTooltip', parameters: { layout: 'centered' } }
+export default meta
+
+type Story = StoryObj<{}>
+
+/** Per-series formatter + total row: each row formats with its own column's unit, and the footer
+ * sums the visible (non-overlay) series. */
+export const PerSeriesFormatterWithTotal: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const series: Series<ColumnMeta>[] = [
+ {
+ key: 'revenue',
+ label: 'Revenue',
+ color: '',
+ data: [120, 180, 150, 240, 210, 300, 260],
+ meta: { unit: '$' },
+ },
+ { key: 'refunds', label: 'Refunds', color: '', data: [12, 18, 9, 24, 15, 30, 21], meta: { unit: '$' } },
+ ]
+ const renderTooltip = (ctx: TooltipContext<ColumnMeta>): React.ReactNode => (
+ <DefaultTooltip
+ {...ctx}
+ valueFormatter={(value, entry) => `${entry.series.meta?.unit ?? ''}${value.toLocaleString()}`}
+ showTotal
+ totalFormatter={(value) => `$${value.toLocaleString()}`}
+ />
+ )
+ return (
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>
+ <Stage>
+ <LineChart<ColumnMeta>
+ series={series}
+ labels={DAYS}
+ config={CONFIG}
+ theme={theme}
+ tooltip={renderTooltip}
+ />
+ </Stage>
+ </div>
+ )
+ },
+ play: async ({ canvasElement }) => {
+ await playHoverAtFraction(canvasElement, 0.5)
+ },
+}
+
+/** A goal-line overlay series is excluded from the total — only Revenue and Refunds are summed. */
+export const TotalExcludesOverlay: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const series: Series<ColumnMeta>[] = [
+ {
+ key: 'revenue',
+ label: 'Revenue',
+ color: '',
+ data: [120, 180, 150, 240, 210, 300, 260],
+ meta: { unit: '$' },
+ },
+ { key: 'refunds', label: 'Refunds', color: '', data: [12, 18, 9, 24, 15, 30, 21], meta: { unit: '$' } },
+ {
+ key: 'goal',
+ label: 'Goal',
+ color: '',
+ data: [200, 200, 200, 200, 200, 200, 200],
+ overlay: true,
+ stroke: { pattern: [6, 6] },
+ meta: { unit: '$' },
+ },
+ ]
+ const renderTooltip = (ctx: TooltipContext<ColumnMeta>): React.ReactNode => (
+ <DefaultTooltip
+ {...ctx}
+ valueFormatter={(value, entry) => `${entry.series.meta?.unit ?? ''}${value.toLocaleString()}`}
+ showTotal
+ totalFormatter={(value) => `$${value.toLocaleString()}`}
+ />
+ )
+ return (
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>
+ <Stage>
+ <LineChart<ColumnMeta>
+ series={series}
+ labels={DAYS}
+ config={CONFIG}
+ theme={theme}
+ tooltip={renderTooltip}
+ />
+ </Stage>
+ </div>
+ )
+ },
+ play: async ({ canvasElement }) => {
+ await playHoverAtFraction(canvasElement, 0.5)
+ },
+}
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
index 3632aab36061..f7e4a427ba79 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx
@@ -6,7 +6,9 @@ import { DefaultTooltip } from './DefaultTooltip'
const SCALES = { x: () => 0, y: (v: number) => v, yTicks: () => [] }
-const SERIES_DATA: TooltipContext['seriesData'] = [{ series: { key: 'a', label: 'A', data: [] }, value: 19402, color: '#000' }]
+const SERIES_DATA: TooltipContext['seriesData'] = [
+ { series: { key: 'a', label: 'A', data: [] }, value: 19402, color: '#000' },
+]
const CANVAS_BOUNDS = {
x: 0,
y: 0,
@@ -19,30 +21,112 @@ const CANVAS_BOUNDS = {
toJSON: () => ({}),
} as DOMRect
-function renderTooltip(valueFormatter?: (v: number) => string): void {
+type TooltipProps = Omit<Parameters<typeof DefaultTooltip>[0], keyof TooltipContext>
+
+function renderTooltip(props: TooltipProps = {}, seriesData: TooltipContext['seriesData'] = SERIES_DATA): void {
const ctx: TooltipContext = {
dataIndex: 0,
label: 'When',
- seriesData: SERIES_DATA,
+ seriesData,
position: { x: 0, y: 0 },
hoverPosition: null,
canvasBounds: CANVAS_BOUNDS,
isPinned: false,
}
- renderOverlayInChart(<DefaultTooltip {...ctx} valueFormatter={valueFormatter} />, makeOverlayContext(SCALES))
+ renderOverlayInChart(<DefaultTooltip {...ctx} {...props} />, makeOverlayContext(SCALES))
}
describe('DefaultTooltip', () => {
afterEach(cleanup)
- it.each([
- ['default (no formatter)', undefined, (19402).toLocaleString(), null as string | null],
- ['custom valueFormatter', (v: number) => `${v}ms`, '19402ms', (19402).toLocaleString()],
- ])('formats values with %s', (_, formatter, expected, absent) => {
- renderTooltip(formatter)
- screen.getByText(expected)
- if (absent) {
- expect(screen.queryByText(absent)).toBeNull()
- }
+ it('formats values with default (no formatter)', () => {
+ renderTooltip({})
+ screen.getByText((19402).toLocaleString())
+ })
+
+ it('formats values with custom valueFormatter', () => {
+ renderTooltip({ valueFormatter: (v: number) => `${v}ms` })
+ screen.getByText('19402ms')
+ expect(screen.queryByText((19402).toLocaleString())).toBeNull()
+ })
+
+ it('passes each row entry to valueFormatter so it can format per-series', () => {
+ const seriesData: TooltipContext['seriesData'] = [
+ { series: { key: 'usd', label: 'Revenue', data: [], meta: { unit: '$' } }, value: 12, color: '#000' },
+ { series: { key: 'pct', label: 'Rate', data: [], meta: { unit: '%' } }, value: 34, color: '#111' },
+ ]
+ renderTooltip(
+ {
+ valueFormatter: (value, entry) => `${value}${(entry.series.meta as { unit: string }).unit}`,
+ },
+ seriesData
+ )
+ screen.getByText('12$')
+ screen.getByText('34%')
+ })
+
+ describe('total row', () => {
+ const TWO_SERIES: TooltipContext['seriesData'] = [
+ { series: { key: 'a', label: 'A', data: [] }, value: 10, color: '#000' },
+ { series: { key: 'b', label: 'B', data: [] }, value: 25, color: '#111' },
+ ]
+
+ it('sums the visible series and labels the row', () => {
+ renderTooltip({ showTotal: true }, TWO_SERIES)
+ 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('$35')
+ })
+
+ it('falls back to valueFormatter for the total, applied with the first summable entry', () => {
+ const metaSeries: TooltipContext['seriesData'] = [
+ { series: { key: 'usd', label: 'Revenue', data: [], meta: { unit: '$' } }, value: 10, color: '#000' },
+ { series: { key: 'usd2', label: 'Revenue 2', data: [], meta: { unit: '€' } }, value: 25, color: '#111' },
+ ]
+ renderTooltip(
+ {
+ showTotal: true,
+ valueFormatter: (v, entry) => `${v}${(entry.series.meta as { unit: string }).unit}`,
+ },
+ metaSeries
+ )
+ // total uses summable[0]'s entry (unit '$'), not summable[1]'s ('€')
+ screen.getByText('35$')
+ expect(screen.queryByText('35€')).toBeNull()
+ })
+
+ it('is suppressed for a single series', () => {
+ renderTooltip({ showTotal: true }, SERIES_DATA)
+ expect(screen.queryByText('Total:')).toBeNull()
+ })
+
+ it('is suppressed when showTotal is not set', () => {
+ renderTooltip({}, TWO_SERIES)
+ expect(screen.queryByText('Total:')).toBeNull()
+ })
+
+ it('excludes overlay series from the sum and the summable count', () => {
+ const withOverlay: TooltipContext['seriesData'] = [
+ ...TWO_SERIES,
+ { series: { key: 'goal', label: 'Goal', data: [], overlay: true }, value: 1000, color: '#222' },
+ ]
+ renderTooltip({ showTotal: true }, withOverlay)
+ screen.getByText((35).toLocaleString())
+ expect(screen.queryByText((1035).toLocaleString())).toBeNull()
+ })
+
+ it('is suppressed when only one non-overlay series remains', () => {
+ const oneRealOneOverlay: TooltipContext['seriesData'] = [
+ { series: { key: 'a', label: 'A', data: [] }, value: 10, color: '#000' },
+ { series: { key: 'goal', label: 'Goal', data: [], overlay: true }, value: 30, color: '#222' },
+ ]
+ renderTooltip({ showTotal: true }, oneRealOneOverlay)
+ expect(screen.queryByText('Total:')).toBeNull()
+ })
})
})
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
index 365ba63fd707..f1b886d9334b 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
@@ -1,14 +1,39 @@
import type { TooltipContext } from '../core/types'
import { TooltipSurface, TooltipSwatch } from './TooltipSurface'
-interface DefaultTooltipProps extends TooltipContext {
- /** Formats each row's value. Defaults to `toLocaleString` — pass the chart's own
- * `valueFormatter` so the tooltip matches the axis/label units (e.g. durations, currency). */
- valueFormatter?: (value: number) => string
+type SeriesDatum<Meta> = TooltipContext<Meta>['seriesData'][number]
+
+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
+ /** 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. */
+ showTotal?: boolean
+ /** Label for the total row. Defaults to 'Total'. */
+ totalLabel?: string
+ /** Formats the total value. Defaults to the `valueFormatter` (applied with the first summable
+ * row's entry) or `toLocaleString`. */
+ totalFormatter?: (value: number) => string
}
-export function DefaultTooltip({ label, seriesData, valueFormatter }: DefaultTooltipProps): React.ReactElement {
+export function DefaultTooltip<Meta = unknown>({
+ label,
+ seriesData,
+ valueFormatter,
+ showTotal,
+ totalLabel = 'Total',
+ totalFormatter,
+}: DefaultTooltipProps<Meta>): React.ReactElement {
const format = valueFormatter ?? ((value: number): string => value.toLocaleString())
+ const summable = seriesData.filter((s) => !s.series.overlay)
+ 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]))
+
return (
<TooltipSurface>
<div className="font-semibold mb-1">{label}</div>
@@ -16,9 +41,16 @@ export function DefaultTooltip({ label, seriesData, valueFormatter }: DefaultToo
<div key={s.series.key} className="flex items-center gap-2">
<TooltipSwatch color={s.color} />
<span>{s.series.label}:</span>
- <strong>{format(s.value)}</strong>
+ <strong>{format(s.value, s)}</strong>
</div>
))}
+ {renderTotal && (
+ <div className="flex items-center gap-2 mt-1 pt-1 border-t border-current/25 font-semibold">
+ <span className="w-2" />
+ <span>{totalLabel}:</span>
+ <strong>{formatTotal(total)}</strong>
+ </div>
+ )}
</TooltipSurface>
)
}