: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): add InsightSeriesTooltip adapter and quill tooltip infrastructure (#67094)
Sam Penningtonef3ed322f71c
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 6eba1e7283ee..d5fcec579fda 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -415,6 +415,7 @@ export const FEATURE_FLAGS = {PRODUCT_ANALYTICS_FUNNELS_COMPARE: 'product-analytics-funnels-compare', // owner: @thmsobrmlr #team-product-analytics, gates "Compare to previous" toggle on funnel insightsPRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-eventsPRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics+ PRODUCT_ANALYTICS_INSIGHTS_TOOLTIPS: 'product-analytics-insights-tooltips', // owner: #team-product-analytics, gates the unified quill DefaultTooltip for trends/retention/stickiness insight chartsPRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_QUILL_LEGEND: 'product-analytics-quill-legend', // owner: #team-product-analytics, gates the in-chart quill legend replacing the legacy side InsightLegendPRODUCT_ANALYTICS_QUILL_SQL_CHARTS: 'product-analytics-quill-sql-charts', // owner: #team-data-tools, gates rendering DataVisualization line/area charts via @posthog/quill-chartsdiff --git a/frontend/src/test/insight-testing/interactions.ts b/frontend/src/test/insight-testing/interactions.tsindex f76b107d1ae7..446fdd26204b 100644--- a/frontend/src/test/insight-testing/interactions.ts+++ b/frontend/src/test/insight-testing/interactions.ts@@ -165,7 +165,7 @@ export const chart = {async clickTooltipRow(label: string | RegExp): Promise<void> {const tooltip = await waitForHogChartTooltip()const row = within(tooltip).getByText(label)- const clickable = row.closest('tr') ?? row+ const clickable = row.closest('[data-attr="hog-chart-tooltip-row"]') ?? row.closest('tr') ?? rowfireEvent.click(clickable)},}diff --git a/frontend/src/test/insight-testing/tooltip-helpers.ts b/frontend/src/test/insight-testing/tooltip-helpers.tsindex 57784af2dce3..03b1de524b8d 100644--- a/frontend/src/test/insight-testing/tooltip-helpers.ts+++ b/frontend/src/test/insight-testing/tooltip-helpers.ts@@ -1,26 +1,40 @@import { createHogChartTooltip, type HogChartTooltip } from '@posthog/quill-charts/testing'/** Insight-flavored tooltip accessor. Extends the generic hog-charts tooltip- * with helpers for the InsightTooltip's table layout — a header `<th>` row- * and per-series `<tr>` rows with `.datum-column` / `.datum-counts-column`- * cells. Other consumers with their own tooltip renderer should compose- * their own accessor on top of `createHogChartTooltip` the same way. */+ * with helpers for reading a per-series tooltip. Dual-mode: trends-family charts+ * render hog-charts' `DefaultTooltip` (`hog-chart-tooltip-*` rows), while funnel+ * and retention still render the legacy `InsightTooltip` table (`<th>` header,+ * `<tr>` rows with `.datum-column` / `.datum-counts-column`). The accessor reads+ * whichever is present so a single helper covers both during the migration. */export interface InsightTooltipAccessor extends HogChartTooltip {/** Header text — typically the hovered date (e.g. "Wednesday, 12 Jun (UTC)"). */title(): string- /** Value cell text for the row whose datum column contains `label`. */+ /** Value cell text for the row whose label contains `label`. */row(label: string): string | undefined- /** Ordered list of row datum labels (skips the header row). */+ /** Ordered list of row labels (skips the header). */rows(): string[]}export function createInsightTooltipAccessor(element: HTMLElement): InsightTooltipAccessor {+ const isDefaultTooltip = (): boolean => !!element.querySelector('[data-attr="hog-chart-tooltip-label"]')+ const defaultRows = (): HTMLElement[] =>+ Array.from(element.querySelectorAll<HTMLElement>('[data-attr="hog-chart-tooltip-row"]'))+return Object.assign(createHogChartTooltip(element), {title(): string {+ if (isDefaultTooltip()) {+ return element.querySelector('[data-attr="hog-chart-tooltip-label"]')?.textContent?.trim() ?? ''+ }return element.querySelector('thead th')?.textContent?.trim() ?? ''},row(label: string): string | undefined {+ if (isDefaultTooltip()) {+ const row = defaultRows().find((r) =>+ r.querySelector('[data-attr="hog-chart-tooltip-series"]')?.textContent?.includes(label)+ )+ return row?.querySelector('[data-attr="hog-chart-tooltip-value"]')?.textContent ?? undefined+ }const rows = element.querySelectorAll('tbody tr')for (let i = 0; i < rows.length; i++) {const row = rows[i]@@ -33,6 +47,11 @@ export function createInsightTooltipAccessor(element: HTMLElement): InsightToolt},rows(): string[] {+ if (isDefaultTooltip()) {+ return defaultRows()+ .map((r) => r.querySelector('[data-attr="hog-chart-tooltip-series"]')?.textContent?.trim() ?? '')+ .filter(Boolean)+ }const rows = element.querySelectorAll('tbody tr')return Array.from(rows).map((r) => r.querySelector('.datum-column')?.textContent?.trim() ?? '')diff --git a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsxnew file mode 100644index 000000000000..83b8222abb22--- /dev/null+++ b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx@@ -0,0 +1,220 @@+import { useValues } from 'kea'+import { useCallback, useMemo } from 'react'++import { DefaultTooltip, type TooltipContext } from '@posthog/quill-charts'++import { percentage } from 'lib/utils/numbers'+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'+import {+ getDatumTitle,+ getFormattedDate,+ getTooltipTitle,+ SeriesDatum,+} from 'scenes/insights/InsightTooltip/insightTooltipUtils'+import { formatAggregationValue, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+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'++type InsightSeriesMetaBase = {+ action?: ActionFilter+ breakdown_value?: string | number | string[] | null+ compare_label?: SeriesDatum['compare_label']+ days?: string[]+ order?: number+ filter?: SeriesDatum['filter']+}++type InsightSeriesTooltipEntry<Meta extends InsightSeriesMetaBase> = TooltipContext<Meta>['seriesData'][number]++export interface InsightSeriesTooltipProps<Meta extends InsightSeriesMetaBase> {+ context: TooltipContext<Meta>+ timezone?: string+ interval?: IntervalType+ breakdownFilter?: BreakdownFilter+ dateRange?: DateRange+ trendsFilter?: TrendsFilter | null+ showPercentView?: boolean+ isPercentStackView?: boolean+ baseCurrency?: CurrencyCode+ groupTypeLabel?: string+ formatCompareLabel?: (label: string, dateLabel?: string) => string+ onRowClick?: (datum: SeriesDatum) => void+ showHeader?: boolean+ /** Override the auto-derived date header. Stickiness needs this since its `date`+ * is an interval-count integer, not a date — letting it format as a calendar date+ * produces a wrong "Thursday, 1 Jan 1970" header. */+ altTitle?: string | ((tooltipData: SeriesDatum[], formattedDate: string) => React.ReactNode)+ /** Overrides the default value formatter — needed for the pie chart, which renders the+ * raw aggregation plus the slice's share of the total. */+ renderCount?: (value: number) => string+ /** Overrides the default row label — used by lifecycle, where the label is the lifecycle+ * status (e.g. "New") rather than the entity name. */+ renderSeriesOverride?: (datum: SeriesDatum) => React.ReactNode+ /** Sort rows by value descending. Defaults true; pass false to use visual top-to-bottom order (e.g. lifecycle). */+ sortedByValue?: boolean+ /** Hide rows with value 0 — useful when zero means the series is absent (e.g. lifecycle statuses). */+ hideZeroRows?: boolean+}++/** Renders hog-charts' DefaultTooltip for insight series charts so they share the same tooltip+ * surface as SQL insights. Maps the quill TooltipContext to the insight-flavored value/label/date+ * formatting and wires the per-series persons-modal drill-down. */+export function InsightSeriesTooltip<Meta extends InsightSeriesMetaBase>({+ context,+ timezone = 'UTC',+ interval,+ breakdownFilter,+ dateRange,+ trendsFilter,+ showPercentView,+ isPercentStackView,+ baseCurrency,+ groupTypeLabel = 'people',+ formatCompareLabel,+ onRowClick,+ showHeader,+ altTitle,+ renderCount: renderCountOverride,+ renderSeriesOverride,+ sortedByValue = true,+ hideZeroRows,+}: InsightSeriesTooltipProps<Meta>): React.ReactElement {+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const { weekStartDay } = useValues(teamLogic)++ // Map each quill series entry (keyed by series.key) to the InsightTooltip SeriesDatum shape so the+ // existing breakdown/compare/value formatting helpers stay reusable. `datasetIndex` mirrors the+ // entry's position in context.seriesData, which the chart's onRowClick maps back to a series key.+ const datumByKey = useMemo(() => {+ const m = new Map<string, SeriesDatum>()+ context.seriesData.forEach((entry, idx) => {+ const meta = entry.series.meta ?? {}+ m.set(entry.series.key, {+ id: idx,+ dataIndex: context.dataIndex,+ datasetIndex: idx,+ order: (meta as InsightSeriesMetaBase).order ?? idx,+ label: entry.series.label,+ color: entry.color,+ count: entry.value,+ action: (meta as InsightSeriesMetaBase).action,+ breakdown_value: (meta as InsightSeriesMetaBase).breakdown_value ?? undefined,+ compare_label: (meta as InsightSeriesMetaBase).compare_label,+ date_label: (meta as InsightSeriesMetaBase).days?.[context.dataIndex],+ filter: (meta as InsightSeriesMetaBase).filter,+ })+ })+ return m+ }, [context.seriesData, context.dataIndex])++ const renderCount = useCallback(+ (value: number): string => {+ if (renderCountOverride) {+ return renderCountOverride(value)+ }+ if (showPercentView) {+ // Stickiness percent view: value is already a percentage.+ return `${value.toFixed(1)}%`+ }+ if (!isPercentStackView) {+ return formatAggregationAxisValue(trendsFilter, value, baseCurrency)+ }+ // hog-charts passes each segment as a 0..1 fraction, so format it directly as a percentage.+ return percentage(value)+ },+ [renderCountOverride, showPercentView, isPercentStackView, trendsFilter, baseCurrency]+ )++ const valueFormatter = useCallback(+ (value: number, entry: InsightSeriesTooltipEntry<Meta>): React.ReactNode => {+ const datum = datumByKey.get(entry.series.key)+ return formatAggregationValue(+ datum?.action?.math_property,+ value,+ renderCount,+ formatPropertyValueForDisplay+ )+ },+ [datumByKey, renderCount, formatPropertyValueForDisplay]+ )++ // Multiple distinct events in the tooltip — prefix breakdown rows with the event name+ // so the user knows which series each breakdown value belongs to.+ const hasMultipleEvents = useMemo(() => {+ const events = new Set([...datumByKey.values()].map((d) => d.action?.id ?? d.action?.name))+ return events.size > 1+ }, [datumByKey])++ const labelRenderer = useCallback(+ (entry: InsightSeriesTooltipEntry<Meta>): React.ReactNode => {+ const datum = datumByKey.get(entry.series.key)+ if (!datum) {+ return entry.series.label+ }+ if (renderSeriesOverride) {+ return renderSeriesOverride(datum)+ }+ const hasBreakdown =+ datum.breakdown_value !== undefined && datum.breakdown_value !== null && datum.breakdown_value !== ''+ if (hasBreakdown || datum.compare_label) {+ const title = getDatumTitle(datum, breakdownFilter, formatCompareLabel)+ if (hasMultipleEvents && (hasBreakdown || datum.compare_label)) {+ const seriesName =+ (datum.action ? getDisplayNameFromEntityFilter(datum.action) : null) ?? datum.label+ return (+ <>+ <span className="opacity-50 mr-1 shrink-0">{seriesName} ·</span>+ {title}+ </>+ )+ }+ return title+ }+ return datum.label+ },+ [datumByKey, renderSeriesOverride, breakdownFilter, formatCompareLabel, hasMultipleEvents]+ )++ const labelFormatter = useCallback((): React.ReactNode => {+ const firstKey = context.seriesData[0]?.series.key+ const date = firstKey ? datumByKey.get(firstKey)?.date_label : undefined+ const formattedDate = getFormattedDate(date, { interval, dateRange, timezone, weekStartDay })+ if (altTitle) {+ return getTooltipTitle([...datumByKey.values()], altTitle, formattedDate) ?? formattedDate+ }+ return formattedDate+ }, [context.seriesData, datumByKey, interval, dateRange, timezone, weekStartDay, altTitle])++ const onRowClickEntry = useCallback(+ (entry: InsightSeriesTooltipEntry<Meta>): void => {+ const datum = datumByKey.get(entry.series.key)+ if (datum) {+ onRowClick?.(datum)+ }+ },+ [datumByKey, onRowClick]+ )++ return (+ <DefaultTooltip<Meta>+ {...context}+ sortedByValue={sortedByValue}+ hideZeroRows={hideZeroRows}+ showHeader={showHeader !== false}+ labelFormatter={labelFormatter}+ labelRenderer={labelRenderer}+ valueFormatter={valueFormatter}+ onRowClick={onRowClick ? onRowClickEntry : undefined}+ footer={+ onRowClick+ ? context.seriesData.length > 1+ ? `Click a series to view ${groupTypeLabel}`+ : `Click to view ${groupTypeLabel}`+ : undefined+ }+ />+ )+}diff --git a/products/product_analytics/frontend/insights/shared/tooltipConfig.ts b/products/product_analytics/frontend/insights/shared/tooltipConfig.tsnew file mode 100644index 000000000000..2a530a4a754f--- /dev/null+++ b/products/product_analytics/frontend/insights/shared/tooltipConfig.ts@@ -0,0 +1,7 @@+import type { TooltipConfig } from '@posthog/quill-charts'++/** Tooltip config for the new unified tooltip (product-analytics-insights-tooltips flag on). */+export const INSIGHT_TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'cursor' }++/** Legacy tooltip config used when the flag is off. */+export const INSIGHT_TOOLTIP_CONFIG_LEGACY: TooltipConfig = { pinnable: true, placement: 'top' }