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(metrics): render metric series with the quill line chart (#76683)

Sam Pennington237331d5307e
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ca60c859054a..bed4b1123b39 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3672,6 +3672,15 @@ importers:
specifier: '*'
devDependencies:
+ '@storybook/react':
+ specifier: 'catalog:'
+ '@testing-library/jest-dom':
+ specifier: ^5.17.0
+ version: 5.17.0
+ '@testing-library/react':
+ specifier: ^14.3.1
kea-test-utils:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
diff --git a/products/metrics/frontend/components/MetricsChartLegend.tsx b/products/metrics/frontend/components/MetricsChartLegend.tsx
deleted file mode 100644
index 49820cfe08dc..000000000000
--- a/products/metrics/frontend/components/MetricsChartLegend.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { getColorVar } from 'lib/colors'
-import { type SparklineTimeSeries } from 'lib/components/Sparkline'
-
-/** Legend for the multi-series chart — a colour swatch + name per series. Hidden for a single series. */
-export function MetricsChartLegend({ series }: { series: SparklineTimeSeries[] }): JSX.Element | null {
- if (series.length < 2) {
- return null
- }
- return (
- <div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
- {series.map((s, i) => (
- <span key={`${i}-${s.name}`} className="flex items-center gap-1.5 text-xs text-secondary">
- <span
- className="w-2 h-2 rounded-full shrink-0"
- // Dynamic per-series colour can't be a Tailwind class.
- style={{ backgroundColor: getColorVar(s.color ?? 'muted') }}
- />
- {s.name}
- </span>
- ))}
- </div>
- )
-}
diff --git a/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx b/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx
new file mode 100644
index 000000000000..350949735d7f
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsExemplarMarkers.test.tsx
@@ -0,0 +1,89 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, screen } from '@testing-library/react'
+
+import { dimensions, makeOverlayContext, renderOverlayInChart } from '@posthog/quill-charts/testing'
+
+import { MetricsExemplarMarkers } from './MetricsExemplarMarkers'
+
+// Three hourly buckets, laid out 100px apart, so an interpolated x is checkable by eye.
+const BUCKETS = ['2026-08-01T10:00:00Z', '2026-08-01T11:00:00Z', '2026-08-01T12:00:00Z']
+const BUCKET_X: Record<string, number> = { [BUCKETS[0]]: 100, [BUCKETS[1]]: 200, [BUCKETS[2]]: 300 }
+const RADIUS = 4
+
+function renderMarkers(timestamps: string[], onClick: () => void = jest.fn()): void {
+ renderOverlayInChart(
+ <MetricsExemplarMarkers
+ exemplars={timestamps.map((timestamp) => ({ timeMs: Date.parse(timestamp), onClick }))}
+ />,
+ makeOverlayContext(
+ { x: (label) => BUCKET_X[label], y: (value) => value, yTicks: () => [] },
+ {
+ labels: BUCKETS,
+ }
+ )
+ )
+}
+
+function markerLefts(): number[] {
+ return screen.queryAllByTestId('metrics-exemplar-marker').map((dot) => parseFloat((dot as HTMLElement).style.left))
+}
+
+describe('MetricsExemplarMarkers', () => {
+ afterEach(() => cleanup())
+
+ it.each([
+ ['on the first bucket', '2026-08-01T10:00:00Z', 100],
+ ['a quarter into the first bucket', '2026-08-01T10:15:00Z', 125],
+ ['halfway between buckets', '2026-08-01T11:30:00Z', 250],
+ ['on the last bucket', '2026-08-01T12:00:00Z', 300],
+ // The last label marks the final bucket's start, not its end — an exemplar inside that
+ // still-open bucket must clamp to the bucket's position rather than being dropped.
+ ['inside the final (partial) bucket', '2026-08-01T12:30:00Z', 300],
+ ])('positions an exemplar %s', (_, timestamp, expectedX) => {
+ renderMarkers([timestamp])
+ expect(markerLefts()).toEqual([expectedX - RADIUS])
+ })
+
+ // Exemplars are fetched over the requested window, not the plotted grid, so a stale or
+ // wider-window response must not pile dots onto the first and last buckets.
+ it.each([
+ ['before the first bucket', '2026-08-01T09:59:00Z'],
+ ['a bucket span past the last bucket', '2026-08-01T13:00:01Z'],
+ ])('drops an exemplar %s instead of clamping it to the edge', (_, timestamp) => {
+ renderMarkers([timestamp])
+ expect(screen.queryAllByTestId('metrics-exemplar-marker')).toHaveLength(0)
+ })
+
+ it('clamps an exemplar onto a single-bucket chart instead of dropping it', () => {
+ renderOverlayInChart(
+ <MetricsExemplarMarkers exemplars={[{ timeMs: Date.parse('2026-08-01T10:30:00Z'), onClick: jest.fn() }]} />,
+ makeOverlayContext(
+ { x: (label) => BUCKET_X[label], y: (value) => value, yTicks: () => [] },
+ { labels: [BUCKETS[0]] }
+ )
+ )
+ expect(markerLefts()).toEqual([100 - RADIUS])
+ })
+
+ it('pins dots to the plot baseline', () => {
+ renderMarkers([BUCKETS[1]])
+ const dot = screen.getByTestId('metrics-exemplar-marker')
+ expect(dot.style.top).toBe(`${dimensions.plotTop + dimensions.plotHeight - RADIUS}px`)
+ })
+
+ it('opens the trace behind a clicked exemplar', () => {
+ const onClick = jest.fn()
+ renderMarkers([BUCKETS[1]], onClick)
+ fireEvent.click(screen.getByTestId('metrics-exemplar-marker'))
+ expect(onClick).toHaveBeenCalledTimes(1)
+ })
+
+ it('renders nothing when the chart has no buckets yet', () => {
+ renderOverlayInChart(
+ <MetricsExemplarMarkers exemplars={[{ timeMs: Date.parse(BUCKETS[0]), onClick: jest.fn() }]} />,
+ makeOverlayContext({ x: () => undefined, y: (value) => value, yTicks: () => [] }, { labels: [] })
+ )
+ expect(screen.queryAllByTestId('metrics-exemplar-marker')).toHaveLength(0)
+ })
+})
diff --git a/products/metrics/frontend/components/MetricsExemplarMarkers.tsx b/products/metrics/frontend/components/MetricsExemplarMarkers.tsx
new file mode 100644
index 000000000000..79d33e59d552
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsExemplarMarkers.tsx
@@ -0,0 +1,92 @@
+import { useChartLayout } from '@posthog/quill-charts'
+
+import { getColorVar } from 'lib/colors'
+import { dayjs } from 'lib/dayjs'
+import { hexToRGBA } from 'lib/utils/colors'
+
+export interface MetricsExemplar {
+ /** Emission time of the traced sample, as epoch ms. */
+ timeMs: number
+ onClick: () => void
+}
+
+const RADIUS = 4
+
+/** Traced emissions as clickable dots along the baseline of the metrics chart — the metric→trace
+ * pivot without opening the Samples tab. */
+export function MetricsExemplarMarkers({ exemplars }: { exemplars: MetricsExemplar[] }): JSX.Element | null {
+ const { scales, dimensions, labels } = useChartLayout()
+
+ if (!exemplars.length || labels.length === 0) {
+ return null
+ }
+
+ const bucketTimes = labels.map((label) => dayjs(label).valueOf())
+ // `link`, not a data color: a dot navigates to a trace, and it must not read as a fourth series.
+ const color = getColorVar('link')
+ const baseline = dimensions.plotTop + dimensions.plotHeight
+
+ return (
+ <>
+ {exemplars.map((exemplar, index) => {
+ const x = exemplarX(exemplar.timeMs, bucketTimes, labels, scales.x)
+ if (x === null) {
+ return null
+ }
+ return (
+ <button
+ key={`${exemplar.timeMs}-${index}`}
+ type="button"
+ aria-label={`Open the trace emitted at ${dayjs(exemplar.timeMs).format('D MMM YYYY HH:mm:ss')}`}
+ data-attr="metrics-exemplar-marker"
+ onClick={(e) => {
+ e.stopPropagation()
+ exemplar.onClick()
+ }}
+ className="absolute pointer-events-auto rounded-full border cursor-pointer transition-transform hover:scale-150"
+ style={{
+ left: x - RADIUS,
+ top: baseline - RADIUS,
+ width: RADIUS * 2,
+ height: RADIUS * 2,
+ backgroundColor: hexToRGBA(color, 0.85),
+ borderColor: color,
+ }}
+ />
+ )
+ })}
+ </>
+ )
+}
+
+/** Pixel x for a timestamp, linearly interpolated between the buckets bracketing it. */
+function exemplarX(
+ timeMs: number,
+ bucketTimes: number[],
+ labels: string[],
+ xScale: (label: string) => number | undefined
+): number | null {
+ const last = bucketTimes.length - 1
+ // Labels mark bucket starts, so the plotted range extends one bucket span past the last label.
+ const bucketWidth = last > 0 ? bucketTimes[last] - bucketTimes[last - 1] : Infinity
+ if (timeMs < bucketTimes[0] || timeMs >= bucketTimes[last] + bucketWidth) {
+ return null
+ }
+ let index = last
+ while (index > 0 && bucketTimes[index] > timeMs) {
+ index--
+ }
+ const start = xScale(labels[index])
+ if (start === undefined || !isFinite(start)) {
+ return null
+ }
+ const end = index + 1 < labels.length ? xScale(labels[index + 1]) : undefined
+ if (end === undefined || !isFinite(end)) {
+ return start
+ }
+ const span = bucketTimes[index + 1] - bucketTimes[index]
+ if (span <= 0) {
+ return start
+ }
+ return start + ((timeMs - bucketTimes[index]) / span) * (end - start)
+}
diff --git a/products/metrics/frontend/components/MetricsSeriesChart.test.tsx b/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
new file mode 100644
index 000000000000..b3ef06471622
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
@@ -0,0 +1,79 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import {
+ createDefaultTooltipAccessor,
+ ensureJsdom,
+ getHogChart,
+ hoverUntilTooltip,
+} from '@posthog/quill-charts/testing'
+
+import { initKeaTests } from '~/test/init'
+
+import type { MetricsChartSeries } from './metricsSeries'
+import { MetricsSeriesChart } from './MetricsSeriesChart'
+
+const BUCKETS = ['2026-08-01T10:00:00Z', '2026-08-01T11:00:00Z', '2026-08-01T12:00:00Z']
+
+function seriesWith(labels: Record<string, string>, values: (number | null)[]): MetricsChartSeries {
+ return { labels, points: BUCKETS.map((time, i) => ({ time, value: values[i] })) }
+}
+
+function renderChart(series: MetricsChartSeries[], exemplars?: { timeMs: number; onClick: () => void }[]): void {
+ render(<MetricsSeriesChart series={series} fallbackName="http.requests" exemplars={exemplars} />)
+}
+
+describe('MetricsSeriesChart', () => {
+ beforeEach(() => {
+ ensureJsdom()
+ initKeaTests()
+ })
+
+ afterEach(() => cleanup())
+
+ it('draws one line per series', () => {
+ renderChart([seriesWith({ service: 'checkout' }, [1, 2, 3]), seriesWith({ service: 'billing' }, [4, 5, 6])])
+ expect(getHogChart().seriesCount).toBe(2)
+ })
+
+ it.each([
+ ['names a grouped series by its labels', { service: 'checkout', env: 'prod' }, 'service=checkout, env=prod'],
+ ['falls back to the metric name when ungrouped', {}, 'http.requests'],
+ ])('%s', (_, labels, expected) => {
+ renderChart([seriesWith(labels, [1, 2, 3]), seriesWith({ service: 'billing' }, [4, 5, 6])])
+ expect(screen.getByText(expected)).toBeInTheDocument()
+ })
+
+ it.each([
+ ['hides the legend for a single series', 1, false],
+ ['shows the legend once there are two', 2, true],
+ ])('%s', (_, count, expected) => {
+ renderChart(Array.from({ length: count }, (_, i) => seriesWith({ service: `svc-${i}` }, [1, 2, 3])))
+ expect(!!screen.queryByTestId('hog-chart-timeseries-line-legend')).toBe(expected)
+ })
+
+ it('renders a clickable dot per traced exemplar', () => {
+ renderChart([seriesWith({}, [1, 2, 3])], [{ timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn() }])
+ expect(screen.getAllByTestId('metrics-exemplar-marker')).toHaveLength(1)
+ })
+
+ // A null bucket is a non-representable aggregate. Charting it as 0 is the legacy behavior;
+ // dropping the point instead would silently shift every later value a bucket to the left.
+ it('charts a null bucket as zero rather than dropping the point', async () => {
+ renderChart([seriesWith({}, [1, null, 3])])
+ const chart = getHogChart()
+ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 1, BUCKETS.length))
+ expect(tooltip.value('http.requests')).toBe('0')
+ })
+
+ // Guards createXAxisTickCallback and the tz-aware labelFormatter wiring: a regression here
+ // renders raw ISO strings on every tick and tooltip header instead of formatted dates.
+ it('formats the x-axis ticks and tooltip label as tz-aware dates', async () => {
+ renderChart([seriesWith({}, [1, 2, 3])])
+ const chart = getHogChart()
+ expect(chart.xTicks()).toEqual(['10:00', '11:00', '12:00'])
+ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 1, BUCKETS.length))
+ expect(tooltip.label()).toBe('1 Aug 2026 11:00:00')
+ })
+})
diff --git a/products/metrics/frontend/components/MetricsSeriesChart.tsx b/products/metrics/frontend/components/MetricsSeriesChart.tsx
index ff149c1aaaeb..c01e31055ec4 100644
--- a/products/metrics/frontend/components/MetricsSeriesChart.tsx
+++ b/products/metrics/frontend/components/MetricsSeriesChart.tsx
@@ -1,97 +1,66 @@
-import { useCallback, useMemo } from 'react'
+import { useValues } from 'kea'
+import { useMemo } from 'react'
-import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
-import { dayjs } from 'lib/dayjs'
+import {
+ type Series,
+ TimeSeriesLineChart,
+ type TimeSeriesLineChartConfig,
+ createXAxisTickCallback,
+} from '@posthog/quill-charts'
-import { MetricsChartLegend } from './MetricsChartLegend'
-import { formatSeriesName, seriesColor } from './metricsSeries'
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import { dayjs } from 'lib/dayjs'
+import { teamLogic } from 'scenes/teamLogic'
-/** Source-agnostic series shape: the REST viewer (`_MetricSeriesApi`) and the
- * `MetricsQuery` schema node (`MetricsQuerySeries`) both map onto it. */
-export interface MetricsChartSeries {
- labels: Record<string, string>
- points: { time: string; value: number }[]
- metricName?: string | null
-}
+import { MetricsExemplarMarkers, type MetricsExemplar } from './MetricsExemplarMarkers'
+import { formatSeriesName, type MetricsChartSeries, seriesColor } from './metricsSeries'
-/** Multi-series metric line chart + legend, shared by the Viewer and the
- * dashboard/insight tile. Every series shares one time grid (the backend
- * zero-fills), so the x-axis comes from the first series. */
+/** Multi-series metric line chart, shared by the Viewer and the dashboard/insight tile. Every series
+ * shares one time grid (the backend zero-fills), so the x-axis comes from the first series. */
export function MetricsSeriesChart({
series,
fallbackName,
- className,
+ exemplars,
}: {
series: MetricsChartSeries[]
fallbackName: string
- className?: string
+ exemplars?: MetricsExemplar[]
}): JSX.Element {
- const chartSeries = useMemo(
+ const { timezone } = useValues(teamLogic)
+ const theme = useChartTheme()
+
+ const chartSeries = useMemo<Series[]>(
() =>
series.map((s, index) => ({
- name: formatSeriesName({ labels: s.labels, metric_name: s.metricName ?? undefined }, fallbackName),
- values: s.points.map((p) => p.value),
- color: seriesColor(index),
+ key: `${index}`,
+ label: formatSeriesName({ labels: s.labels, metric_name: s.metricName ?? undefined }, fallbackName),
+ // A null value is a gap (non-representable aggregate); charted as 0 for now.
+ data: s.points.map((p) => p.value ?? 0),
+ color: getColorVar(seriesColor(index)),
})),
[series, fallbackName]
)
- const sparklineLabels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])
-
- // Mirrors the format/timeUnit ladder LogsSparkline uses so the X-axis density
- // matches the selected range.
- const { timeUnit, tickFormat } = useMemo(() => {
- if (!sparklineLabels.length) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }
- }
- const first = dayjs(sparklineLabels[0])
- const last = dayjs(sparklineLabels[sparklineLabels.length - 1])
- const hoursDiff = last.diff(first, 'hours')
- if (hoursDiff <= 1) {
- return { timeUnit: 'second' as const, tickFormat: 'HH:mm:ss' }
- }
- if (hoursDiff <= 6) {
- return { timeUnit: 'minute' as const, tickFormat: 'HH:mm:ss' }
- }
- if (hoursDiff <= 48) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }
- }
- return { timeUnit: 'day' as const, tickFormat: 'D MMM HH:mm' }
- }, [sparklineLabels])
+ const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])
- const withXScale = useCallback(
- (scale: AnyScaleOptions): AnyScaleOptions =>
- ({
- ...scale,
- type: 'timeseries',
- ticks: {
- display: true,
- maxRotation: 0,
- maxTicksLimit: 6,
- font: { size: 10, lineHeight: 1 },
- callback: function (value: string | number) {
- return dayjs(value).format(tickFormat)
- },
- },
- time: { unit: timeUnit },
- }) as AnyScaleOptions,
- [timeUnit, tickFormat]
+ const config = useChartConfig<TimeSeriesLineChartConfig>(
+ () => ({
+ xAxis: { tickFormatter: createXAxisTickCallback({ allDays: labels, timezone }) },
+ legend: { show: chartSeries.length > 1, interactive: true },
+ tooltip: {
+ placement: 'cursor',
+ pinnable: true,
+ labelFormatter: (label: string) => dayjs(label).tz(timezone).format('D MMM YYYY HH:mm:ss'),
+ },
+ }),
+ [labels, timezone, chartSeries.length]
)
- const renderLabel = useCallback((label: string): string => dayjs(label).format('D MMM YYYY HH:mm:ss'), [])
-
return (
- <div className={className}>
- <div className="flex-1 min-h-0">
- <Sparkline
- type="line"
- data={chartSeries}
- labels={sparklineLabels}
- className="w-full h-full"
- withXScale={withXScale}
- renderLabel={renderLabel}
- />
- </div>
- <MetricsChartLegend series={chartSeries} />
+ <div className="relative flex h-full w-full min-h-0 flex-col">
+ <TimeSeriesLineChart series={chartSeries} labels={labels} theme={theme} config={config}>
+ {exemplars?.length ? <MetricsExemplarMarkers exemplars={exemplars} /> : null}
+ </TimeSeriesLineChart>
</div>
)
}
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 3de5936e414b..a79f48108888 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -1,6 +1,6 @@
import { useActions, useMountedLogic, useValues } from 'kea'
import { router } from 'kea-router'
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import {
LemonButton,
@@ -16,7 +16,6 @@ import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboar
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
import { type MetricSummary } from 'lib/components/Metric/metricSummary'
-import { AnyScaleOptions, Sparkline, SparklineMarker } from 'lib/components/Sparkline'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'
@@ -40,9 +39,10 @@ import { traceUrl } from 'products/tracing/frontend/traceLinks'
import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'
import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
-import { MetricsChartLegend } from './MetricsChartLegend'
+import { type MetricsExemplar } from './MetricsExemplarMarkers'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import { MetricsSamplesPanel } from './MetricsSamplesPanel'
+import { MetricsSeriesChart } from './MetricsSeriesChart'
import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'
import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'
import { MetricStatPanel } from './MetricStatPanel'
@@ -112,6 +112,10 @@ const DATE_OPTIONS: DateMappingOption[] = [
},
]
+function renderLabel(label: string): string {
+ return dayjs(label).format('D MMM YYYY HH:mm:ss')
+}
+
export const MetricsViewer = (): JSX.Element => {
const logic = metricsViewerLogic()
// Keep the picker logic mounted alongside the viewer so the chosen metric's
@@ -181,13 +185,12 @@ export const MetricsViewer = (): JSX.Element => {
// Traced emissions as clickable dots along the bottom of the chart — the
// metric->trace pivot without opening the Samples tab. Skipped entirely when
// the user can't view traces, so a dot never leads to a dead end.
- const exemplarMarkers: SparklineMarker[] = useMemo(
+ const exemplarMarkers: MetricsExemplar[] = useMemo(
() =>
tracingDisabledReason
? []
: traceExemplars.map((exemplar) => ({
- xValue: dayjs(exemplar.timestamp).valueOf(),
- color: 'primary',
+ timeMs: dayjs(exemplar.timestamp).valueOf(),
onClick: () => {
exemplarDotClicked(!!exemplar.spanId)
router.actions.push(
@@ -222,48 +225,6 @@ export const MetricsViewer = (): JSX.Element => {
)
const recommendedAggregation = selectedMetricType ? RECOMMENDED_AGGREGATION_BY_TYPE[selectedMetricType] : undefined
- // Mirrors the format/timeUnit ladder LogsSparkline uses so the X-axis density
- // matches the selected range.
- const { timeUnit, tickFormat } = useMemo(() => {
- if (!sparklineLabels.length) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }
- }
- const first = dayjs(sparklineLabels[0])
- const last = dayjs(sparklineLabels[sparklineLabels.length - 1])
- const hoursDiff = last.diff(first, 'hours')
- if (hoursDiff <= 1) {
- return { timeUnit: 'second' as const, tickFormat: 'HH:mm:ss' }
- }
- if (hoursDiff <= 6) {
- return { timeUnit: 'minute' as const, tickFormat: 'HH:mm:ss' }
- }
- if (hoursDiff <= 48) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }
- }
- return { timeUnit: 'day' as const, tickFormat: 'D MMM HH:mm' }
- }, [sparklineLabels])
-
- const withXScale = useCallback(
- (scale: AnyScaleOptions): AnyScaleOptions =>
- ({
- ...scale,
- type: 'timeseries',
- ticks: {
- display: true,
- maxRotation: 0,
- maxTicksLimit: 6,
- font: { size: 10, lineHeight: 1 },
- callback: function (value: string | number) {
- return dayjs(value).format(tickFormat)
- },
- },
- time: { unit: timeUnit },
- }) as AnyScaleOptions,
- [timeUnit, tickFormat]
- )
-
- const renderLabel = useCallback((label: string): string => dayjs(label).format('D MMM YYYY HH:mm:ss'), [])
-
const hasResults = sparklineValues.length > 0
return (
@@ -422,14 +383,10 @@ export const MetricsViewer = (): JSX.Element => {
anomaly={anomalyBadge}
/>
) : hasResults ? (
- <Sparkline
- type="line"
- data={chartSeries}
- labels={sparklineLabels}
- className="w-full h-full"
- withXScale={withXScale}
- renderLabel={renderLabel}
- markers={exemplarMarkers}
+ <MetricsSeriesChart
+ series={chartSeries}
+ fallbackName={metricName}
+ exemplars={exemplarMarkers}
/>
) : !queryResultsLoading ? (
<div className="h-full flex items-center justify-center text-secondary text-sm">
@@ -438,7 +395,6 @@ export const MetricsViewer = (): JSX.Element => {
) : null}
{queryResultsLoading && <SpinnerOverlay />}
</div>
- {viewMode === 'chart' && hasResults && <MetricsChartLegend series={chartSeries} />}
</div>
{viewMode === 'chart' && hasMetricName && (
<div className="xl:w-[26rem] shrink-0 xl:max-h-[360px] flex flex-col">
diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.ts
index 5787f9624546..41037a141a20 100644
--- a/products/metrics/frontend/components/metricsSeries.ts
+++ b/products/metrics/frontend/components/metricsSeries.ts
@@ -1,5 +1,13 @@
import type { _MetricSeriesApi } from 'products/metrics/frontend/generated/api.schemas'
+/** Source-agnostic series shape for the metrics chart: the REST viewer (`_MetricSeriesApi`) and the
+ * `MetricsQuery` schema node (`MetricsQuerySeries`) both map onto it. */
+export interface MetricsChartSeries {
+ labels: Record<string, string>
+ points: { time: string; value: number | null }[]
+ metricName?: string | null
+}
+
// PostHog defines data-color-1..15 in vars.scss; cycle through them so each series gets a distinct line.
const SERIES_COLOR_COUNT = 15
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index adf52b0369fc..47a3aaf9f351 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -5,7 +5,6 @@ import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import { type MetricSummary } from 'lib/components/Metric/metricSummary'
-import { type SparklineTimeSeries } from 'lib/components/Sparkline'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { dayjs } from 'lib/dayjs'
@@ -38,7 +37,7 @@ import type { Node } from '../../../../frontend/src/queries/schema/schema-genera
import type { _MetricNameApi } from '../generated/api.schemas'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import type { MetricNameItem } from './metricNamePickerLogic'
-import { formatSeriesName, seriesColor } from './metricsSeries'
+import type { MetricsChartSeries } from './metricsSeries'
export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95' | 'rate' | 'increase'
@@ -166,7 +165,7 @@ export interface metricsViewerLogicValues {
label: string
}[]
attributeKeyOptionsLoading: boolean
- chartSeries: SparklineTimeSeries[]
+ chartSeries: MetricsChartSeries[]
currentSeries: MetricsViewerSeries | undefined
dateFrom: string | null
dateTo: string | null
@@ -357,7 +356,7 @@ export interface metricsViewerLogicMeta {
queryFilters: (filterGroup: UniversalFiltersGroup) => _MetricFilterApi[]
attributeEndpointFilters: (dateFrom: string | null, dateTo: string | null) => Record<string, string>
currentSeries: (queryResults: _MetricSeriesApi[]) => MetricsViewerSeries | undefined
- chartSeries: (queryResults: _MetricSeriesApi[], metricName: string) => SparklineTimeSeries[]
+ chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]
sparklineValues: (currentSeries: _MetricSeriesApi | undefined) => number[]
sparklineLabels: (currentSeries: _MetricSeriesApi | undefined) => string[]
statTotal: (sparklineValues: number[]) => number
@@ -762,16 +761,14 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
(results: MetricsViewerSeries[]): MetricsViewerSeries | undefined => results[0],
],
// All series rendered as chart lines (a group-by query returns one series per label combination).
- // The x-axis labels come from `sparklineLabels` (the backend grids every series onto one time axis).
+ // `MetricsSeriesChart` owns naming and colors; this only bridges the API's snake_case field.
chartSeries: [
- (s) => [s.queryResults, s.metricName],
- (results: MetricsViewerSeries[], metricName: string): SparklineTimeSeries[] =>
- results.map((series, index) => ({
- name: formatSeriesName(series, metricName),
- // A null value is a gap (non-representable aggregate); Sparkline
- // takes plain numbers, so gaps chart as 0 for now.
- values: series.points.map((p) => p.value ?? 0),
- color: seriesColor(index),
+ (s) => [s.queryResults],
+ (results: MetricsViewerSeries[]): MetricsChartSeries[] =>
+ results.map((series) => ({
+ labels: series.labels,
+ points: series.points,
+ metricName: series.metric_name,
})),
],
sparklineValues: [
diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
index b260d3430068..965c3f4ac5c9 100644
--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx
+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
@@ -43,11 +43,7 @@ export function MetricsQueryNode(props: {
return (
<div className="relative flex flex-col w-full h-full min-h-[200px]">
{hasPoints ? (
- <MetricsSeriesChart
- series={series.map((s) => ({ labels: s.labels, points: s.points, metricName: s.metricName }))}
- fallbackName={fallbackName}
- className="flex flex-col w-full h-full"
- />
+ <MetricsSeriesChart series={series} fallbackName={fallbackName} />
) : !responseLoading ? (
<div className="flex-1 flex items-center justify-center text-secondary text-sm">
No data for this metric in the selected range.
diff --git a/products/metrics/package.json b/products/metrics/package.json
index 6cadda681e72..c163a4c4db73 100644
--- a/products/metrics/package.json
+++ b/products/metrics/package.json
@@ -12,12 +12,18 @@
"posthog-js": "catalog:"
},
"devDependencies": {
+ "@storybook/react": "catalog:",
+ "@testing-library/jest-dom": "^5.17.0",
+ "@testing-library/react": "^14.3.1",
"kea-test-utils": "catalog:"
},
"peerDependencies": {
"@posthog/brand": "catalog:",
"@posthog/icons": "catalog:",
"@posthog/products-error-tracking": "workspace:*",
+ "@storybook/react": "*",
+ "@testing-library/jest-dom": "*",
+ "@testing-library/react": "*",
"@types/react": "*",
"clsx": "*",
"react": "*",