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(insights): date the comparison period row in the insight tooltip (#83575)

Daniel Parker1e0da175ed7c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 148fca7d3856..6d68b5bc61c0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2672,22 +2672,30 @@ snapshots:
hash: v1.k794b7964.51c09169b5a57e217572bc35c0882b15252b4af936921569bf8d2a1d3a330f2f.red8aW6nElMIxDUdAHhilR3Ls2NgRChoEmFzfpGcgbU
insights-funneltrendstable--default--light:
hash: v1.k794b7964.f4486460f4481d343ecf8e0890d94f8d4c3da70164008d53bc762b6900623bc1.MRfTllR3ODYt6mNxjI-nTmfYZk0V2cXLMRmUwbKFC1Q
+ insights-insightseriestooltip--compare-to-previous-period--dark:
+ hash: v1.k794b7964.c678377bbf5032ac7eecc97fa759c8fc9e3c06b57ba16689210c912536a2db4e.gpyupEpCOehnsZYtAShrMscqqGEa5IzBVy3Zvin1AxY
+ insights-insightseriestooltip--compare-to-previous-period--light:
+ hash: v1.k794b7964.fe66a9a81d1cfad2b31e17932f0aaa5951e386c66d15a2f72a3a06556aaeeaf1.-mMZ0ZBqw02XLGxkjNIzt9jbvc-CYe_lJP-seoien7w
+ insights-insightseriestooltip--compare-to-previous-period-with-breakdown--dark:
+ hash: v1.k794b7964.70573eaefe2caf1df8e9df7d06bcb0a5bfd792e111d6b27baa0a071db8c73dac.i8G5xtKkXf_02jXPVkKMZmd4prvg1wun6DRxKsWKsAk
+ insights-insightseriestooltip--compare-to-previous-period-with-breakdown--light:
+ hash: v1.k794b7964.df3fc154dd774f23fb6c1e34ca61e15362ccdabc2cb1bd49773a924554ce4fd7.wK9NCJZpxlmZdvFUBEoWqe2_wY1Q89SlLMyujbJ3EMY
insights-insightseriestooltip--long-series-name-with-breakdown--dark:
- hash: v1.k794b7964.199545e36ed0533f2e52b4e8a88497c4f3587208a61eb2bade6f19e09e6acb09.chYT5gr5mJZO2rmHIGW03J--hW6-dcHe9-3SSmlvfGc
+ hash: v1.k794b7964.02efe0c272601d88771f746200a6ba7c0eafe4b4e5591b45a61da060b1da69bc.6YQtVQfdlEayGDy6dKw0Ek4vzGE5NexySwKlQd93Tqg
insights-insightseriestooltip--long-series-name-with-breakdown--light:
- hash: v1.k794b7964.7458a50ee4ac7fc39850215d33661ce955b9668aac29b58741f7972dfe97e02c.lNsTCNe5pr3yPPDVrpuuCvM02RTOqkomfXzb9jWJVdQ
+ hash: v1.k794b7964.add03affe5e904b0e7e25dc02a64a2c4b5e8675a6fd248092c3c4f9ccd017270.v3DqkDMCZGO1wL2qcw9019f4gps6WY9qPwRe0SH7RZs
insights-insightseriestooltip--multiple-formulas-with-breakdown--dark:
- hash: v1.k794b7964.c2c1e9d12c2e6c27ebecdd94aaa799f9b49fd5b0f0b9e86c3ab126cab2b8ab3a.Mp3xiWvz6KnRuqNh4R3aBrrtVMdG-q0tTMyPvM4g35U
+ hash: v1.k794b7964.f03e00bd77e4d765859443dbbddaa1618b4076b61bc8c63889f3bb99a739a5cf.P42JfB5eDUppR3yGx6Ccd6hYnE77Lx5sp5T82YhM0eE
insights-insightseriestooltip--multiple-formulas-with-breakdown--light:
- hash: v1.k794b7964.d8f1d85a326c2fa64b2474d747f6c2fc55a04837d4047e51f7be8081f01a728a.Q9OOrfePNmj_B2IgRrjI3EQqdrLjhktX66EcbKWtUjQ
+ hash: v1.k794b7964.970aa26fe9da77660c5bc38f9213cbd05cfb1795215334d134ebe41becb41b5d.r3t_NY_Li8xMbv7IeXx522a7eMsPVJ0L7mTt_HSxozc
insights-insightseriestooltip--multiple-series-with-breakdown--dark:
- hash: v1.k794b7964.fefcda3546cc3585fa2ee3e78cbd5e7e8911e0a186ef2d3a55524a1bd9a87dbf.XTaPSGWvLckMkkdXiOnce0cwQ9EomWkVNulkQRz015s
+ hash: v1.k794b7964.5bfa549f548aa3568e46c0887ec1c25f993424a01d18d2a6c71e590188d7caa9.Q9ge6rM1Ga2_yDhVyt6lmUiIZO47K_Vd59aJtMp80T4
insights-insightseriestooltip--multiple-series-with-breakdown--light:
- hash: v1.k794b7964.aab48f4950e5ed1da0ef48e75ad65d754aaecd0527b1779980ae997958dd56f2.7ogPLJVbfRr0y0iw4HkXOZMv2jeP2rDLkWxp7aU_HX4
+ hash: v1.k794b7964.30ae3fc7ed9ff096ac81d00301b82566ff20e97352d543c2031b18cf5906f103.6QForav35AQFQD35zPNU7WTPEPk4jtP7UJdcw3XGyEs
insights-insightseriestooltip--same-event-series-with-breakdown--dark:
- hash: v1.k794b7964.15149b5a1d8ab596d36e7f1cbee6dd09df7d10ee68e31d61ed076266284ddeac.PA8cjf-p-D6gZR4_AoVC8S6kzs_hYF22Js66P8oAZnQ
+ hash: v1.k794b7964.8c5f1be7bda1d9688273349c73512afa7e1a7492245abd6f8f7d4c7f5cd8f3aa.f-Vpg6pjAL8o2lcVOlLw_5m7-RvNgHTlBkryFqeZ-8c
insights-insightseriestooltip--same-event-series-with-breakdown--light:
- hash: v1.k794b7964.7fbc4c70dcfb77807cd72d37140eff2468055091f79f04e7ea8bf201aee2dd25.oNUrG_LVzG8BURRQZdldu7oMzL9dyPcIPMUMx2f6f9k
+ hash: v1.k794b7964.6789c8ff57d974d5ca5d972f8c34a598eda20aaae36fe4c126a35d63bae682e5.XOC_sSq1rzYzWDr1OD8A6re6ebgFp251tmRjYNpHaaQ
insights-insightstable--aggregation--dark:
hash: v1.k794b7964.531d5fdec5bc837da5dd1f334b850e6321fde25a7fb70834856ae88338214e28.RVObUcwlwFdjIrk0GTbySMzPeAWR7zUyPLsUtdIu57w
insights-insightstable--aggregation--light:
@@ -5401,9 +5409,9 @@ snapshots:
replay-tabs-home-success--recordings-play-list-no-pinned-recordings--light:
hash: v1.k794b7964.53967579ef53f411c9adc668e0e8b832b0fbb8fb1f346e55fff866d861d0566a.N3xzqevtEf7EogtcsQXhd04fINxfV0MejZn-DsAhQws
replay-tabs-home-success--second-recording-in-list--dark:
- hash: v1.k794b7964.e55e3f17536c13f7561cd6275dc2c63e9950e7f83394de972364ba0b51211c58.S9fUa5v1eSxXT-D7D7lmS3os0kSj8a1gIhb7EPsivNc
+ hash: v1.k794b7964.2ba8b5789dc4e6732085d5c3e9b4434011dfd0f50c9b9bf20101273d65e6ee7d.vbjff-vvIJ5OC55myq8StIReDxV12WsR2hkQyMFeHmk
replay-tabs-home-success--second-recording-in-list--light:
- hash: v1.k794b7964.db9df524befb2d2b1f9115318d2a4ddc5cd5009ef1e38100a7511011634114b8.wlpOrqbKlF47Bul9gFvQ2fuD9OXN-TopZSNFM3Z7K2I
+ hash: v1.k794b7964.3a8372e58168132be7cc904fd0b41f6758930206eb5c51fb50f3a067f19398fc.HToJJ6kF0cytmkWxhkwCEtjSN0YxsJV7p8OtC9qShv0
scenes-app-ai-observability-clustercard--default--dark:
hash: v1.k794b7964.745c8ac41b251f329b890d56d7b07fb31b4939a440a40eea7932f1081d3de702.ESnQVAOfySBfRJWfJsURYu-prgU3EUvQZCD62MyLlX4
scenes-app-ai-observability-clustercard--default--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 339398ea4672..6f27c2336ad3 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -83,7 +83,7 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`) compose as children.
- `HighlightedRange` draws a translucent box spanning an x-axis range — pass `start`/`end` as data indices or labels (e.g. straight from `onDateRangeZoom`'s `startIndex`/`endIndex`). Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart. On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point. `color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border); it clamps to the plot area and renders null when an endpoint doesn't resolve.
-- `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"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `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) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) 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. Pinned tooltips are copy-friendly: outside-dismissal keys off where the press _started_ (pointer-down outside the tooltip/chart, or Escape), so a text-selection drag that releases outside the tooltip doesn't dismiss it, and a click that completes a text selection inside a row doesn't fire `onRowClick`.
+- `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"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `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) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) 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. Rows share one grid (swatch, label, value), so the value column is as wide as the widest value and every row's label ends at the same x — a `labelRenderer` that pushes part of its label right (e.g. a date) lines up as a column down the tooltip. Pinned tooltips are copy-friendly: outside-dismissal keys off where the press _started_ (pointer-down outside the tooltip/chart, or Escape), so a text-selection drag that releases outside the tooltip doesn't dismiss it, and a click that completes a text selection inside a row doesn't fire `onRowClick`.
- A custom `tooltip` render prop builds its panel from the exported tooltip pieces: `TooltipSurface` (the floating panel), `TooltipSwatch` (series-color dot), and `TooltipFooter` (divider + muted row for a "click to inspect" hint — the same slot `DefaultTooltip`'s `footer` renders into, so a bespoke tooltip's hint stays styled like the built-in one).
- Touch devices are tap-driven (cartesian charts): a tap on a data point reveals its tooltip — pinned when `config.tooltip.pinnable`, so its rows are tappable for `onRowClick` drill-downs — a tap on a different point moves it there, and a tap on the point whose tooltip is already showing runs the click action (dismiss a pinned tooltip; fire `onPointClick` on non-pinnable charts). Tapping outside the chart, scrolling, or Escape dismisses. Mouse hover/click behavior is unchanged; the split lives in `useChartInteraction`, keyed off the pointerdown's `pointerType`.
- BarChart sets `TooltipContext.hoveredSeriesKey` — the key of the bar/segment under the cursor (stacked: the visible segment; grouped: the band-slot hit). Stacked `seriesData` keeps every segment in declaration order, so a custom tooltip that describes a single segment (e.g. a funnel breakdown) must select by `hoveredSeriesKey`, not `seriesData[0]`. It may reference a series hidden from `seriesData` via `visibility.tooltip: false` (e.g. a drop-off filler), and is `undefined` on other chart types and pinned rebuilds without a cursor.
diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
index 663b8c86d5f8..7fc010afb6d8 100644
--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx
@@ -144,6 +144,9 @@ export function DefaultTooltip<Meta = unknown>({
<div
ref={scrollContainerRef}
onScroll={updateScrollFades}
+ // One grid for all rows, with each row subgridded onto it, so the value column is
+ // as wide as the widest value and every row's label ends at the same x.
+ className="grid grid-cols-[auto_minmax(0,1fr)_auto]"
style={{
maxHeight: ROWS_MAX_HEIGHT,
overflowY: 'auto',
@@ -162,7 +165,7 @@ export function DefaultTooltip<Meta = unknown>({
key={s.series.key}
data-attr="hog-chart-tooltip-row"
data-closest={isClosest ? 'true' : undefined}
- 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}`}
+ className={`grid grid-cols-subgrid col-span-3 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
? () => {
@@ -179,7 +182,7 @@ export function DefaultTooltip<Meta = unknown>({
<TooltipSwatch color={s.color} />
{/* 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="min-w-0 overflow-hidden grid">
<span className="font-semibold invisible truncate [grid-area:1/1]" aria-hidden="true">
{labelContent}
</span>
@@ -187,7 +190,7 @@ export function DefaultTooltip<Meta = unknown>({
{labelContent}
</span>
</span>
- <strong data-attr="hog-chart-tooltip-value" className="tabular-nums">
+ <strong data-attr="hog-chart-tooltip-value" className="tabular-nums justify-self-end">
{format(s.value, s)}
</strong>
</div>
diff --git a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx
index d4380c796d3f..053b4e080d0e 100644
--- a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx
+++ b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx
@@ -6,11 +6,13 @@ import { Stage, playHoverAtFraction } from '@posthog/quill-charts/story-helpers'
import { useChartTheme } from 'lib/charts/hooks'
import type { BreakdownFilter } from '~/queries/schema/schema-general'
+import { CompareLabelType } from '~/types'
import type { TrendsSeriesMeta } from '../trends/shared/trendsSeriesMeta'
import { InsightSeriesTooltip } from './InsightSeriesTooltip'
const DAYS = ['2024-06-10', '2024-06-11', '2024-06-12', '2024-06-13', '2024-06-14']
+const PREVIOUS_DAYS = ['2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06', '2024-06-07']
const BOOLEAN_BREAKDOWN_FILTER: BreakdownFilter = { breakdown: 'is_subscribed', breakdown_type: 'event' }
@@ -22,7 +24,10 @@ interface FixtureSeries {
/** Formula label carried as `series_name` for rows without an event. */
seriesName?: string
seriesOrder: number
- breakdown_value: string
+ breakdown_value?: string
+ compareLabel?: CompareLabelType
+ /** This series' own period. A previous-period series covers earlier dates than the chart's. */
+ days?: string[]
}
function buildSeries(fixtures: FixtureSeries[]): {
@@ -39,7 +44,8 @@ function buildSeries(fixtures: FixtureSeries[]): {
action: f.event ? { id: f.event, name: f.event, type: 'events', order: f.seriesOrder } : undefined,
series_name: f.seriesName,
breakdown_value: f.breakdown_value,
- days: DAYS,
+ compare_label: f.compareLabel,
+ days: f.days ?? DAYS,
order: f.seriesOrder,
},
}))
@@ -147,6 +153,77 @@ export const SameEventSeriesWithBreakdown: Story = {
play: async ({ canvasElement }) => await playHoverAtFraction(canvasElement, 0.5),
}
+// The previous row is dated; the current row's date is the header above it.
+export const CompareToPreviousPeriod: Story = {
+ render: () => (
+ <TooltipChart
+ fixtures={[
+ {
+ label: '$pageview',
+ data: [45, 82, 134, 210, 95],
+ event: '$pageview',
+ seriesOrder: 0,
+ compareLabel: CompareLabelType.Current,
+ },
+ {
+ label: '$pageview',
+ data: [30, 64, 100, 155, 71],
+ event: '$pageview',
+ seriesOrder: 0,
+ compareLabel: CompareLabelType.Previous,
+ days: PREVIOUS_DAYS,
+ },
+ ]}
+ />
+ ),
+ play: async ({ canvasElement }) => await playHoverAtFraction(canvasElement, 0.5),
+}
+
+// Compare with a breakdown: the date competes with the breakdown value for row width.
+export const CompareToPreviousPeriodWithBreakdown: Story = {
+ render: () => (
+ <TooltipChart
+ fixtures={[
+ {
+ label: 'true',
+ data: [45, 82, 134, 210, 95],
+ event: '$pageview',
+ seriesOrder: 0,
+ breakdown_value: 'true',
+ compareLabel: CompareLabelType.Current,
+ },
+ {
+ label: 'false',
+ data: [20, 31, 46, 70, 38],
+ event: '$pageview',
+ seriesOrder: 0,
+ breakdown_value: 'false',
+ compareLabel: CompareLabelType.Current,
+ },
+ {
+ label: 'true',
+ data: [8, 15, 22, 34, 17],
+ event: '$pageview',
+ seriesOrder: 0,
+ breakdown_value: 'true',
+ compareLabel: CompareLabelType.Previous,
+ days: PREVIOUS_DAYS,
+ },
+ {
+ label: 'false',
+ data: [5, 9, 12, 19, 10],
+ event: '$pageview',
+ seriesOrder: 0,
+ breakdown_value: 'false',
+ compareLabel: CompareLabelType.Previous,
+ days: PREVIOUS_DAYS,
+ },
+ ]}
+ />
+ ),
+ play: async ({ canvasElement }) => await playHoverAtFraction(canvasElement, 0.5),
+}
+
// A long event name doesn't fit beside the breakdown value at the tooltip's max width.
// The name truncates and the breakdown value stays readable, not the other way round.
export const LongSeriesNameWithBreakdown: Story = {
diff --git a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx
index 29c0480a2acf..f0eb7617a7c4 100644
--- a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx
+++ b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx
@@ -9,6 +9,7 @@ import { percentage } from 'lib/utils/numbers'
import { alphabet } from 'lib/utils/strings'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import {
+ FormattedDateOptions,
getDatumTitle,
getFormattedDate,
getTooltipTitle,
@@ -19,7 +20,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { BreakdownFilter, CurrencyCode, DateRange, TrendsFilter } from '~/queries/schema/schema-general'
-import { ActionFilter, IntervalType } from '~/types'
+import { ActionFilter, CompareLabelType, IntervalType } from '~/types'
// ── Types ──────────────────────────────────────────────────────────────────
@@ -91,6 +92,16 @@ function formatRowValue(
return formatAggregationAxisValue(opts.trendsFilter, value, opts.baseCurrency)
}
+/** Spells out the weekday on daily buckets, matching the classic insight tooltip. */
+function formatHeaderDate(date: string | undefined, options: FormattedDateOptions): string {
+ const formattedDate = getFormattedDate(date, options)
+ if (options.interval !== 'day' || typeof date !== 'string') {
+ return formattedDate
+ }
+ const parsed = parseDateInTimezone(date, options.timezone ?? 'UTC')
+ return parsed.isValid() ? `${parsed.format('dddd')}, ${formattedDate}` : formattedDate
+}
+
// ── SeriesLabel ────────────────────────────────────────────────────────────
/** How rows must identify the series they belong to:
@@ -108,6 +119,8 @@ interface SeriesLabelProps {
datum: TooltipSeriesDatum
breakdownFilter?: BreakdownFilter
formatCompareLabel?: (label: string, dateLabel?: string) => string
+ /** The row's own bucket date, or "Current"/"Previous". Null when not comparing periods. */
+ periodLabel: string | null
seriesIdentification: SeriesIdentification
renderSeriesOverride?: (datum: SeriesDatum) => React.ReactNode
}
@@ -123,6 +136,7 @@ export function SeriesLabel({
datum,
breakdownFilter,
formatCompareLabel,
+ periodLabel,
seriesIdentification,
renderSeriesOverride,
}: SeriesLabelProps): React.ReactNode {
@@ -160,14 +174,6 @@ export function SeriesLabel({
)
}
- const comparePeriod = datum.compare_label
- ? formatCompareLabel
- ? formatCompareLabel(String(datum.compare_label), datum.date_label)
- : datum.compare_label === 'current'
- ? 'Current'
- : 'Previous'
- : null
-
const breakdownTitle = hasBreakdown
? getDatumTitle({ ...datum, compare_label: undefined }, breakdownFilter, formatCompareLabel)
: null
@@ -186,17 +192,19 @@ export function SeriesLabel({
</>
) : null
+ // The period label sits at the row's right edge so the dates line up as a column down the
+ // tooltip rather than trailing labels of different lengths.
// Three levels of priority, in order: the period label never shrinks, the breakdown value
// shrinks only once the row runs out of name, and the name absorbs everything before that.
- // The breakdown and the period share a shrink-0 group so shrinking is sequential — a group
+ // The name and the breakdown share a growing group so shrinking is sequential — a group
// that shrinks proportionally costs a short value two characters to the ellipsis.
return (
<span className="inline-flex items-center w-full overflow-hidden">
- {seriesPrefix}
- <span className="inline-flex items-center min-w-0 shrink-0 max-w-full">
- <span className="truncate min-w-0 shrink">{breakdownTitle ?? datum.label}</span>
- {comparePeriod && <span className="shrink-0 opacity-60">&nbsp;·&nbsp;{comparePeriod}</span>}
+ <span className="inline-flex items-center min-w-0 flex-1 overflow-hidden">
+ {seriesPrefix}
+ <span className="truncate min-w-0 shrink-0 max-w-full">{breakdownTitle ?? datum.label}</span>
</span>
+ {periodLabel && <span className="shrink-0 opacity-60 pl-2">{periodLabel}</span>}
</span>
)
}
@@ -274,6 +282,56 @@ export function InsightSeriesTooltip<Meta extends InsightSeriesMetaBase>({
return new Set(nameByEntity.values()).size < nameByEntity.size ? 'letter-and-name' : 'name'
}, [datumByKey])
+ const compareDates = useMemo((): Partial<Record<CompareLabelType, string>> => {
+ const dates: Partial<Record<CompareLabelType, string>> = {}
+ for (const datum of datumByKey.values()) {
+ const label = datum.compare_label
+ if (label === CompareLabelType.Current || label === CompareLabelType.Previous) {
+ dates[label] ??= datum.date_label
+ }
+ }
+ return dates
+ }, [datumByKey])
+
+ const comparePeriodsShareAYear = useMemo((): boolean => {
+ const current = compareDates[CompareLabelType.Current]
+ const previous = compareDates[CompareLabelType.Previous]
+ if (!current || !previous) {
+ return true
+ }
+ return parseDateInTimezone(current, timezone).year() === parseDateInTimezone(previous, timezone).year()
+ }, [compareDates, timezone])
+
+ // Only the previous row needs a date; the current row's is already the header.
+ const periodLabelOf = useCallback(
+ (datum: TooltipSeriesDatum): string | null => {
+ if (!datum.compare_label) {
+ return null
+ }
+ if (formatCompareLabel) {
+ return formatCompareLabel(String(datum.compare_label), datum.date_label)
+ }
+ if (datum.compare_label !== CompareLabelType.Previous) {
+ return 'Current'
+ }
+ // A headerless tooltip (aggregated bar, pie slice) covers the whole range rather than one
+ // bucket, and stickiness sets `altTitle` because its `date_label` counts intervals.
+ if (altTitle || showHeader === false || !datum.date_label) {
+ return 'Previous'
+ }
+ return getFormattedDate(datum.date_label, {
+ interval,
+ // No `dateRange`: it bounds the current period, so clamping a previous-period week
+ // to it would cut that week's range short.
+ timezone,
+ weekStartDay,
+ // The header carries the year already, so repeat it only across a year boundary.
+ short: comparePeriodsShareAYear,
+ })
+ },
+ [formatCompareLabel, interval, altTitle, showHeader, timezone, weekStartDay, comparePeriodsShareAYear]
+ )
+
const valueFormatter = useCallback(
(value: number, entry: InsightSeriesTooltipEntry<Meta>): React.ReactNode => {
const datum = datumByKey.get(entry.series.key)
@@ -313,30 +371,27 @@ export function InsightSeriesTooltip<Meta extends InsightSeriesMetaBase>({
datum={datum}
breakdownFilter={breakdownFilter}
formatCompareLabel={formatCompareLabel}
+ periodLabel={periodLabelOf(datum)}
seriesIdentification={seriesIdentification}
renderSeriesOverride={renderSeriesOverride}
/>
)
},
- [datumByKey, breakdownFilter, formatCompareLabel, seriesIdentification, renderSeriesOverride]
+ [datumByKey, breakdownFilter, formatCompareLabel, periodLabelOf, seriesIdentification, renderSeriesOverride]
)
const labelFormatter = useCallback((): React.ReactNode => {
+ // Not `seriesData[0]`: grouped bars list the previous period first, and hiding the current
+ // series in the legend drops it.
const firstKey = context.seriesData[0]?.series.key
- const date = firstKey ? datumByKey.get(firstKey)?.date_label : undefined
- let formattedDate = getFormattedDate(date, { interval, dateRange, timezone, weekStartDay })
- // Match the classic insight tooltip, which spells out the weekday on daily buckets
- if (interval === 'day' && typeof date === 'string') {
- const parsed = parseDateInTimezone(date, timezone)
- if (parsed.isValid()) {
- formattedDate = `${parsed.format('dddd')}, ${formattedDate}`
- }
- }
+ const currentDate =
+ compareDates[CompareLabelType.Current] ?? (firstKey ? datumByKey.get(firstKey)?.date_label : undefined)
+ const formattedDate = formatHeaderDate(currentDate, { interval, dateRange, timezone, weekStartDay })
if (altTitle) {
return getTooltipTitle([...datumByKey.values()], altTitle, formattedDate) ?? formattedDate
}
return formattedDate
- }, [context.seriesData, datumByKey, interval, dateRange, timezone, weekStartDay, altTitle])
+ }, [context.seriesData, datumByKey, compareDates, interval, dateRange, timezone, weekStartDay, altTitle])
const onUnpin = context.onUnpin
const onRowClickEntry = useCallback(
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
index 1cf40a75f34a..a43f32f506df 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
@@ -165,7 +165,7 @@ describe('TrendsBarChart (ActionsBar)', () => {
}
)
- it('shows current and previous period rows in compare mode', async () => {
+ it('dates the previous period row in compare mode', async () => {
renderInsight({
query: trendsBar({ compareFilter: { compare: true } }),
})
@@ -180,7 +180,7 @@ describe('TrendsBarChart (ActionsBar)', () => {
const tooltip = await chart.hoverTooltip(2)
expect(tooltip.row('Current')).toBeTruthy()
- expect(tooltip.row('Previous')).toBeTruthy()
+ expect(tooltip.row('5 Jun')).toBeTruthy()
})
it('formats values as percentages in percent stack view', async () => {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
index 07adcff6fd61..89c7416663ed 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
@@ -186,7 +186,7 @@ describe('TrendsLineChart', () => {
expect(tooltip.row('Formula (A*2) · Spike')).toContain('6')
})
- it('shows current and previous period rows in compare mode', async () => {
+ it('dates the previous period row in compare mode', async () => {
renderInsight({
query: buildTrendsQuery({
compareFilter: { compare: true },
@@ -199,8 +199,10 @@ describe('TrendsLineChart', () => {
const tooltip = await chart.hoverTooltip(2)
+ // Index 2 is 12 Jun in the current period, so 5 Jun can only come from the previous one.
expect(tooltip.row('Current')).toContain('134')
- expect(tooltip.row('Previous')).toContain('100')
+ expect(tooltip.row('5 Jun')).toContain('100')
+ expect(tooltip.element.textContent).not.toContain('Previous')
})
it('uses context.formatCompareLabel to override Current/Previous in compare mode', async () => {