: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
fix(metrics): fit stat panels to their tiles and tidy their captions (#114616)
Frank Hamand6875002602b7
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsxindex bd0d7a3e1d2b..162e12000ae8 100644--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx@@ -127,12 +127,16 @@ describe('MetricCard', () => {}})- it('updates the headline value and label when hovering a different point', () => {+ it.each<[string, ((label: string) => string) | undefined, string]>([+ ['the raw label', undefined, 'Feb'],+ ['the label from formatLabel', (label) => `${label} 2026`, 'Feb 2026'],+ ])('updates the headline value and shows %s when hovering a different point', (_name, formatLabel, label) => {const { container, chart } = renderHogChart(<MetricCardtitle="Total"data={[100, 200, 300, 400]}labels={LABELS}+ formatLabel={formatLabel}theme={THEME}animationMs={0}hoverIntentMs={0}@@ -141,7 +145,7 @@ describe('MetricCard', () => {)chart.hoverAtIndex(1)expect(container.textContent).toContain('$200')- expect(container.textContent).toContain('Feb')+ expect(container.textContent).toContain(label)})it('headlines the supplied `value` at rest while the chart still draws from `data`', () => {diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsxindex 6c6e060cdef6..093218ac51b2 100644--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx@@ -29,6 +29,9 @@ export interface MetricCardProps {data?: number[]/** Labels paired with `data`. Used for the default subtitle on hover. */labels?: string[]+ /** Formats a label for the default subtitle, e.g. an ISO time as a short date. The sparkline+ * keeps the raw `labels`, which must stay unique. */+ formatLabel?: (label: string) => React.ReactNode/** Required when `data` is present. */theme?: ChartTheme/** Sparkline line + fill color. Falls back to `theme.colors[0]`. */@@ -41,6 +44,9 @@ export interface MetricCardProps {/** Dash the sparkline from this index onward (e.g. an in-progress trailing period). */sparklineDashedFromIndex?: numberformatValue?: (value: number) => string+ /** Classes for the headline number. Replaces the default `text-4xl` size, e.g. with container+ * query sizes so a narrow tile keeps the number on one line. */+ headlineClassName?: stringformatChange?: (percent: number) => stringshowChange?: boolean/** Fixed comparison pill. Supplied → no hover-driven fallback. Pass `null` to suppress. */@@ -87,6 +93,7 @@ function MetricCardInner({value,data,labels,+ formatLabel,theme,color,sparklineHeight = 120,@@ -95,6 +102,7 @@ function MetricCardInner({sparklineClassName = 'mt-4',sparklineDashedFromIndex,formatValue = DEFAULT_FORMAT_VALUE,+ headlineClassName = 'text-4xl',formatChange = DEFAULT_FORMAT_CHANGE,showChange = true,change,@@ -150,8 +158,9 @@ function MetricCardInner({// The tooltip describes the resting comparison, so hide it once the pill shows the per-point delta.const activeChangeTooltip = usePrevPointHover ? undefined : changeTooltipconst headlineDisplay = sparklineData ? formatValue(animatedValue) : formatValue(restingValue)- const resolvedSubtitle =- subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : labels?.[activeIndex])+ const activeLabel = labels?.[activeIndex]+ const pointLabel = activeLabel != null && formatLabel ? formatLabel(activeLabel) : activeLabel+ const resolvedSubtitle = subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : pointLabel)const positive = delta != null && delta.value >= 0const isGood = goodDirection === 'up' ? positive : !positive@@ -161,7 +170,7 @@ function MetricCardInner({const showHeader = title != null || headerDelta != nullconst headerJustify = title != null ? 'justify-between' : 'justify-end'const renderedHeadline = (- <div className={`text-4xl font-bold tracking-tight tabular-nums${showHeader ? ' mt-2' : ''}`}>+ <div className={`${headlineClassName} font-bold tracking-tight tabular-nums${showHeader ? ' mt-2' : ''}`}>{headlineDisplay}</div>)@@ -184,7 +193,8 @@ function MetricCardInner({)}{changeInline && delta != null ? (- <div className="flex items-center justify-between gap-2">+ // Wraps so a narrow card moves the pill under the number instead of clipping it.+ <div className="flex flex-wrap items-center justify-between gap-2">{renderedHeadline}<ChangePillpositive={positive}diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.mdindex 08393f5611f4..97562ebaec00 100644--- a/packages/quill/packages/charts/src/docs/chart-types.md+++ b/packages/quill/packages/charts/src/docs/chart-types.md@@ -101,9 +101,11 @@ Bars use `hitArea: 'band'`.A left-aligned tile: headline number, change pill, sparkline.- `title={null}` drops the title row. The header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle and no `labels`, so a value-only card renders just the number.-- `changeSize="md"` renders a larger pill (default `sm`); `changeInline` puts it beside the headline instead of in the header.+- `changeSize="md"` renders a larger pill (default `sm`); `changeInline` puts it beside the headline instead of in the header. The inline pill wraps under the headline when the card is too narrow for both.+- `headlineClassName` replaces the headline's default `text-4xl`, for example with container query sizes so a narrow tile keeps the number on one line.- `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes it from that index onward (an in-progress trailing period).- `subtitle` always wins. `restingSubtitle` (`'Avg'`) shows only at rest and yields to the hovered point's label on hover; pair it with a `value` that summarizes the series.+- `formatLabel` formats the point label in the default subtitle, for example an ISO time as a short date. The sparkline keeps the raw `labels`, so they stay unique.- `hoverChangeFromPreviousPoint` keeps the resting `change` pill at rest but, while hovering, swaps it for the hovered point's change versus the previous point (hidden at the first point).- `changeTooltip` shows a styled hover tooltip on the change pill, using the host's tooltip surface tokens with chart-surface fallbacks.diff --git a/products/metrics/frontend/nodes/MetricsHistogramQueryNode.tsx b/products/metrics/frontend/nodes/MetricsHistogramQueryNode.tsxindex 8ca78a2150e2..c7fa55d1ecec 100644--- a/products/metrics/frontend/nodes/MetricsHistogramQueryNode.tsx+++ b/products/metrics/frontend/nodes/MetricsHistogramQueryNode.tsx@@ -4,6 +4,7 @@ import { useState } from 'react'import { SpinnerOverlay } from '@posthog/lemon-ui'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { cn } from 'lib/utils/css-classes'import { InsightErrorState } from 'scenes/insights/EmptyStates'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'@@ -40,7 +41,14 @@ export function MetricsHistogramQueryNode(props: {const unit = props.query.unitreturn (- <div className="relative flex flex-col w-full h-full min-h-[200px]">+ // A dashboard tile sets the height, so a minimum would overflow a short tile. Elsewhere the+ // parent can have no height, and the heatmap then needs the minimum to draw at all.+ <div+ className={cn(+ 'relative flex flex-col w-full h-full',+ props.context.insightProps?.dashboardId == null && 'min-h-[200px]'+ )}+ >{responseError ? (<InsightErrorState query={props.query} excludeDetail title={responseError} />) : histogram && histogram.times?.length ? (diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsxindex 60ebf5755282..becc5a306707 100644--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx@@ -5,6 +5,7 @@ import { LemonBanner, SpinnerOverlay } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { cn } from 'lib/utils/css-classes'import { truncate } from 'lib/utils/strings'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'@@ -136,7 +137,14 @@ function MetricsQueryResults({ dataKey: key, ...props }: MetricsQueryNodeProps &(props.query.language === 'promql' && props.query.promql ? truncate(props.query.promql, 80) : 'metric')return (- <div className="relative flex flex-col w-full h-full min-h-[200px]">+ // A dashboard tile sets the height, so a minimum would overflow a short tile. Elsewhere the+ // parent can have no height, and a chart then needs the minimum to draw at all.+ <div+ className={cn(+ 'relative flex flex-col w-full h-full',+ props.context.insightProps?.dashboardId == null && 'min-h-[200px]'+ )}+ >{responseError && !responseLoading ? (<div className="flex-1 flex items-center p-4 min-w-0"><LemonBanner type="error" className="w-full">diff --git a/products/metrics/frontend/panels/MetricsPanel.test.tsx b/products/metrics/frontend/panels/MetricsPanel.test.tsxindex ee33e6308b59..140227941bf7 100644--- a/products/metrics/frontend/panels/MetricsPanel.test.tsx+++ b/products/metrics/frontend/panels/MetricsPanel.test.tsx@@ -94,9 +94,11 @@ describe('MetricsPanel', () => {afterEach(() => cleanup())- it('renders the stat headline with the resolved unit', () => {+ it('renders a single stat with the resolved unit, and no metric name or time at rest', () => {renderPanel([seriesWith({}, [100, 200, 340], 'http.duration', 'ms')], { type: 'stat' })expect(screen.getByText('340 ms')).toBeInTheDocument()+ expect(screen.queryByText('http.duration')).not.toBeInTheDocument()+ expect(screen.queryByText(/12:00/)).not.toBeInTheDocument()})it('stat uses the reduce reducer', () => {diff --git a/products/metrics/frontend/panels/StatPanel.tsx b/products/metrics/frontend/panels/StatPanel.tsxindex 299bf2189b3f..9c3653be3a95 100644--- a/products/metrics/frontend/panels/StatPanel.tsx+++ b/products/metrics/frontend/panels/StatPanel.tsx@@ -1,7 +1,12 @@+import { useValues } from 'kea'+import { MetricCard } from '@posthog/quill-charts'import { useChartTheme } from 'lib/charts/hooks'import { getColorVar } from 'lib/colors'+import { dayjs } from 'lib/dayjs'+import { cn } from 'lib/utils/css-classes'+import { teamLogic } from 'scenes/teamLogic'import { flattenSeriesRows } from './metricsReduce'import { thresholdColor } from './metricsThresholds'@@ -12,14 +17,22 @@ import { resolveReducer } from './registry'const FALLBACK_COLOR = 'data-color-1'/** Cap on grouped stat cards so a high-cardinality groupBy does not flood the tile. */const MAX_STAT_CARDS = 12+const GROUPED_SPARKLINE_HEIGHT = 40/** A headline number with a sparkline, colored by threshold. One card per series when the* query groups, capped at `MAX_STAT_CARDS`. */export function StatPanel({ series, display, fallbackName }: MetricsPanelProps): JSX.Element {const theme = useChartTheme()+ const { timezone } = useValues(teamLogic)const reducer = resolveReducer(display)// A series with no non-null point has nothing to headline; drop it rather than render a "—" card.const rows = flattenSeriesRows(series, [reducer]).filter((row) => row.values[reducer] !== null)+ // A single card fills the tile, and the tile title already names it. Grouped cards need their labels.+ const single = rows.length === 1++ if (rows.length === 0) {+ return <div className="flex h-full w-full items-center justify-center text-secondary text-sm">No data</div>+ }const cards = rows.slice(0, MAX_STAT_CARDS).map((row, index) => {const value = row.values[reducer] ?? null@@ -33,31 +46,39 @@ export function StatPanel({ series, display, fallbackName }: MetricsPanelProps):return (<MetricCardkey={index}- title={name}+ title={single ? null : name}value={value ?? undefined}data={row.series.points.map((p) => p.value ?? 0)}labels={row.series.points.map((p) => p.time)}+ formatLabel={(time) => dayjs(time).tz(timezone).format('D MMM HH:mm')}+ // The time shows only on hover. A blank caption at rest keeps its row, so the+ // sparkline does not resize under the cursor when the time appears.+ restingSubtitle={' '}theme={theme}color={color}formatValue={(v) => formatMetricValue(v, row.series.unit ?? undefined)}- sparklineFill+ headlineClassName="whitespace-nowrap text-2xl @min-[13rem]:text-3xl @min-[16rem]:text-4xl"+ changeInline+ sparklineFill={single}+ sparklineHeight={GROUPED_SPARKLINE_HEIGHT}+ sparklineClassName="mt-2"+ className={cn('@container min-w-0', single && 'h-full')}/>)})return (- <div className="flex h-full w-full flex-wrap content-start items-start gap-3 overflow-auto p-2">- {cards.length > 0 ? (- <>- {cards}- {rows.length > MAX_STAT_CARDS && (- <span className="text-xs text-secondary self-center">- and {rows.length - MAX_STAT_CARDS} more- </span>- )}- </>- ) : (- <div className="flex flex-1 items-center justify-center text-secondary text-sm">No data</div>+ <div+ className={cn(+ 'h-full w-full p-2',+ single+ ? 'flex overflow-hidden'+ : 'grid grid-cols-[repeat(auto-fill,minmax(12rem,1fr))] content-start gap-3 overflow-auto'+ )}+ >+ {cards}+ {rows.length > MAX_STAT_CARDS && (+ <span className="text-xs text-secondary self-center">and {rows.length - MAX_STAT_CARDS} more</span>)}</div>)