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.

chore(quill): move metric tiles to Metric and deprecate MetricCard (#127450)

Sam Penningtonf372c5b86813
diff --git a/.agents/skills/visualizing-change-over-time/SKILL.md b/.agents/skills/visualizing-change-over-time/SKILL.md
index 3c7b5a5c8e47..ceb3bd09eb6d 100644
--- a/.agents/skills/visualizing-change-over-time/SKILL.md
+++ b/.agents/skills/visualizing-change-over-time/SKILL.md
@@ -29,7 +29,7 @@ Present the fitting option(s) and let the user choose — none of these is manda
| A continuous series over many time points (a trend) | `TimeSeriesLineChart` / `LineChart` (area fill for emphasis) | The standard trend; the slope between every pair of points is visible. |
| **Two points only** (before → after) across **several series/categories** | **`SlopeChart`** | One line per entity from a left "before" to a right "after" — direction and magnitude of each entity's change, and rank flips, read at a glance. |
| Magnitude comparison at points in time (not the path between them) | `BarChart` / `TimeSeriesBarChart` | Bars compare discrete values; group/stack for sub-series. |
-| A single headline number plus its change vs a prior period | `MetricCard` | Big number + sparkline + change pill. |
+| A single headline number plus its change vs a prior period | `Metric` (`@posthog/quill-components/metric`) | Big number + sparkline + change pill. |
If the user is comparing exactly **two snapshots** (this week vs last, control vs
treatment, Q1 vs Q2) and especially when there are **many categories** whose
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 70e8a59cd1af..759ab92096e1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4209,9 +4209,9 @@ snapshots:
insights-sqlbargraph--stacked-bar-with-negative-values--light:
hash: v1.k794b7964.e9f32e35e60194c76df1aad0e7963ca99bc76d2b6099437c5e679c4959feb976.3DeROLuvQPwEHmWPIxoY7SxfXAcAgX6gufInnDLnBh0
insights-sqlmetriccard--default--dark:
- hash: v1.k794b7964.76f4e3c4cd2804af666f0468d31072602124556d82aa223b6660cd97271f4caa.928VYvoGe3aVu00xSR4wclIUv-vp_qsvqn8BKWUsDBQ
+ hash: v1.k794b7964.9225791400a6ac2d881d4e7b92ff69a158e3e9b903786ed6077732030f994d59.uTTlyytUgIYw97Kab3KkaWuY5-qWU40BQeSgQc6um1o
insights-sqlmetriccard--default--light:
- hash: v1.k794b7964.1ad68ec9b7d4211384f53994f7abdc82065e2c801e22332589f4a60f1590b761.GR_EaYQlS2zbCj74wsiYr8BbKZmtoI016arf1ZcA28c
+ hash: v1.k794b7964.81061ab73233684b5b8c7e6bb9a70075c0f67c4a9e92c0866d93d9b1268903f6.zY_PZr762IwBWvEPyx826H-FT7GZ3NowxICs9s_-TYQ
insights-sqlpiegraph--breakdown-colors--dark:
hash: v1.k794b7964.01928cb0ffb1554a01ffae8f214773557e22647fea676e40007a7803cec0af32.fk7qZ2CtcV_Ouq_6xOxJ7wqRdxmck-P18wvqRq1jLsc
insights-sqlpiegraph--breakdown-colors--light:
@@ -11235,13 +11235,13 @@ snapshots:
scenes-app-engineering-analytics-lead-time-box-plot--horizontal-log-scale--light:
hash: v1.k794b7964.51d3c36ffda14d8d1c136dc4e5ec71c9b6965ea3ae8b93491449025310fe1d20.eapX8C-c-f3G3tV0WKMG84Df1eNYen34zEiVgkHtmno
scenes-app-engineering-analytics-pull-request--merged--dark:
- hash: v1.k794b7964.914da66b8ffcd2d304504ee64f546d481a086f850a595453eac277776709a5f8.lRLNQnprlC-abPDRUnVoIsQdk3RrVERdN-r9yixuN7M
+ hash: v1.k794b7964.45aa00198707a34956711fe7897f2a1abb6fe233d051a154167c58ba72ec8272.Hcl1ss2I9T0q8Gc2ZD95SuxWq7edYuSPQRfbkWFw5bg
scenes-app-engineering-analytics-pull-request--merged--light:
- hash: v1.k794b7964.341faee45938a8f6e8f5bebf7d084d5cdbcc7167f936a9650faec95045075c61.dn9TGnxHEk5KJWSHuMY2q7AB4_hkGL3-1bKs7eRnruU
+ hash: v1.k794b7964.a9454c27de3433f338bf6a38c79e42dde407116ab5cb27e26142ad18d6e3c17f.yNx66xHxNkGHcnlgyI_fndwE_lylr5it885oLvQ3lVQ
scenes-app-engineering-analytics-pull-request--out-of-the-merge-queue--dark:
- hash: v1.k794b7964.93978802c42af2797d05a301adfe70d194d33f3e0702525c5e7661ace6c5cfe3.m62m19bjRUDWr9gYD9QWEv8GwNN1-Fjy3CSodAnv050
+ hash: v1.k794b7964.0164c8af353cda89894f253377b5c1945e314690ce2f72f84c13778a5516eda0.UCZYtmrs56jsSOydmUJxKkJHLzCZFy7tBfg6dHIGBwQ
scenes-app-engineering-analytics-pull-request--out-of-the-merge-queue--light:
- hash: v1.k794b7964.6797fcc13df425c50c66c660ac6db3d4dd8474b41a47d0b09a1670b469efd81f.fPK07aqVd8TZO06FptD5tbBRFhJRw1JnJ4DrUYHkISM
+ hash: v1.k794b7964.a651d2a0468c4c78356aa38543e198e1b55571ebc7000bd5fabd919a0823db3f.QTFNJOnK8DBJEoIRWQrhIwYAHhXCyFsUfGYI_Gbvpmk
scenes-app-engineering-analytics-pull-request--section-load-errors--dark:
hash: v1.k794b7964.97e7bcdeea9686784229086d09b943f4228fbb41a4f8255932df388ca98e1e9e.y0wF4Trm7Vu1BWmenoIA0-1ZaL4U5e4gXQfvI-ZqxfU
scenes-app-engineering-analytics-pull-request--section-load-errors--light:
@@ -11299,17 +11299,17 @@ snapshots:
scenes-app-engineering-analytics-tests--trunk-quarantine-debt-owners-unavailable--light:
hash: v1.k794b7964.70bc2ea4a5fcd54507b2dfabcc07f590c62cce10b526a0ed280528ecbceea69b.iWeEYnBFIGrt7LXKgREcgR-zbrDUOw5_60buXfMetZ4
scenes-app-engineering-analytics-workflow--workflow-detail--dark:
- hash: v1.k794b7964.ed63cba05c3a1c2d6b7dc9b6441aac22e0d6dc988c7012fd074f12822ec5cbca.6zKD-NymQGqdyyeFHU9TPVEBlS9GtMTJnLXpB431ELE
+ hash: v1.k794b7964.2ed87726705d8ae895d7826eea9b2f4da737194b19e4c6024edd379c2035b46b.BUWfL65hb8LdLy2rBmUWiit0CvaxYIY46gA1-o3rSTo
scenes-app-engineering-analytics-workflow--workflow-detail--light:
- hash: v1.k794b7964.bb503cbb4f6ee08e34c92e80b227f54591ead62e84841c18924afcd3599ccd1b._zHPcoT_vIZB1LrL6RT2mh7oLmbZMeaXKGObUi7ZvuM
+ hash: v1.k794b7964.f56932b640fd21c724497ca13240018478a052921402f85c333a33a13d82d7a2.AUXHafrEBMxt8vFB-OPu55OdhK-eaduHkUS_MinY6W4
scenes-app-engineering-analytics-workflow--workflow-detail-scoped-to-pull-requests--dark:
- hash: v1.k794b7964.1896c52142144d82af5db567bd08cf4bd87e11e2dc489c6e913fc503b83653a7.afFZpV5zRDFsJfZIUzW_9NcRiqkKedD5yrBgZAVHf7E
+ hash: v1.k794b7964.a29c10f9901de695bc86aa07ab6cfadd1bf142c4b1b08b82943b6134382bee54.Apx4QZCVHl1KhZWsC_R68C0HIUsOZz0D89nVgq_-kb4
scenes-app-engineering-analytics-workflow--workflow-detail-scoped-to-pull-requests--light:
- hash: v1.k794b7964.e28db48aeba4771cb18ef4ff388ba0aba3045aaf2f9d622c384b0b2b10f16f1f.8vHMuh1LeR1QDvmgRxtdc3Kuxz1mBsdn2xnGcyDK8V8
+ hash: v1.k794b7964.464bcf527efdb52af1db911d79a17e40552dc8df81aa5dfd72eebc91e60f829a.CPqx4bs9F_2UIFT9zDU8qywFWGhBnex4j9QA0i2gF7E
scenes-app-engineering-analytics-workflow--workflow-detail-section-load-errors--dark:
- hash: v1.k794b7964.f778b874ef5ab671500a6743a4550d815d63ff2a9dedad4bbb311b252b64ef16._LJoKtU2xCtL3ikMrqPbjaMnE_0wxr9-xc-4t2wbyA4
+ hash: v1.k794b7964.d1669585fb02d1f54af703a9d84be0ac3c89cecfc0a893ae848675637664eb73.EnZw19_XxRjOynQpzNIHaZNsnzWjDKh5WPdY2TdaXDo
scenes-app-engineering-analytics-workflow--workflow-detail-section-load-errors--light:
- hash: v1.k794b7964.54bd5d744f9ff16d43d5476daa93c4c8af0f2fdc466a00c49479421f1dbef642.2uK1j4cniblurwfUzmx3XF1wCcqHEbpSO9YncZXXmAw
+ hash: v1.k794b7964.237763794443471ccacc86fb1248bd0fee63791867c44146d1e384b0078a42ff.z9x-vhmcqrLZDIcLr0gkf1ZZ_40tVuDDKPEpJwiNJoY
scenes-app-engineering-analytics-workflow-run--depot-run--dark:
hash: v1.k794b7964.7ea4595766d44257b30d5d0761369a9b5d65fb550be19852a8ef4fa151189ed9.7X2-tDJWLvGhntaVuRxXKyAzkrXc7-sZxeThjhBbf-0
scenes-app-engineering-analytics-workflow-run--depot-run--light:
diff --git a/frontend/src/design.md b/frontend/src/design.md
index c7e78e15a19f..990ba954dcb3 100644
--- a/frontend/src/design.md
+++ b/frontend/src/design.md
@@ -121,7 +121,6 @@ Compose from the listed parts only. Part names are shown without their prefix (e
- Read `packages/quill/packages/charts/AGENTS.md` ("Choosing a chart") before using
- LineChart, BarChart, ScatterChart, ComboChart, FunnelChart, Sparkline
- TimeSeriesLineChart, TimeSeriesBarChart, TimeSeriesComboChart
-- MetricCard
### Blocks
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.test.tsx
index b4b70f7ae319..001a08d306fc 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.test.tsx
@@ -53,7 +53,7 @@ describe('SqlMetricCard', () => {
await waitFor(() => expect(screen.getByText('$1,500')).toBeInTheDocument())
expect(screen.getByText('Jan 3, 2026')).toBeInTheDocument()
- expect(container.querySelector('[data-attr="metric-card-sparkline"]')).toBeInTheDocument()
+ expect(container.querySelector('[data-attr="metric-sparkline"]')).toBeInTheDocument()
hoverAtIndex(getChart(container).element, 1, 3)
await waitFor(() => expect(screen.getByText('Jan 2, 2026')).toBeInTheDocument())
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.tsx
index 6bfb47080e2d..c4d8a45b130e 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard.tsx
@@ -1,6 +1,13 @@
import clsx from 'clsx'
-import { MetricCard } from '@posthog/quill-charts'
+import {
+ Metric,
+ MetricDelta,
+ MetricHeader,
+ MetricSparkline,
+ MetricSubtitle,
+ MetricValue,
+} from '@posthog/quill-components/metric'
import { makeChartErrorHandler } from 'lib/charts/chartErrorHandler'
import { useChartTheme } from 'lib/charts/hooks'
@@ -52,8 +59,8 @@ export const SqlMetricCard = ({
})}
>
{model ? (
- <MetricCard
- title={null}
+ <Metric
+ className="w-full px-0"
value={model.headlineValue}
data={model.data}
labels={model.labels}
@@ -69,14 +76,20 @@ export const SqlMetricCard = ({
metricSettings?.changeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR
)}
restingSubtitle={model.summary === 'latest' ? undefined : METRIC_SUMMARY_LABELS[model.summary]}
- changeInline
hoverChangeFromPreviousPoint
sparklineFill
- sparklineClassName="mt-4 -mx-3 -mb-3"
formatValue={(value) => formatSqlSeriesValue(value, model.series.settings)}
dataAttr="metric-value"
onError={handleChartError}
- />
+ >
+ {/* Wraps so a narrow card moves the pill under the number instead of clipping it. */}
+ <MetricHeader className="flex-wrap items-center">
+ <MetricValue />
+ <MetricDelta />
+ </MetricHeader>
+ <MetricSubtitle className="mt-1" />
+ <MetricSparkline className="mt-4 -mx-3 -mb-3" />
+ </Metric>
) : (
<InsightEmptyState sampleDataVariant="number" />
)}
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 8228ec802e02..832a78067637 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -25,9 +25,10 @@ This file is the map. Prop-level semantics live in the JSDoc on the config and p
| `SankeyChart` | Flow between stages (tool call journeys, user paths) — `nodes` + `links` keyed by id, no `series`; the graph must be acyclic |
| `SlopeChart` | Change between two points — one line per series, `data: [start, end]` |
| `Sparkline` | Tiny inline trend, no axes — gradient line or stacked bars; tooltip off by default |
-| `MetricCard` | Headline number + sparkline + change pill (dashboard stat tiles) |
| `Gauge` | One value against a min and max, colored by thresholds (Apdex, error budget, CPU); optional target tick |
+For a headline stat tile (number, change pill, sparkline), use `Metric` from `@posthog/quill-components/metric`.
+
Share of total over time takes a time-series chart in its 100% form: `TimeSeriesLineChart` with `fill` series and `percentStackView` for a stacked area, or `TimeSeriesBarChart` with `barLayout: 'percent'` for bars.
Pick the one that matches the design you are copying.
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
index a6f2fbca28f2..d172127b1b0b 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
@@ -19,6 +19,7 @@ import { useHoverIntent } from './useHoverIntent'
export type { MetricChange }
export type { ChangeColor }
+/** @deprecated Use `MetricProps` from `@posthog/quill-components/metric`. */
export interface MetricCardProps {
title: React.ReactNode
/** Resting headline number. Defaults to `data[data.length - 1]` when `data` is present;
@@ -80,6 +81,7 @@ export interface MetricCardProps {
onError?: (error: Error, info: React.ErrorInfo) => void
}
+/** @deprecated Use the composable `Metric` from `@posthog/quill-components/metric`. */
export function MetricCard(props: MetricCardProps): React.ReactElement | null {
return (
<ChartErrorBoundary onError={props.onError}>
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
index 261ab7f8478c..ffe19448d626 100644
--- a/packages/quill/packages/charts/src/docs/chart-types.md
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -194,6 +194,9 @@ Bars use `hitArea: 'band'`.
## MetricCard
+Deprecated: use `Metric` from `@posthog/quill-components/metric`.
+`MetricCard` stays only so apps that pin an older version can upgrade without a break.
+
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.
@@ -206,6 +209,5 @@ A left-aligned tile: headline number, change pill, sparkline.
- `changeTooltip` shows a styled hover tooltip on the change pill, using the host's tooltip surface tokens with chart-surface fallbacks.
- `change.value` is a percent, so `8` reads as +8%. Its sign sets the pill's direction, and `goodDirection` decides whether that direction is good. `change.label` replaces the formatted text, for example `+1.1 pts` for a change in percentage points.
-The composable form is `Metric` in `@posthog/quill-components` (it needs `Card` and `Badge` from primitives, which charts cannot depend on).
+`Metric` lives in `@posthog/quill-components` because it needs `Card` and `Badge` from primitives, which charts cannot depend on.
It is built on `Sparkline` plus the headless helpers this package exports: `resolveDelta` and `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell), and the `MetricChange` and `ResolvedDelta` types.
-Reach for `Metric` for a custom layout; use `MetricCard` for the default self-contained tile.
diff --git a/packages/quill/packages/components/AGENTS.md b/packages/quill/packages/components/AGENTS.md
index 61703e80d156..47857822fe3d 100644
--- a/packages/quill/packages/components/AGENTS.md
+++ b/packages/quill/packages/components/AGENTS.md
@@ -147,7 +147,7 @@ Headless month-grid state for building custom calendar UIs: returns `calendar` (
## Metric
-A composable stat tile: a headline number, a `Badge` change pill, and an optional `Sparkline`. `Metric` is **content, not a surface** — wrap it in `<Card flush>` for the border. It's the one component here that depends on `@posthog/quill-charts` (for `Sparkline` + the headless metric math), which pulls d3 — so it lives behind its own `@posthog/quill-components/metric` entry point, **not** the main barrel (and not the `@posthog/quill` umbrella). That keeps charts/d3 out of the always-eager app-shell graph: only code that imports the metric subpath pays for it. The `MetricCard` in `@posthog/quill-charts` is the older, self-contained (prop-driven, primitives-free) tile; use `Metric` when you want to compose the layout or lean on quill's `Card`/`Badge`.
+A composable stat tile: a headline number, a `Badge` change pill, and an optional `Sparkline`. `Metric` is **content, not a surface** — wrap it in `<Card flush>` for the border. It's the one component here that depends on `@posthog/quill-charts` (for `Sparkline` + the headless metric math), which pulls d3 — so it lives behind its own `@posthog/quill-components/metric` entry point, **not** the main barrel. That keeps charts/d3 out of the always-eager app-shell graph: only code that imports the metric subpath pays for it.
```tsx
import {
@@ -184,8 +184,8 @@ Rules:
- The root owns the data/hover behavior and feeds the parts via context — a part used outside `<Metric>` throws. Pass `value` for a number-only tile; pass `data`+`labels`+`theme` for a sparkline.
- `labels` doubles as the sparkline's x-scale keys, so entries must be **unique** — a duplicate collapses two points onto one position and draws the series backwards (see the charts guide's `labels` rule). Pass raw keys (ISO dates) and render them for display with `formatLabel`, instead of pre-formatting text like `'June 16'`, which repeats once a range spans a year. `formatLabel` covers the subtitle; a `sparklineTooltip` formats the same keys through the charts' own `labelFormatter`.
- `MetricDelta` renders a `Badge`; `goodDirection` (default `up`) decides success vs destructive. It carries its own `TooltipProvider`, so `changeTooltip` needs no app-root setup. resize via `className` (the metric insight passes its own larger-pill classes and puts it inline next to the headline via `MetricHeader`; there is no `changeInline` or size prop, compose and style at the call site).
-- Color the headline at the call site: `<MetricValue style={{ color }} />` for a dynamic color (a threshold status), or a `text-*` class for a token. The root `color` tints only the sparkline.
-- Reproduces `MetricCard`'s behavior (`restingSubtitle`, `hoverChangeFromPreviousPoint`, `changeTooltip`, `positiveColor`/`negativeColor` for user-configured pill colors); omit the color props to keep the semantic `Badge` variants.
+- Color the headline with `valueColor`, a function of the shown value, so a hovered point gets its own color (a threshold status). For a fixed color use a `text-*` class on `MetricValue`. The root `color` tints only the sparkline.
+- Supports `restingSubtitle`, `hoverChangeFromPreviousPoint`, `changeTooltip`, and `positiveColor`/`negativeColor` for user-configured pill colors; omit the color props to keep the semantic `Badge` variants.
- `series` draws a multi-series sparkline (one line per series, the charts' `Series[]` shape) instead of the single `data` line. It's purely visual — the headline, hover and change pill still read `data`, so pass the numbers the tile should read (e.g. the per-index totals) as `data` alongside it; the types reject `series` without `data`. The single-line conveniences (`color`, `sparklineDashedFromIndex`) don't apply — set them per series.
- `sparklineTooltip` is a render prop passed straight to the sparkline (off by default, since hover already scrubs the headline) — supply `(ctx) => <DefaultTooltip {...ctx} />` to also show a hover tooltip, e.g. the per-series breakdown behind a multi-series total.
- Things `Metric` deliberately doesn't have props for — compose them yourself around it: a clickable tile (put the handler on the wrapping `Card`), a footer (a sibling node after `MetricSparkline`), an info icon next to the title (a `Tooltip` inside `MetricTitle`), and a loading state (render `Skeleton`s instead of the `Metric`).
diff --git a/packages/quill/packages/components/src/metric.test.tsx b/packages/quill/packages/components/src/metric.test.tsx
index 21bfcc2f13d0..a74fa18e3fc5 100644
--- a/packages/quill/packages/components/src/metric.test.tsx
+++ b/packages/quill/packages/components/src/metric.test.tsx
@@ -3,7 +3,7 @@ import { render } from '@testing-library/react'
import type { ChartTheme } from '@posthog/quill-charts'
import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
-import { Metric, MetricSubtitle } from './metric'
+import { Metric, MetricSparkline, MetricSubtitle, MetricValue } from './metric'
const THEME: ChartTheme = { colors: ['#22d3ee'], backgroundColor: '#ffffff' }
// Raw bucket keys, the shape a caller passes to keep the sparkline's x-scale keys unique.
@@ -32,4 +32,33 @@ describe('Metric', () => {
)
expect(container.textContent).toContain('bucket 2025-11-01')
})
+
+ it('colors the resting headline by the shown value, not the last point', () => {
+ const valueColor = jest.fn((value: number) => (value > 100 ? 'red' : 'green'))
+ const { getByTestId } = render(
+ <Metric value={120} data={[60, 60]} theme={THEME} valueColor={valueColor}>
+ <MetricValue data-attr="headline" />
+ </Metric>
+ )
+ expect(getByTestId('headline').style.color).toBe('red')
+ })
+
+ it('reports an error from its sparkline through onError', () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {})
+ // Only the base `Chart` reads `axisColor`, so the error starts inside the sparkline's own boundary.
+ const theme = {
+ ...THEME,
+ get axisColor(): string {
+ throw new Error('boom')
+ },
+ } as ChartTheme
+ const onError = jest.fn()
+ render(
+ <Metric data={[1, 2, 3]} theme={theme} onError={onError}>
+ <MetricSparkline />
+ </Metric>
+ )
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }), expect.anything())
+ jest.mocked(console.error).mockRestore()
+ })
})
diff --git a/packages/quill/packages/components/src/metric.tsx b/packages/quill/packages/components/src/metric.tsx
index 372cbe32281f..3634195cf580 100644
--- a/packages/quill/packages/components/src/metric.tsx
+++ b/packages/quill/packages/components/src/metric.tsx
@@ -24,6 +24,7 @@ export type { ChangeColor, MetricChange }
interface MetricContextValue {
/** Formatted headline — already follows the hovered sparkline point. */
headlineDisplay: string
+ headlineColor?: string
/** Resolved caption (subtitle override → resting subtitle at rest → hovered label). */
subtitle: React.ReactNode
/** The change pill's resolved state, or null when there is nothing to show. */
@@ -50,6 +51,7 @@ interface MetricContextValue {
dashedFromIndex?: number
setHoverIndex: (index: number) => void
tooltip?: (ctx: TooltipContext) => React.ReactNode
+ onError?: (error: Error, info: React.ErrorInfo) => void
} | null
}
@@ -95,6 +97,8 @@ interface MetricBaseProps {
/** Tooltip renderer for the sparkline. Off by default — hovering already scrubs the headline. */
sparklineTooltip?: (ctx: TooltipContext) => React.ReactNode
formatValue?: (value: number) => string
+ /** Headline color for the value it shows, so a hovered point gets its own color (a threshold status). */
+ valueColor?: (value: number) => string | undefined
formatChange?: (percent: number) => string
showChange?: boolean
/** Fixed comparison pill. Supplied → no hover-driven fallback. Pass `null` to suppress. */
@@ -163,10 +167,9 @@ export type MetricProps = MetricBaseProps &
* ```
*/
export function Metric(props: MetricProps): React.ReactElement | null {
- const { onError, ...rest } = props
return (
- <ChartErrorBoundary onError={onError}>
- <MetricInner {...rest} />
+ <ChartErrorBoundary onError={props.onError}>
+ <MetricInner {...props} />
</ChartErrorBoundary>
)
}
@@ -185,6 +188,7 @@ function MetricInner({
sparklineDashedFromIndex,
sparklineTooltip,
formatValue = DEFAULT_FORMAT_VALUE,
+ valueColor,
formatChange = DEFAULT_FORMAT_CHANGE,
showChange = true,
change,
@@ -199,8 +203,9 @@ function MetricInner({
hoverIntentMs = 60,
className,
dataAttr,
+ onError,
children,
-}: Omit<MetricBaseProps, 'onError'> & {
+}: MetricBaseProps & {
data?: number[]
series?: Series[]
}): React.ReactElement | null {
@@ -251,6 +256,7 @@ function MetricInner({
return {
headlineDisplay: sparklineData ? formatValue(animatedValue) : formatValue(restingValue),
+ headlineColor: valueColor?.(animationTarget),
subtitle: subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : labelCaption),
change:
delta != null
@@ -276,6 +282,7 @@ function MetricInner({
dashedFromIndex: sparklineDashedFromIndex,
setHoverIndex,
tooltip: sparklineTooltip,
+ onError,
}
: null,
}
@@ -294,6 +301,8 @@ function MetricInner({
positiveColor,
negativeColor,
formatValue,
+ valueColor,
+ animationTarget,
animatedValue,
subtitle,
restingSubtitle,
@@ -307,6 +316,7 @@ function MetricInner({
sparklineFillOpacity,
sparklineDashedFromIndex,
sparklineTooltip,
+ onError,
])
if (ctx == null) {
@@ -343,14 +353,15 @@ export const MetricTitle = React.forwardRef<HTMLDivElement, React.ComponentProps
/** Headline number. Follows the hovered sparkline point; pass `children` to render your own, or a
* `text-*` class to resize it (cn lets your size win over the default `text-4xl`). */
export const MetricValue = React.forwardRef<HTMLDivElement, React.ComponentProps<'div'>>(function MetricValue(
- { className, children, ...props },
+ { className, children, style, ...props },
ref
) {
- const { headlineDisplay } = useMetric('MetricValue')
+ const { headlineDisplay, headlineColor } = useMetric('MetricValue')
return (
<div
ref={ref}
className={cn('min-w-0 truncate text-4xl font-bold tracking-tight tabular-nums', className)}
+ style={{ color: headlineColor, ...style }}
{...props}
>
{children ?? headlineDisplay}
@@ -446,6 +457,7 @@ export function MetricSparkline({
tooltip={sparkline.tooltip}
className={cn('relative top-[6px]', pinBottom, className)}
dataAttr="metric-sparkline"
+ onError={sparkline.onError}
/>
)
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fe7262b940b0..7df7defb9dcd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3712,6 +3712,9 @@ importers:
'@posthog/quill-charts':
specifier: workspace:*
version: link:../../packages/quill/packages/charts
+ '@posthog/quill-components':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/components
'@storybook/react':
specifier: 'catalog:'
@@ -4465,6 +4468,9 @@ importers:
'@posthog/quill-charts':
specifier: workspace:*
version: link:../../packages/quill/packages/charts
+ '@posthog/quill-components':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/components
'@types/react':
specifier: 18.3.27
version: 18.3.27
diff --git a/products/engineering_analytics/frontend/AGENTS.md b/products/engineering_analytics/frontend/AGENTS.md
index 9ed6c1aefcfc..ee795bb098df 100644
--- a/products/engineering_analytics/frontend/AGENTS.md
+++ b/products/engineering_analytics/frontend/AGENTS.md
@@ -26,5 +26,5 @@ UI grammar for every scene in this product. `frontend/src/AGENTS.md` and the rep
## Components and copy
-- Lemon for all UI chrome; `@posthog/quill-charts` only for data viz (charts, the `MetricCard` pill). Never raw `@posthog/quill` primitives on the current UI. UI behind the `today-rail-nav` feature flag uses quill and follows [`frontend/src/design.md`](../../../frontend/src/design.md).
+- Lemon for all UI chrome; `@posthog/quill-charts` only for data viz (charts), and `Metric` from `@posthog/quill-components/metric` for headline stat tiles. Never raw `@posthog/quill` primitives on the current UI. UI behind the `today-rail-nav` feature flag uses quill and follows [`frontend/src/design.md`](../../../frontend/src/design.md).
- No boilerplate subheader paragraphs under section titles. Method caveats go in column and card tooltips; the scene subtitle is one plain line.
diff --git a/products/engineering_analytics/frontend/components/MetricTile.tsx b/products/engineering_analytics/frontend/components/MetricTile.tsx
index 357c54d3db0d..502f504492e2 100644
--- a/products/engineering_analytics/frontend/components/MetricTile.tsx
+++ b/products/engineering_analytics/frontend/components/MetricTile.tsx
@@ -1,11 +1,11 @@
-// Headline-metric tile: label · value · caption, rendered with quill's MetricCard inside the
+// Headline-metric tile: label · value · caption, rendered with quill's Metric inside the
// product's card chrome. It carries no delta, because a window comparison renders as
// WindowComparisonCard.
import { ReactNode } from 'react'
import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
-import { MetricCard } from '@posthog/quill-charts'
+import { Metric, MetricSubtitle, MetricTitle, MetricValue } from '@posthog/quill-components/metric'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { cn } from 'lib/utils/css-classes'
@@ -97,7 +97,7 @@ export function MetricTile({
hoverEffect={false}
className={cn('flex min-w-44 flex-1 flex-col justify-center px-5 py-4', className)}
>
- {/* MetricCard has no loading prop; skeleton the whole tile on a genuine reload so it never
+ {/* Metric has no loading prop; skeleton the whole tile on a genuine reload so it never
flashes a stale/zero headline (the loading-states rule). */}
{loading ? (
<div className="flex flex-col gap-2 py-1">
@@ -105,14 +105,12 @@ export function MetricTile({
<LemonSkeleton className="h-7 w-20" />
</div>
) : (
- <MetricCard
- title={labelNode}
- // These tiles have no series data and often a non-numeric headline ("3 / 5", "2h 10m"),
- // so the pre-formatted display string rides through MetricCard's formatter.
- value={0}
- formatValue={() => value}
- subtitle={sub}
- />
+ // The headline is often non-numeric ("3 / 5", "2h 10m"), so it renders as children.
+ <Metric value={0} subtitle={sub} className="px-0">
+ <MetricTitle>{labelNode}</MetricTitle>
+ <MetricValue className="mt-2">{value}</MetricValue>
+ <MetricSubtitle className="mt-1" />
+ </Metric>
)}
</LemonCard>
)
diff --git a/products/engineering_analytics/frontend/components/StatCard.tsx b/products/engineering_analytics/frontend/components/StatCard.tsx
index 2868aef0c3a1..463d638a1a30 100644
--- a/products/engineering_analytics/frontend/components/StatCard.tsx
+++ b/products/engineering_analytics/frontend/components/StatCard.tsx
@@ -1,6 +1,6 @@
import { IconFilter } from '@posthog/icons'
import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
-import { MetricCard } from '@posthog/quill-charts'
+import { Metric, MetricSubtitle, MetricTitle, MetricValue } from '@posthog/quill-components/metric'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyNumber } from 'lib/utils/numbers'
@@ -103,14 +103,11 @@ export function StatCard({
<LemonSkeleton className="h-9 w-20" />
</>
) : (
- <MetricCard
- title={<span className={active ? 'text-accent' : undefined}>{label}</span>}
- // Pre-formatted display string ('—' when no data yet) rides through the formatter.
- value={0}
- formatValue={() => value}
- change={null}
- subtitle={caption}
- />
+ <Metric value={0} subtitle={caption} className="px-0">
+ <MetricTitle className={active ? 'text-accent' : undefined}>{label}</MetricTitle>
+ <MetricValue className="mt-2">{value}</MetricValue>
+ <MetricSubtitle className="mt-1" />
+ </Metric>
)
if (!onClick) {
return (
diff --git a/products/engineering_analytics/package.json b/products/engineering_analytics/package.json
index c83c919fac2b..2e09af0fa899 100644
--- a/products/engineering_analytics/package.json
+++ b/products/engineering_analytics/package.json
@@ -8,6 +8,7 @@
"@posthog/icons": "catalog:",
"@posthog/quill": "workspace:*",
"@posthog/quill-charts": "workspace:*",
+ "@posthog/quill-components": "workspace:*",
"kea": "catalog:",
"kea-loaders": "catalog:",
"kea-router": "catalog:",
diff --git a/products/metrics/frontend/panels/StatPanel.tsx b/products/metrics/frontend/panels/StatPanel.tsx
index 198bf1f4f936..28984018512d 100644
--- a/products/metrics/frontend/panels/StatPanel.tsx
+++ b/products/metrics/frontend/panels/StatPanel.tsx
@@ -1,6 +1,14 @@
import { useValues } from 'kea'
-import { MetricCard } from '@posthog/quill-charts'
+import {
+ Metric,
+ MetricDelta,
+ MetricHeader,
+ MetricSparkline,
+ MetricSubtitle,
+ MetricTitle,
+ MetricValue,
+} from '@posthog/quill-components/metric'
import { useChartTheme } from 'lib/charts/hooks'
import { getColorVar } from 'lib/colors'
@@ -29,6 +37,9 @@ export function StatPanel({ series, display, fallbackName }: MetricsPanelProps):
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
+ const valueColor = display.thresholds?.length
+ ? (v: number): string => getColorVar(thresholdColor(v, display.thresholds, FALLBACK_COLOR))
+ : undefined
if (rows.length === 0) {
return <div className="flex h-full w-full items-center justify-center text-secondary text-sm">No data</div>
@@ -47,9 +58,8 @@ export function StatPanel({ series, display, fallbackName }: MetricsPanelProps):
// The headline shows the hovered sparkline point, so it shares one scale with every point.
const formatValue = metricValuesFormatter(row.series.unit ?? undefined, [...data, value ?? 0])
return (
- <MetricCard
+ <Metric
key={index}
- title={single ? null : name}
value={value ?? undefined}
data={data}
labels={row.series.points.map((p) => p.time)}
@@ -60,13 +70,19 @@ export function StatPanel({ series, display, fallbackName }: MetricsPanelProps):
theme={theme}
color={color}
formatValue={formatValue}
- headlineClassName="whitespace-nowrap text-2xl @min-[13rem]:text-3xl @min-[16rem]:text-4xl"
- changeInline
+ valueColor={valueColor}
sparklineFill={single}
sparklineHeight={GROUPED_SPARKLINE_HEIGHT}
- sparklineClassName="mt-2"
- className={cn('@container min-w-0', single && 'h-full')}
- />
+ className="@container w-full min-w-0 px-0"
+ >
+ {!single && <MetricTitle>{name}</MetricTitle>}
+ <MetricHeader className={cn('flex-wrap items-center', !single && 'mt-2')}>
+ <MetricValue className="text-2xl @min-[13rem]:text-3xl @min-[16rem]:text-4xl" />
+ <MetricDelta />
+ </MetricHeader>
+ <MetricSubtitle className="mt-1" />
+ <MetricSparkline className="mt-2" />
+ </Metric>
)
})
diff --git a/products/metrics/package.json b/products/metrics/package.json
index c4daff342439..ca4ece7438b2 100644
--- a/products/metrics/package.json
+++ b/products/metrics/package.json
@@ -7,6 +7,7 @@
"dependencies": {
"@posthog/quill": "workspace:*",
"@posthog/quill-charts": "workspace:*",
+ "@posthog/quill-components": "workspace:*",
"kea": "catalog:",
"kea-loaders": "catalog:",
"kea-router": "catalog:",