: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(error-tracking): show a tooltip when hovering a spike bar (#124300)
Hugues Pouillot40fcf57daaad
diff --git a/products/error_tracking/frontend/components/VolumeSparkline/SpikeTooltip.tsx b/products/error_tracking/frontend/components/VolumeSparkline/SpikeTooltip.tsxnew file mode 100644index 000000000000..74d6dd3b8d58--- /dev/null+++ b/products/error_tracking/frontend/components/VolumeSparkline/SpikeTooltip.tsx@@ -0,0 +1,35 @@+import { TooltipFooter, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'++import { resolveVariableColor } from 'lib/charts/utils/color'++import { formatCompactVolumeHoverDate, formatCompactVolumeHoverOccurrences } from './formatCompactVolumeHover'+import type { SparklineDatum } from './types'++export type SpikeTooltipProps = {+ datum: SparklineDatum+ clickable: boolean+}++export function SpikeTooltip({ datum, clickable }: SpikeTooltipProps): JSX.Element {+ const swatchColor = resolveVariableColor(datum.color)+ return (+ <TooltipSurface data-attr="error-tracking-volume-spike-tooltip">+ <div className="flex items-center justify-between gap-4">+ <span className="flex items-center gap-1.5 font-semibold">+ {swatchColor && <TooltipSwatch color={swatchColor} />}+ <span>Spike detected</span>+ </span>+ <span className="opacity-60">+ <span>{formatCompactVolumeHoverDate(datum)}</span> (UTC)+ </span>+ </div>+ <div className="tabular-nums">{formatCompactVolumeHoverOccurrences(datum)}</div>+ {datum.spikeMultiplier !== undefined && (+ <div className="tabular-nums">+ <span>{datum.spikeMultiplier.toFixed(1)}x</span> this issue's baseline+ </div>+ )}+ {clickable && <TooltipFooter>Click to see spike details</TooltipFooter>}+ </TooltipSurface>+ )+}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsx b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsxindex 66c07a51d0c6..1e1c8f1f4901 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsx+++ b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.test.tsx@@ -1,6 +1,13 @@import { cleanup, fireEvent, render } from '@testing-library/react'-import { dragSelection, getChart, hoverAtIndex, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'+import {+ dragSelection,+ getChart,+ hoverAtIndex,+ hoverUntilTooltip,+ setupJsdom,+ setupSyncRaf,+} from '@posthog/quill-charts/testing'import { initKeaTests } from '~/test/init'@@ -220,6 +227,21 @@ describe('VolumeSparkline', () => {})})+ describe('spike tooltip', () => {+ it.each([+ { index: 2, expected: "Spike detected1 Jan 02:00 (UTC)10 occurrences4.5x this issue's baseline" },+ { index: 1, expected: null },+ ])('shows spike details only when hovering a spike bucket ($index)', async ({ index, expected }) => {+ const data = buildData({ 2: { isSpike: true, color: 'var(--brand-yellow)', spikeMultiplier: 4.5 } })+ const wrapper = renderChart({ data, layout: 'compact', xAxis: 'minimal' })++ const tooltip = await hoverUntilTooltip(wrapper, index, data.length)++ const spikeTooltip = tooltip.querySelector('[data-attr="error-tracking-volume-spike-tooltip"]')+ expect(spikeTooltip?.textContent ?? null).toEqual(expected)+ })+ })+describe('bar hover reporting', () => {it('publishes the hovered bin to the logic', () => {const data = buildData()diff --git a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsxindex c733f913811d..65250d880ebb 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx+++ b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx@@ -8,6 +8,7 @@ import {type Series,TimeSeriesBarChart,type TimeSeriesBarChartConfig,+ type TooltipContext,useChartHover,} from '@posthog/quill-charts'@@ -19,6 +20,7 @@ import { teamLogic } from 'scenes/teamLogic'import { errorTrackingVolumeSparklineLogic } from './errorTrackingVolumeSparklineLogic'import { EVENT_LABEL_BAR_GAP, EVENT_LABEL_HEIGHT, EventMarkers } from './EventMarkers'import { SpikeStripes } from './SpikeStripes'+import { SpikeTooltip } from './SpikeTooltip'import type {SparklineData,SparklineDatum,@@ -102,6 +104,8 @@ export function VolumeSparkline({[data])+ const hasSpikes = useMemo(() => data.some((datum) => datum.isSpike), [data])+const showAxis = xAxis !== 'none'const eventLabelReserve = events.length > 0 ? EVENT_LABEL_HEIGHT + EVENT_LABEL_BAR_GAP : undefinedconst config = useChartConfig<TimeSeriesBarChartConfig>(@@ -117,10 +121,19 @@ export function VolumeSparkline({showTickMarks: false,showCrosshair: showAxis,showGrid: false,- // Hover is surfaced as issue metrics beside the chart, not as a tooltip over it.- tooltip: { enabled: false },+ // Only spike bars get a tooltip. Other hovers show as issue metrics beside the chart.+ // `band` keeps a floored tiny spike bar easy to hit.+ tooltip: { enabled: hasSpikes, hitArea: 'band' },}),- [layout, xAxis, showAxis, eventLabelReserve, timezone, maxValue]+ [layout, xAxis, showAxis, eventLabelReserve, timezone, maxValue, hasSpikes]+ )++ const renderTooltip = useCallback(+ ({ dataIndex }: TooltipContext): JSX.Element | null => {+ const datum = data[dataIndex]+ return datum?.isSpike ? <SpikeTooltip datum={datum} clickable={!!onSpikeClick} /> : null+ },+ [data, onSpikeClick])const onDateRangeZoom = useMemo(() => {@@ -144,8 +157,6 @@ export function VolumeSparkline({}}, [data, onRangeSelect])- const hasSpikes = useMemo(() => data.some((datum) => datum.isSpike), [data])-const isPointClickable = useCallback((dataIndex: number): boolean =>(!!onSpikeClick && !!data[dataIndex].isSpike) || (!!onBucketClick && !!bucketEnd(data, dataIndex)),@@ -183,6 +194,7 @@ export function VolumeSparkline({labels={labels}theme={theme}config={config}+ tooltip={renderTooltip}onDateRangeZoom={onDateRangeZoom}onPointClick={onPointClick}isPointClickable={isPointClickable}diff --git a/products/error_tracking/frontend/components/VolumeSparkline/types.ts b/products/error_tracking/frontend/components/VolumeSparkline/types.tsindex bb4f4ab63650..145a1e96b204 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/types.ts+++ b/products/error_tracking/frontend/components/VolumeSparkline/types.ts@@ -4,6 +4,8 @@ export type SparklineDatum = {color?: string/** With `color`, flags the bar as a detected spike: its own color plus animated stripes. */isSpike?: boolean+ /** For a spike, how many times the detection baseline its bucket reached. */+ spikeMultiplier?: number}export type SparklineData = SparklineDatum[]diff --git a/products/error_tracking/frontend/hooks/use-sparkline-data.test.ts b/products/error_tracking/frontend/hooks/use-sparkline-data.test.tsnew file mode 100644index 000000000000..f5c144d63c40--- /dev/null+++ b/products/error_tracking/frontend/hooks/use-sparkline-data.test.ts@@ -0,0 +1,35 @@+import { ErrorTrackingSpikeEvent } from 'lib/components/Errors/types'++import { applyVolumeSpikeHighlights } from './use-sparkline-data'++const HOUR_MS = 60 * 60 * 1000+const BASE = Date.parse('2024-01-01T00:00:00.000Z')++function spikeAt(offsetMs: number, currentBucketValue: number, computedBaseline: number): ErrorTrackingSpikeEvent {+ return {+ id: `spike-${offsetMs}-${currentBucketValue}`,+ issue: { id: 'issue', name: null, description: null },+ detected_at: new Date(BASE + offsetMs).toISOString(),+ current_bucket_value: currentBucketValue,+ computed_baseline: computedBaseline,+ }+}++describe('applyVolumeSpikeHighlights', () => {+ const data = [0, 1, 2].map((index) => ({ date: new Date(BASE + index * HOUR_MS), value: 10 }))++ it.each([+ {+ name: 'the largest multiplier in the bucket',+ spikes: [spikeAt(HOUR_MS, 30, 10), spikeAt(HOUR_MS + 60_000, 50, 10)],+ expected: 5,+ },+ { name: 'no multiplier for a zero baseline', spikes: [spikeAt(HOUR_MS, 30, 0)], expected: undefined },+ ])('flags the bucket with $name', ({ spikes, expected }) => {+ const [before, spiked, after] = applyVolumeSpikeHighlights(data, spikes)++ expect(spiked).toMatchObject({ isSpike: true, spikeMultiplier: expected })+ expect(before.isSpike).toBeUndefined()+ expect(after.isSpike).toBeUndefined()+ })+})diff --git a/products/error_tracking/frontend/hooks/use-sparkline-data.tsx b/products/error_tracking/frontend/hooks/use-sparkline-data.tsxindex 2d926e42104e..8e8faa6212ae 100644--- a/products/error_tracking/frontend/hooks/use-sparkline-data.tsx+++ b/products/error_tracking/frontend/hooks/use-sparkline-data.tsx@@ -79,11 +79,23 @@ export function applyVolumeSpikeHighlights(}const binSizeMs = data[1].date.getTime() - data[0].date.getTime()- const spikeTimestamps = spikeEvents.map((s) => new Date(s.detected_at).getTime())+ const spikes = spikeEvents.map((s) => ({+ time: new Date(s.detected_at).getTime(),+ multiplier: s.computed_baseline > 0 ? s.current_bucket_value / s.computed_baseline : undefined,+ }))return data.map((datum) => {const datumTime = datum.date.getTime()- const hasSpikeInBin = spikeTimestamps.some((st) => st >= datumTime && st < datumTime + binSizeMs)- return hasSpikeInBin ? { ...datum, color: spikeStripeColor, isSpike: true } : datum+ const spikesInBin = spikes.filter((spike) => spike.time >= datumTime && spike.time < datumTime + binSizeMs)+ if (spikesInBin.length === 0) {+ return datum+ }+ const multipliers = spikesInBin.flatMap((spike) => (spike.multiplier === undefined ? [] : [spike.multiplier]))+ return {+ ...datum,+ color: spikeStripeColor,+ isSpike: true,+ spikeMultiplier: multipliers.length > 0 ? Math.max(...multipliers) : undefined,+ }})}