: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(hog-charts): add Metric component (#61006)
Sam Penningtoncf7911a5a84d
diff --git a/frontend/src/lib/hog-charts/blocks/Metric/Metric.test.tsx b/frontend/src/lib/hog-charts/blocks/Metric/Metric.test.tsxnew file mode 100644index 000000000000..970f122309aa--- /dev/null+++ b/frontend/src/lib/hog-charts/blocks/Metric/Metric.test.tsx@@ -0,0 +1,256 @@+import { render } from '@testing-library/react'++import type { ChartTheme } from '../../core/types'+import { renderHogChart, setupJsdom, setupSyncRaf } from '../../testing'+import { Metric, type MetricChange } from './Metric'++const THEME: ChartTheme = { colors: ['#22d3ee'], backgroundColor: '#ffffff' }+const LABELS = ['Jan', 'Feb', 'Mar', 'Apr']+const POSITIVE_COLOR = { background: 'rgb(0 200 0 / 10%)', foreground: '#008800' }+const NEGATIVE_COLOR = { background: 'rgb(200 0 0 / 10%)', foreground: '#aa0000' }++describe('Metric', () => {+ let teardownJsdom: () => void+ let teardownRaf: () => void++ beforeEach(() => {+ teardownJsdom = setupJsdom()+ teardownRaf = setupSyncRaf()+ })++ afterEach(() => {+ teardownRaf()+ teardownJsdom()+ })++ describe('with sparkline (data + theme)', () => {+ it('shows the last data point and label by default', () => {+ const { container } = renderHogChart(+ <Metric+ title="Total"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ formatValue={(v) => `$${Math.round(v)}`}+ />+ )+ expect(container.textContent).toContain('$400')+ expect(container.textContent).toContain('Apr')+ })++ it('renders a positive change pill when the series ends above the first non-zero value', () => {+ const { container } = renderHogChart(+ <Metric+ title="Total"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ formatValue={(v) => `$${Math.round(v)}`}+ />+ )+ expect(container.textContent).toContain('+300.0%')+ })++ it('renders a negative change pill when the series ends below the first value', () => {+ const { container } = renderHogChart(+ <Metric+ title="Total"+ data={[400, 300, 200, 100]}+ labels={LABELS}+ theme={THEME}+ formatValue={(v) => `$${Math.round(v)}`}+ />+ )+ expect(container.textContent).toContain('-75.0%')+ })++ it('skips the change pill when showChange is false', () => {+ const { container } = renderHogChart(+ <Metric title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} showChange={false} />+ )+ expect(container.textContent).not.toContain('%')+ })++ it('omits the change pill when the first non-zero value is undefined', () => {+ const { container } = renderHogChart(+ <Metric title="Total" data={[0, 0, 0]} labels={['Jan', 'Feb', 'Mar']} theme={THEME} />+ )+ expect(container.textContent).not.toContain('%')+ })++ it('renders nothing when data is empty and no value is supplied', () => {+ const { container } = render(<Metric title="Total" data={[]} labels={[]} theme={THEME} />)+ expect(container.textContent).toBe('')+ })++ it('uses Math.abs in the denominator so a negative baseline still reads as a rise', () => {+ const { container } = renderHogChart(+ <Metric+ title="Total"+ data={[-100, 0, 100]}+ labels={['Jan', 'Feb', 'Mar']}+ theme={THEME}+ formatValue={(v) => `${Math.round(v)}`}+ />+ )+ expect(container.textContent).toContain('+200.0%')+ })++ it('updates the headline value and label when hovering a different point', () => {+ const { container, chart } = renderHogChart(+ <Metric+ title="Total"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ animationMs={0}+ formatValue={(v) => `$${Math.round(v)}`}+ />+ )+ chart.hoverAtIndex(1)+ expect(container.textContent).toContain('$200')+ expect(container.textContent).toContain('Feb')+ })++ it('headlines the supplied `value` at rest while the chart still draws from `data`', () => {+ const { container, chart } = renderHogChart(+ <Metric+ title="Revenue"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ animationMs={0}+ value={9999}+ formatValue={(v) => `$${Math.round(v)}`}+ />+ )+ expect(container.textContent).toContain('$9999')+ expect(container.querySelector('canvas')).not.toBeNull()+ chart.hoverAtIndex(2)+ expect(container.textContent).toContain('$300')+ })++ it('renders a supplied `change` pill fixed across hover', () => {+ const { container, chart } = renderHogChart(+ <Metric+ title="Revenue"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ animationMs={0}+ change={{ value: 12.5, label: '+12.5% vs. last week' }}+ formatValue={(v) => `$${Math.round(v)}`}+ />+ )+ expect(container.textContent).toContain('+12.5% vs. last week')+ chart.hoverAtIndex(0)+ expect(container.textContent).toContain('+12.5% vs. last week')+ expect(container.textContent).not.toContain('+300.0%')+ })++ it('formats a supplied `change` via `formatChange` when no label is provided', () => {+ const { container } = renderHogChart(+ <Metric+ title="Revenue"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ animationMs={0}+ change={{ value: -8 }}+ />+ )+ expect(container.textContent).toContain('-8.0%')+ })++ it('suppresses the pill when change is null', () => {+ const { container } = renderHogChart(+ <Metric+ title="Revenue"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ animationMs={0}+ change={null}+ />+ )+ expect(container.textContent).not.toContain('%')+ })++ it('uses the supplied subtitle in place of the hover-driven label', () => {+ const { container } = renderHogChart(+ <Metric+ title="Revenue"+ data={[100, 200, 300, 400]}+ labels={LABELS}+ theme={THEME}+ animationMs={0}+ subtitle="Last 12 months"+ />+ )+ expect(container.textContent).toContain('Last 12 months')+ expect(container.textContent).not.toContain('Apr')+ })+ })++ describe('number-only (no data)', () => {+ it('renders the formatted value without a sparkline', () => {+ const { container } = render(+ <Metric title="Revenue" value={8800} formatValue={(v) => `$${v.toLocaleString()}`} />+ )+ expect(container.textContent).toContain('Revenue')+ expect(container.textContent).toContain('$8,800')+ expect(container.querySelector('canvas')).toBeNull()+ })++ it('renders nothing when neither `value` nor `data` is supplied', () => {+ const { container } = render(<Metric title="Revenue" />)+ expect(container.textContent).toBe('')+ })++ it.each<{ name: string; change: MetricChange; goodDirection?: 'up' | 'down'; expectedColor: string }>([+ {+ name: 'positive change uses the positive color',+ change: { value: 12.5, label: '+12.5%' },+ expectedColor: 'rgb(0, 136, 0)',+ },+ {+ name: 'negative change uses the negative color',+ change: { value: -4.2, label: '-4.2%' },+ expectedColor: 'rgb(170, 0, 0)',+ },+ {+ name: 'negative change flips to the positive color when goodDirection is "down"',+ change: { value: -1.2, label: '-1.2%' },+ goodDirection: 'down',+ expectedColor: 'rgb(0, 136, 0)',+ },+ ])('$name', ({ change, goodDirection, expectedColor }) => {+ const { container } = render(+ <Metric+ title="Revenue"+ value={8800}+ change={change}+ goodDirection={goodDirection}+ positiveColor={POSITIVE_COLOR}+ negativeColor={NEGATIVE_COLOR}+ />+ )+ expect(container.textContent).toContain(change.label)+ const pill = container.querySelector('.rounded-full') as HTMLElement | null+ expect(pill?.style.color).toBe(expectedColor)+ })++ it('points the change chevron down for a negative change', () => {+ const { container } = render(+ <Metric title="Revenue" value={8800} change={{ value: -4.2, label: '-4.2%' }} />+ )+ const chevron = container.querySelector('.rounded-full svg')+ expect(chevron?.getAttribute('class')).toContain('rotate-180')+ })++ it('applies dataAttr to the root', () => {+ const { container } = render(<Metric title="Revenue" value={8800} dataAttr="metric-revenue" />)+ expect(container.querySelector('[data-attr="metric-revenue"]')).not.toBeNull()+ })+ })+})diff --git a/frontend/src/lib/hog-charts/blocks/Metric/Metric.tsx b/frontend/src/lib/hog-charts/blocks/Metric/Metric.tsxnew file mode 100644index 000000000000..2313fab4d5f3--- /dev/null+++ b/frontend/src/lib/hog-charts/blocks/Metric/Metric.tsx@@ -0,0 +1,181 @@+import React, { useMemo, useState } from 'react'++import { Sparkline } from '../../charts/Sparkline/Sparkline'+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import type { ChartTheme } from '../../core/types'+import { percentage } from '../../utils/format'+import { type MetricChange, resolveDelta } from './resolveDelta'+import { useAnimatedNumber } from './useAnimatedNumber'++export type { MetricChange }++export interface ChangeColor {+ background: string+ foreground: string+}++export interface MetricProps {+ title: React.ReactNode+ /** Resting headline number. Defaults to `data[data.length - 1]` when `data` is present;+ * required when `data` is empty or omitted. */+ value?: number+ /** Series values. When present, a sparkline renders below the headline and hovering a point+ * swaps the headline. */+ data?: number[]+ /** Labels paired with `data`. Used for the default subtitle on hover. */+ labels?: string[]+ /** Required when `data` is present. */+ theme?: ChartTheme+ /** Sparkline line + fill color. Falls back to `theme.colors[0]`. */+ color?: string+ sparklineHeight?: number+ sparklineFillOpacity?: number+ sparklineClassName?: string+ formatValue?: (value: number) => string+ formatChange?: (percent: number) => string+ showChange?: boolean+ /** Fixed comparison pill. Supplied → no hover-driven fallback. Pass `null` to suppress. */+ change?: MetricChange | null+ goodDirection?: 'up' | 'down'+ positiveColor?: ChangeColor+ negativeColor?: ChangeColor+ /** Caption under the headline. Defaults to `labels[activeIndex]` when a sparkline is present. */+ subtitle?: React.ReactNode+ animationMs?: number+ className?: string+ dataAttr?: string+ onError?: (error: Error, info: React.ErrorInfo) => void+}++const DEFAULT_POSITIVE_COLOR: ChangeColor = { background: 'rgb(56 134 0 / 10%)', foreground: '#388600' }+const DEFAULT_NEGATIVE_COLOR: ChangeColor = { background: 'rgb(219 55 7 / 10%)', foreground: '#db3707' }++const DEFAULT_FORMAT_VALUE = (v: number): string => v.toLocaleString()+const DEFAULT_FORMAT_CHANGE = (p: number): string => {+ const formatted = percentage(p / 100, 1, true)+ return p > 0 ? `+${formatted}` : formatted+}++export function Metric(props: MetricProps): React.ReactElement | null {+ const { onError, ...rest } = props+ return (+ <ChartErrorBoundary onError={onError}>+ <MetricInner {...rest} />+ </ChartErrorBoundary>+ )+}++function MetricInner({+ title,+ value,+ data,+ labels,+ theme,+ color,+ sparklineHeight = 120,+ sparklineFillOpacity = 0.35,+ sparklineClassName = 'mt-4',+ formatValue = DEFAULT_FORMAT_VALUE,+ formatChange = DEFAULT_FORMAT_CHANGE,+ showChange = true,+ change,+ goodDirection = 'up',+ positiveColor = DEFAULT_POSITIVE_COLOR,+ negativeColor = DEFAULT_NEGATIVE_COLOR,+ subtitle,+ animationMs = 350,+ className,+ dataAttr,+}: Omit<MetricProps, 'onError'>): React.ReactElement | null {+ const sparklineData = data != null && data.length > 0 && theme != null ? data : null+ const lastIndex = sparklineData ? sparklineData.length - 1 : -1++ const [hoverIndex, setHoverIndex] = useState(-1)+ const activeIndex = hoverIndex >= 0 ? hoverIndex : lastIndex++ const restingValue = value ?? (sparklineData ? sparklineData[lastIndex] : undefined)+ const animationTarget = sparklineData && hoverIndex >= 0 ? (sparklineData[hoverIndex] ?? 0) : (restingValue ?? 0)+ const animatedValue = useAnimatedNumber(animationTarget, animationMs)++ const baselineValue = useMemo(() => sparklineData?.find((v) => v !== 0 && Number.isFinite(v)), [sparklineData])++ if (restingValue == null) {+ return null+ }++ const liveValue = sparklineData ? (sparklineData[activeIndex] ?? 0) : restingValue+ const fallbackChangePercent =+ sparklineData == null || baselineValue == null+ ? null+ : ((liveValue - baselineValue) / Math.abs(baselineValue)) * 100++ const delta = resolveDelta({ showChange, change, fallbackChangePercent, formatChange })+ const headlineDisplay = sparklineData ? formatValue(animatedValue) : formatValue(restingValue)+ const resolvedSubtitle = subtitle ?? labels?.[activeIndex] ?? ' '++ const positive = delta != null && delta.value >= 0+ const isGood = goodDirection === 'up' ? positive : !positive+ const pillColors = isGood ? positiveColor : negativeColor++ return (+ <div className={`flex flex-col w-full ${className ?? ''}`} data-attr={dataAttr}>+ <div className="flex items-start justify-between gap-2">+ <div className="text-sm font-medium">{title}</div>+ {delta != null && <ChangePill positive={positive} label={delta.label} colors={pillColors} />}+ </div>++ <div className="mt-2 text-4xl font-bold tracking-tight tabular-nums">{headlineDisplay}</div>++ <div className="mt-1 text-sm opacity-60">{resolvedSubtitle}</div>++ {sparklineData && theme && (+ <Sparkline+ data={sparklineData}+ labels={labels}+ theme={theme}+ color={color}+ height={sparklineHeight}+ fillOpacity={sparklineFillOpacity}+ onHoverIndexChange={setHoverIndex}+ className={sparklineClassName}+ />+ )}+ </div>+ )+}++interface ChangePillProps {+ positive: boolean+ label: React.ReactNode+ colors: ChangeColor+}++function ChangePill({ positive, label, colors }: ChangePillProps): React.ReactElement {+ return (+ <div+ className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium transition-colors"+ style={{ background: colors.background, color: colors.foreground }}+ >+ <Chevron up={positive} />+ <span className="tabular-nums">{label}</span>+ </div>+ )+}++function Chevron({ up }: { up: boolean }): React.ReactElement {+ return (+ <svg+ width="10"+ height="10"+ viewBox="0 0 10 10"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={up ? '' : 'rotate-180'}+ >+ <path d="M2 6.5 L5 3.5 L8 6.5" />+ </svg>+ )+}diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.tsindex 13f73c2d4c74..6e944b296aef 100644--- a/frontend/src/lib/hog-charts/index.ts+++ b/frontend/src/lib/hog-charts/index.ts@@ -16,6 +16,8 @@ export { TimeSeriesBarChart } from './charts/TimeSeriesBarChart/TimeSeriesBarChaexport type { TimeSeriesBarChartConfig, TimeSeriesBarChartProps } from './charts/TimeSeriesBarChart/TimeSeriesBarChart'export { Sparkline } from './charts/Sparkline/Sparkline'export type { SparklineProps } from './charts/Sparkline/Sparkline'+export { Metric } from './blocks/Metric/Metric'+export type { ChangeColor, MetricChange, MetricProps } from './blocks/Metric/Metric'// Base chart (for building new chart types)export { Chart } from './core/Chart'