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(insights): add Metric trends display type (#63907)

Sam Pennington92a0f304a4c2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index bc9a45f16351..31e433da7fa7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -693,17 +693,17 @@ snapshots:
components-hogcharts-linechart--with-zeros-and-negatives--light:
hash: v1.k794b7964.0f3eb38f28bf8a2ce7e0a386f87e2045b257a6ce75d6d11b5b1117c15e529026.02OMElAdKYjGyK-3S9OEMaOwrasxW8MN2vMpKA7ioIc
components-hogcharts-metriccard--default--dark:
- hash: v1.k794b7964.fdae35f43c62ef56c1b5b6a1f20c8276484e1715434a643e69f84fdb0bc13050.palMcesa0sPp_jjblGpdBuLNhAv0-Ay_frIrM4PpDWw
+ hash: v1.k794b7964.3861290ba0f09405b66f9b73364e9873016b1272c20f7c1bd8b35f2fa3d1bff7.HPFksQG41dayiFaYQKOKR1Frx5tSi4GMzKer6rKExeU
components-hogcharts-metriccard--default--light:
- hash: v1.k794b7964.258352110d21296ef4cd99b01e3c4a247137e0a489e3f28f7843e94e5ac5e001.ThpcqSIeItEkBI8KSjHIV6iKcyk3tiLQwGPeDtdFVN0
+ hash: v1.k794b7964.28f1733b2dbd4267ee4c749bfc0f0609fee3d6508302c4bf060615606fc6a879.r6AH1LqJPooXWLlrEyXmvO75VOP_o8yKhx3Qfq8rHP4
components-hogcharts-metriccard--falling--dark:
- hash: v1.k794b7964.b583bc0c2260089501d342928145ebf29c2ecd19a877ef070754f92cf5704a6c.OBsoY8oour3ycVg-1e_MEbuIaoBXHE3T4SNoOkwppOk
+ hash: v1.k794b7964.d6540f839923dacec7185415d7d8b5cb065e8d6514041fbfdd83b226dc993cf4.qXWVNsCEUsOo1vhn1YiXI9gQq0uKl9oUN5IJ5265d4g
components-hogcharts-metriccard--falling--light:
- hash: v1.k794b7964.90a5d170cef7d14bde3db12bf121df5dc7f9199f94b07ece8893c86a2e85107d.sM10Ln2LBoEAXnbpcV-obeQ04UntfoJ5oD_zDieUo_c
+ hash: v1.k794b7964.258db964f84a31bfe604b19b1bfb9faa03bb98f41136c7188a2ea3db073a322b.GdxdeW4lJgAwqkeyyM94DlUkLOYIwP4OLkMN7qmqc6o
components-hogcharts-metriccard--no-change--dark:
- hash: v1.k794b7964.dee982acd6e60ffeb36299d80d748fed4ed8fc6fadf930d62741d70a58fbe7a5.xE0QTdSRilMkACw_Uypmi5JgF4OumpYgJnH83Sle8vE
+ hash: v1.k794b7964.cc7000b2031ab73a0922b493c62d140608f8f06ec054a5e6ecfa953967e4c0c9.Ee6vIwPcI14qimH2HuHvuUauqJlGIKsLv4tuIq_j-kg
components-hogcharts-metriccard--no-change--light:
- hash: v1.k794b7964.bf3bd811a81a6d0a618b7b98478390a0510e96feef9b020d41379148c214f2ec.hi_YI79MhU2Z1ITkwnURxMH25lrPAdHv-v9g0WGieJw
+ hash: v1.k794b7964.d2967882a54924264558605a9d2dd879ec2aada58eebe897494699cfb060f719.NBuxT533CmhoHdiuuCsdNp_LgFh5FwREvoncmnOeDYs
components-hogcharts-metriccard--number-only--dark:
hash: v1.k794b7964.a09b8609071d1aaa038a5ed7981d94669e8640c2a877d11d9b70000482987c3e.JKqQfzNlh19Y1ZHWiGcl5jw6-g0pFjoFk7dClPCCa0w
components-hogcharts-metriccard--number-only--light:
@@ -789,25 +789,25 @@ snapshots:
components-hogcharts-slopechart--without-series-labels--light:
hash: v1.k794b7964.5f4ed4bd2e8b76a9146d4cec772a9dec098f1d101bbfff9eb7c2de542807ee36.B4F1sc0cdH3SMp-rPFHfd4VnivUHhH2neom0RghB0Ng
components-hogcharts-sparkline--custom-color--dark:
- hash: v1.k794b7964.9a599ca7e855408c1bda17c3b9094b60c333249c9df7d14d0be865a4f9fb424d.EFS4alrXA5COnCpJYXUfVxFvJd4GWClskV2utoqKWtE
+ hash: v1.k794b7964.fe78efe136cddcd6eb3b35c161f9ea1ab15383c31a7406f12fd66726d4ec37e9.1CoDmn7MkL3aQvQLXIWLG6CE4jgEm6T3uHEFOJzeAhg
components-hogcharts-sparkline--custom-color--light:
- hash: v1.k794b7964.af97dc25575ee74487ebf3ded42aff5af86b9133469c0bf7654047c03e52542f.QjZCQYpkNyOBPZ6m_zB8aK_JG6vRYRgDAjioFndEGQ8
+ hash: v1.k794b7964.468fecacb45ea8e63973f76a879eef808f745f88113678934d126924d407741d.Cuo6Lex3pAK_pWz8dkHh5gfvcJcQHY1GpmAhyN0FCQo
components-hogcharts-sparkline--default--dark:
- hash: v1.k794b7964.bbfe7f33815104ae340c50cf548833104ee7a6ac5177f596dc7cb8ed883974ee.VmAFZptKWU8izuAm82dpb0nFv1fNO1Y69T7mBPm95RY
+ hash: v1.k794b7964.111f64658c7df79aea9f2214d2e8d03dddeda94d29c45c4658fdd9adaaed6499.07Eo_oViC9lEI0N83KI0vmTztjuNOxIXQSsT2t8l7EY
components-hogcharts-sparkline--default--light:
- hash: v1.k794b7964.86f4f5f914b7abc96f0eec6db7ee2b341d938b98245e73a4140821dff2e18948.xGf_AmD32h-OLyy8VOZYZQju67R19WGKMCKuKONpI1A
+ hash: v1.k794b7964.b620c4de95000d73bfae09022e7da415f67615d3a66c15d99d301ce15e29fa12.VIwiFznYrEOgit8uRgmsKOCNYRPUrQTgUjS1lOZ2ndw
components-hogcharts-sparkline--fill-opacity-variants--dark:
- hash: v1.k794b7964.cf8c9b6982bebc81204d5dcc711c45690f3b8fed7f088730bde95ad154f0a850.eT0oRxwQLdyqGJKeMa2X-ZkYoDJfmUjeA_7iXT3Zfrw
+ hash: v1.k794b7964.89f2d89aa6db2d26ce5188d8be395a71230db4de4fa94ae4ff6c799891ab1916.gPGmCU8XTPT-_rr5E-Qam3oH0q63R1GadKjOvCcMKLI
components-hogcharts-sparkline--fill-opacity-variants--light:
- hash: v1.k794b7964.b1a6e56ad4416d4d324d2b2acc026040453b4ea7151d6f4933354d875b040265.TCskBkXRQIIGxeP1TVg5gtlv03_fbl0bgjBjs5B472U
+ hash: v1.k794b7964.5d41f35d49fae0715f8ed0932bd934097993f89a425f54d9391654bf7668f14e.TNHaw2gdTs_0MOa849tIyWjPRH_-8azEm6kHKJMhFyA
components-hogcharts-sparkline--flat--dark:
- hash: v1.k794b7964.f59b778cbf14145daebb90deda9e4d6e43b39f37db39652065faa4bd6dc78d56.Bg-gXDV14nTLdohXrehOyHFXNI6qaRjZaQOdQ8qYopY
+ hash: v1.k794b7964.53fdc0d3c494d1ed89587f0c1867c77a2793f4e5bd02775451e3fa50080c3223.1q18RKBU3X_MI1FXD9koGx5irEnkztXov4yG-jFzNOw
components-hogcharts-sparkline--flat--light:
- hash: v1.k794b7964.2d4a2093d64f5f8764d7c8c0305ac1e3954c7e6153800997dffbc583acff03c2.U6ySgBGnwKgJll1d0uPKeb7Z8MBxmsflJ7eN6oRlQJ8
+ hash: v1.k794b7964.d786a4e2f7f586efb844c69f4c8469218df01fc8cb8fcf4f062f91cd901901e5.SktIyoMHAw_PGyJT-MFUaQ7wN_3QKUedaAU9mt9LUTM
components-hogcharts-sparkline--volatile--dark:
- hash: v1.k794b7964.4840b4db90794f9305ff9b1fc6d68eb7132b4dab0ffb1180b34711373d8afa9f.JkLiHnw1a2oCYKLSeI-XwZ-HO7zUWZ-ZMqW_dbkJHr0
+ hash: v1.k794b7964.78c5852a35d0712e541e43742c092734fae98c4211006e5cd32de0008485092c.JRPUzMhsTjR1kj7t_k6dmc3J3afFEnp5MhYokgKnwok
components-hogcharts-sparkline--volatile--light:
- hash: v1.k794b7964.a1c48718d5430b6c2be309c3b421caa6bb880a2f7291452723b4d506ec2bf8b9.l0afGkktvS_ulydwlBchwKA0ClsF2c1C_qDXeRPhMFU
+ hash: v1.k794b7964.43ae770e9ade45be47b529127a9836a97f508a6157f08ec81c81dd38bfbf1120.ZTO1dJnuVbYebO8PRQhm2TFf4Nwpdx5Vf--u-kHMDv4
components-hogcharts-timeseriesbarchart--basic--dark:
hash: v1.k794b7964.98e874c250b931d9740a75031a5b831d9da41a26fda196017a4053b861eb9175.LlBI3eDk6YXzQciqnB_0uyYzKN2lWpKq0Jbq2E0yg-4
components-hogcharts-timeseriesbarchart--basic--light:
@@ -5508,6 +5508,14 @@ snapshots:
hash: v1.k794b7964.a44e0ceccf278166f1813212b79e536cb88844f3d1d344c16de7b27a7e22f922.0K9H7VtJOtggpNtwlrIBHV2Tbe_V1VvkL_K44SIT6R8
scenes-app-insights-trendsboxplot--trends-box-plot-edit--light:
hash: v1.k794b7964.7357d5bc4368db2240237131335e8b44a5a153211856a611267638fd4a389a4b.r3ZcjHo4heeqDVbloPPMqezcIa6OhFmVi5QnWLsQ2iw
+ scenes-app-insights-trendsmetric--trends-metric--dark:
+ hash: v1.k794b7964.78702e7b3a96182cce0f0093fd66d6a6b3ca7d9a61cda74804a033eb2a19d1e2.SnoS_KhAKCQGWymkhwtZ8ygxj2FzF-GN7Gm5HF36m5U
+ scenes-app-insights-trendsmetric--trends-metric--light:
+ hash: v1.k794b7964.b10fade93852ef1aee28349f66d294eea60679613154dfe2ec8275c41ceaa1e5.1VA5kRv9PTPPo2JsE9IRux68ErPP_lMA-nBjsezc47I
+ scenes-app-insights-trendsmetric--trends-metric-edit--dark:
+ hash: v1.k794b7964.957dbfd7fd5b3f7510b51c464a35605745b266f8ca63503b64364d15b4d77787.a0bKcs8Bh_bOBQvPrHTL_mov6TFcCJcg9Af_z6ZIAa4
+ scenes-app-insights-trendsmetric--trends-metric-edit--light:
+ hash: v1.k794b7964.0e72de519e0e573ebbcc5a288110f9ceaa9dc7263fbf67740e54d29e1c5d8cc7.lSOvCInp4FxiQs9_TUcneesPfcILOl7IzP12esglg6s
scenes-app-insights-trendspie--trends-world-map--dark:
hash: v1.k794b7964.7c2513dd39a38ed590ab0ece1c30ff2eab34ed2c60599de28f90a3e698961c1e.BjXUZxRmeRGqVc-DkahiGNwhDsIQRdLm5xQhd1ykhXk
scenes-app-insights-trendspie--trends-world-map--light:
@@ -5709,9 +5717,9 @@ snapshots:
scenes-app-mcp-analytics-dashboard-cards--flagged-sessions--light:
hash: v1.k794b7964.52a1b29f817077e0d8452260716e950f063e206bd90d35c7be58ba72e93f13de.awEggL6KzFFucKT1Dd055i2oacGHM1WnHCSYHOwxQIo
scenes-app-mcp-analytics-dashboard-cards--key-metrics--dark:
- hash: v1.k794b7964.a8702a279540c2b5948595e182262c46a5aab9cfa8ed7537835771f4bf72542c.2VmeQEIAddJRjB0JGkg3gy-SPb5xiNeRrjUdPUyI0O0
+ hash: v1.k794b7964.30a761d8a47452414e6f158ad50484885f81394fb58c075ff1f2e66c36c1fe6e.bV_JfGaoE60VA3pGReyVwyQ23zmdaaflqKtTyQVTeq4
scenes-app-mcp-analytics-dashboard-cards--key-metrics--light:
- hash: v1.k794b7964.c78e0996ca8f257caa690c14f798aa30a3d6c184e268a4e66258d8e35248238d.--SI4BHWCCEKaTk33AtDEjh5BifMpWBcPFmO2FF4EfE
+ hash: v1.k794b7964.376099d576081c78dc740e794c25f4094489df28bac5fd4727422ca36635adee.GA6VOP1ygkbjHOeReQaUqZNIhU_LdIirGX3H_t9mMy8
scenes-app-mcp-analytics-dashboard-cards--share-by-harness--dark:
hash: v1.k794b7964.91754923c079ce0c9fc46b83fe672ee4f967701bde08562b80fee6cacdbeeb01.eWYTt2AnIb5vZmQehDXCSkxR03Ld6ryyA6rYoyG-J1g
scenes-app-mcp-analytics-dashboard-cards--share-by-harness--light:
@@ -7209,9 +7217,9 @@ snapshots:
web-analytics-overview-metric-cards--with-warning--light:
hash: v1.k794b7964.513140f3a07e4bce5f44fe469685b1b3d8270eb15bc29e5007d49b9e9c06778f.ixsQR_vjrm4XqsSY5V0WPPZYMsIl4KgtDJAGoICmsCU
web-analytics-overview-metric-cards--without-comparison--dark:
- hash: v1.k794b7964.8825120f2b27646cf45cc0d8d0542c5ee1e3507e0655206e73545189bd1f1dbb.cVd8lH8I8g1jIhadVw5d8usNH1QRh6yv2CIVuOguaBU
+ hash: v1.k794b7964.6256127079d73599075d80b4dd048e219b5680fea37104d73369f8cb63c2dcff.G2BH1b594qhZtpUvCZwHTinaAW5GxEU2SE31eozqqAM
web-analytics-overview-metric-cards--without-comparison--light:
- hash: v1.k794b7964.3dd39840375b4273c7da065e98ac10275ab343d5984f83ae5f4592c2f40f938a.7gkGGhVI0N8ieih821st4MUfXsiQWjGKu0HyQQzOJ2A
+ hash: v1.k794b7964.73465d052a3505e6cc989e5ebfd8a2e12d8c83ff6c98132b28ab30443d303268.S1rfkPzFjQc9Z-PR3_9sfM2P2l40ISgqiP5ygkabAaw
web-analytics-tile-skeletons--chart--dark:
hash: v1.k794b7964.7aa1344291af29b3bea21b1b4fc2962bf865899c63cb8137383d5d6e941a96bf.AElvCuEYtP-fom9VLZcolkkA-soqOxUPJLSlN1SB4NE
web-analytics-tile-skeletons--chart--light:
diff --git a/frontend/src/lib/components/Cards/InsightCard/annotationsToggle.ts b/frontend/src/lib/components/Cards/InsightCard/annotationsToggle.ts
index 53af6dfc8593..f9f543fba027 100644
--- a/frontend/src/lib/components/Cards/InsightCard/annotationsToggle.ts
+++ b/frontend/src/lib/components/Cards/InsightCard/annotationsToggle.ts
@@ -13,7 +13,7 @@ export function canToggleAnnotationsInInsightQuery(query: QueryBasedInsightModel
const source = query.source
if (isTrendsQuery(source)) {
const display = source.trendsFilter?.display || ChartDisplayType.ActionsLineGraph
- return !NON_TIME_SERIES_DISPLAY_TYPES.includes(display)
+ return display !== ChartDisplayType.Metric && !NON_TIME_SERIES_DISPLAY_TYPES.includes(display)
}
if (isFunnelsQuery(source)) {
diff --git a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
index 935f14d5e3de..dfd721befa4b 100644
--- a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
+++ b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
@@ -144,6 +144,22 @@ export function ChartFilter(): JSX.Element {
),
disabledReason: trendsOnlyDisabledReason || singleSeriesOnlyDisabledReason,
},
+ ...(featureFlags[FEATURE_FLAGS.METRIC_INSIGHT]
+ ? [
+ {
+ value: ChartDisplayType.Metric,
+ icon: <IconTrends />,
+ label: 'Metric',
+ labelInMenu: (
+ <ChartFilterOptionLabel
+ label="Metric"
+ description="A headline value with a sparkline and period-over-period change."
+ />
+ ),
+ disabledReason: trendsOnlyDisabledReason || singleSeriesOnlyDisabledReason,
+ },
+ ]
+ : []),
{
value: ChartDisplayType.ActionsPie,
icon: <IconPieChart />,
diff --git a/frontend/src/lib/components/InsightLegend/utils.ts b/frontend/src/lib/components/InsightLegend/utils.ts
index 84148d246ef7..ffd46d953a85 100644
--- a/frontend/src/lib/components/InsightLegend/utils.ts
+++ b/frontend/src/lib/components/InsightLegend/utils.ts
@@ -4,6 +4,7 @@ export const DISPLAY_TYPES_WITHOUT_LEGEND = [
ChartDisplayType.WorldMap,
ChartDisplayType.ActionsTable,
ChartDisplayType.BoldNumber,
+ ChartDisplayType.Metric,
ChartDisplayType.ActionsBarValue,
]
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 65203219ad20..44896e2ffc04 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -12,6 +12,7 @@ export const DISPLAY_TYPES_TO_CATEGORIES: Record<ChartDisplayType, ChartDisplayC
[ChartDisplayType.ActionsAreaGraph]: ChartDisplayCategory.TimeSeries,
[ChartDisplayType.ActionsLineGraphCumulative]: ChartDisplayCategory.CumulativeTimeSeries,
[ChartDisplayType.BoldNumber]: ChartDisplayCategory.TotalValue,
+ [ChartDisplayType.Metric]: ChartDisplayCategory.TimeSeries,
[ChartDisplayType.ActionsPie]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.ActionsBarValue]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.ActionsTable]: ChartDisplayCategory.TotalValue,
@@ -30,6 +31,7 @@ export const NON_TIME_SERIES_DISPLAY_TYPES = Object.entries(DISPLAY_TYPES_TO_CAT
/** Display types for which `breakdown` is hidden and ignored. Sync with backend NON_BREAKDOWN_DISPLAY_TYPES. */
export const NON_BREAKDOWN_DISPLAY_TYPES = [
ChartDisplayType.BoldNumber,
+ ChartDisplayType.Metric,
ChartDisplayType.CalendarHeatmap,
ChartDisplayType.TwoDimensionalHeatmap,
ChartDisplayType.BoxPlot,
@@ -38,6 +40,7 @@ export const NON_BREAKDOWN_DISPLAY_TYPES = [
export const SINGLE_SERIES_DISPLAY_TYPES = [
ChartDisplayType.WorldMap,
ChartDisplayType.BoldNumber,
+ ChartDisplayType.Metric,
ChartDisplayType.CalendarHeatmap,
ChartDisplayType.TwoDimensionalHeatmap,
]
@@ -46,6 +49,7 @@ export const NON_VALUES_ON_SERIES_DISPLAY_TYPES = [
ChartDisplayType.ActionsTable,
ChartDisplayType.WorldMap,
ChartDisplayType.BoldNumber,
+ ChartDisplayType.Metric,
ChartDisplayType.CalendarHeatmap,
ChartDisplayType.TwoDimensionalHeatmap,
]
@@ -193,6 +197,7 @@ export const FEATURE_FLAGS = {
BATCH_EXPORTS_POSTHOG_HTTP: 'posthog-http-batch-exports', // owner: #team-batch-exports
BILLING_SKIP_FORECASTING: 'billing-skip-forecasting', // owner: @zach
BOX_PLOT_INSIGHT: 'box-plot-insight', // owner: @pauldambra #team-product-analytics
+ METRIC_INSIGHT: 'metric-insight', // owner: @sampennington #team-product-analytics
CALENDAR_HEATMAP_INSIGHT: 'calendar-heatmap-insight', // owner: @jabahamondes #team-web-analytics
COOKIELESS_SERVER_HASH_MODE_SETTING: 'cookieless-server-hash-mode-setting', // owner: #team-web-analytics
EXPERIMENT_INTERVAL_TIMESERIES: 'experiments-interval-timeseries', // owner: @jurajmajerik #team-experiments
diff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/trendsMetric.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/trendsMetric.json
new file mode 100644
index 000000000000..40472e38325f
--- /dev/null
+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/trendsMetric.json
@@ -0,0 +1,278 @@
+{
+ "id": 9999001,
+ "short_id": "metric01",
+ "name": "Metric",
+ "derived_name": null,
+ "filters": {
+ "display": "Metric"
+ },
+ "filters_hash": "cache_42127776c1709f7c4209cea8925faefd",
+ "order": null,
+ "deleted": false,
+ "dashboard": null,
+ "layouts": {},
+ "color": null,
+ "last_refresh": null,
+ "refreshing": false,
+ "result": [
+ {
+ "action": {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ },
+ "label": "$pageview",
+ "count": 61010,
+ "data": [
+ 0,
+ 0,
+ 0,
+ 15625,
+ 22870,
+ 15044,
+ 6675,
+ 796
+ ],
+ "labels": [
+ "4-Mar-2022",
+ "5-Mar-2022",
+ "6-Mar-2022",
+ "7-Mar-2022",
+ "8-Mar-2022",
+ "9-Mar-2022",
+ "10-Mar-2022",
+ "11-Mar-2022"
+ ],
+ "days": [
+ "2022-03-04",
+ "2022-03-05",
+ "2022-03-06",
+ "2022-03-07",
+ "2022-03-08",
+ "2022-03-09",
+ "2022-03-10",
+ "2022-03-11"
+ ],
+ "persons_urls": [
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-04",
+ "date_to": "2022-03-04"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-04&date_to=2022-03-04&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-05",
+ "date_to": "2022-03-05"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-05&date_to=2022-03-05&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-06",
+ "date_to": "2022-03-06"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-06&date_to=2022-03-06&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-07",
+ "date_to": "2022-03-07"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-07&date_to=2022-03-07&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-08",
+ "date_to": "2022-03-08"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-08&date_to=2022-03-08&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-09",
+ "date_to": "2022-03-09"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-09&date_to=2022-03-09&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-10",
+ "date_to": "2022-03-10"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-10&date_to=2022-03-10&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-11",
+ "date_to": "2022-03-11"
+ },
+ "url": "api/projects/1/persons/trends/?date_from=2022-03-11&date_to=2022-03-11&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events"
+ }
+ ],
+ "filter": {
+ "display": "ActionsLineGraph",
+ "events": [
+ {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ }
+ ],
+ "insight": "TRENDS",
+ "interval": "day"
+ }
+ }
+ ],
+ "created_at": "2022-03-15T21:31:00.192917Z",
+ "created_by": {
+ "id": 1,
+ "uuid": "017f7913-c1ee-0000-faff-0fe5ace3849a",
+ "distinct_id": "Q1OD2NmnqqbqrLR45mYm2p1VNNbSO9DBFsMig90GWkK",
+ "first_name": "Marius",
+ "email": "[email protected]"
+ },
+ "description": "",
+ "updated_at": "2022-03-15T21:31:04.623891Z",
+ "tags": [],
+ "favorited": false,
+ "saved": true,
+ "last_modified_at": "2022-03-15T21:31:04.619654Z",
+ "last_modified_by": {
+ "id": 1,
+ "uuid": "017f7913-c1ee-0000-faff-0fe5ace3849a",
+ "distinct_id": "Q1OD2NmnqqbqrLR45mYm2p1VNNbSO9DBFsMig90GWkK",
+ "first_name": "Marius",
+ "email": "[email protected]"
+ },
+ "is_sample": false,
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "dateRange": {
+ "date_from": "-8w"
+ },
+ "interval": "week",
+ "kind": "TrendsQuery",
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "key": "$current_url",
+ "operator": "exact",
+ "type": "event",
+ "value": [
+ "https://hedgebox.net/signup/"
+ ]
+ },
+ {
+ "key": "$geoip_country_code",
+ "operator": "exact",
+ "type": "event",
+ "value": [
+ "PY"
+ ]
+ }
+ ]
+ },
+ {
+ "type": "OR",
+ "values": [
+ {
+ "key": "$browser",
+ "operator": "icontains",
+ "type": "event",
+ "value": "XX"
+ },
+ {
+ "key": "$session_duration",
+ "operator": "exact",
+ "type": "session",
+ "value": 3.0
+ },
+ {
+ "key": "selector",
+ "operator": "exact",
+ "type": "element",
+ "value": [
+ "href"
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "series": [
+ {
+ "custom_name": "Pageviews",
+ "event": "$pageview",
+ "kind": "EventsNode",
+ "math": "total",
+ "name": "$pageview",
+ "properties": [
+ {
+ "key": "from_invite",
+ "operator": "exact",
+ "type": "event",
+ "value": [
+ "false"
+ ]
+ },
+ {
+ "key": "$referrer",
+ "operator": "is_not_set",
+ "type": "event",
+ "value": "is_not_set"
+ }
+ ]
+ }
+ ],
+ "trendsFilter": {
+ "display": "Metric",
+ "resultCustomizationBy": "value"
+ },
+ "version": 2
+ },
+ "full": true
+ }
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
index 788d507b40ab..2808d3751476 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
@@ -26,6 +26,7 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element
[ChartDisplayType.ActionsAreaGraph]: 'Area chart',
[ChartDisplayType.ActionsLineGraphCumulative]: 'Cumulative line chart',
[ChartDisplayType.BoldNumber]: 'Big number',
+ [ChartDisplayType.Metric]: 'Metric',
[ChartDisplayType.ActionsPie]: 'Pie chart',
[ChartDisplayType.ActionsBarValue]: 'Value chart',
[ChartDisplayType.ActionsTable]: 'Table',
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index f12ec598a4f8..d859e8821bb0 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -25,6 +25,7 @@ import { HideIncompleteConversionWindowPeriodsFilter } from 'scenes/insights/Edi
import { HideWeekendsFilter } from 'scenes/insights/EditorFilters/HideWeekendsFilter'
import { LifecyclePercentagesFilter } from 'scenes/insights/EditorFilters/LifecyclePercentagesFilter'
import { LifecycleStackingFilter } from 'scenes/insights/EditorFilters/LifecycleStackingFilter'
+import { MetricColorFilter, MetricShowChangeFilter } from 'scenes/insights/EditorFilters/MetricFilters'
import { PercentStackViewFilter } from 'scenes/insights/EditorFilters/PercentStackViewFilter'
import { ResultCustomizationByPicker } from 'scenes/insights/EditorFilters/ResultCustomizationByPicker'
import { ScalePicker } from 'scenes/insights/EditorFilters/ScalePicker'
@@ -121,11 +122,15 @@ export function InsightDisplayConfig(): JSX.Element {
const isSlopeGraph = display === ChartDisplayType.SlopeGraph
const funnelsCompareEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE]
+
+ const isMetric = display === ChartDisplayType.Metric
+ const hideContinuousChartOptions = isNonTimeSeriesDisplay || isMetric || isSlopeGraph
const showCompare =
(isTrends &&
display !== ChartDisplayType.ActionsAreaGraph &&
display !== ChartDisplayType.CalendarHeatmap &&
display !== ChartDisplayType.BoxPlot &&
+ !isMetric &&
!isSlopeGraph) ||
isStickiness ||
isWebAnalyticsInsightQuery(querySource) ||
@@ -140,9 +145,9 @@ export function InsightDisplayConfig(): JSX.Element {
(!display || display === ChartDisplayType.ActionsLineGraph || display === ChartDisplayType.ActionsAreaGraph) &&
!!interval &&
(smoothingOptions[interval]?.length ?? 0) > 0
- const showMultipleYAxesConfig = (isTrends || isStickiness) && !isNonTimeSeriesDisplay && !isSlopeGraph
- const showAlertThresholdLinesConfig = isTrends && !isNonTimeSeriesDisplay && !isSlopeGraph
- const showAnnotationsConfig = (isTrends && !isNonTimeSeriesDisplay && !isSlopeGraph) || isTrendsFunnel
+ const showMultipleYAxesConfig = (isTrends || isStickiness) && !hideContinuousChartOptions
+ const showAlertThresholdLinesConfig = isTrends && !hideContinuousChartOptions
+ const showAnnotationsConfig = (isTrends && !hideContinuousChartOptions) || isTrendsFunnel
const isLineDisplay = isDefaultTrendsLineDisplay(display, querySource) || displayMatches(display, LINE_DISPLAYS)
const isBarDisplay = displayMatches(display, BAR_DISPLAYS)
const isCumulativeLineDisplay = display === ChartDisplayType.ActionsLineGraphCumulative
@@ -227,6 +232,12 @@ export function InsightDisplayConfig(): JSX.Element {
? [{ label: () => <ShowLegendFilter /> }]
: []
: [
+ ...(isMetric
+ ? [
+ { label: () => <MetricShowChangeFilter /> },
+ { label: () => <MetricColorFilter /> },
+ ]
+ : []),
...(isLifecycle ? [{ label: () => <LifecycleStackingFilter /> }] : []),
...(supportsValueOnSeries ? [{ label: () => <ValueOnSeriesFilter /> }] : []),
...(isLifecycle ? [{ label: () => <LifecyclePercentagesFilter /> }] : []),
@@ -245,13 +256,13 @@ export function InsightDisplayConfig(): JSX.Element {
]
: []),
...(showMultipleYAxesConfig ? [{ label: () => <ShowMultipleYAxesFilter /> }] : []),
- ...((isTrends || isRetention || isTrendsFunnel) && !isNonTimeSeriesDisplay
+ ...((isTrends || isRetention || isTrendsFunnel) && !hideContinuousChartOptions
? [{ label: () => <ShowTrendLinesFilter /> }]
: []),
- ...(isTrendsFunnel && !isNonTimeSeriesDisplay
+ ...(isTrendsFunnel && !hideContinuousChartOptions
? [{ label: () => <HideIncompleteConversionWindowPeriodsFilter /> }]
: []),
- ...(isTrends && !isNonTimeSeriesDisplay && hideWeekendsEnabled
+ ...(isTrends && !hideContinuousChartOptions && hideWeekendsEnabled
? [{ label: () => <HideWeekendsFilter /> }]
: []),
...(showAnnotationsConfig ? [{ label: () => <ShowAnnotationsFilter /> }] : []),
@@ -284,7 +295,7 @@ export function InsightDisplayConfig(): JSX.Element {
},
]
: []),
- ...(!isNonTimeSeriesDisplay && isTrends && display !== ChartDisplayType.CalendarHeatmap && !isSlopeGraph
+ ...(!hideContinuousChartOptions && isTrends && display !== ChartDisplayType.CalendarHeatmap
? [
{
title: 'Y-axis scale',
@@ -422,7 +433,9 @@ export function InsightDisplayConfig(): JSX.Element {
(showAxisLabelsConfig && normalizeAxisLabel(trendsFilter?.yAxisLabel) ? 1 : 0) +
(showMultipleYAxes ? 1 : 0) +
(trendsFilter?.hideWeekends && hideWeekendsEnabled ? 1 : 0) +
- (showAnnotationsConfig && showAnnotations === false ? 1 : 0)
+ (showAnnotationsConfig && showAnnotations === false ? 1 : 0) +
+ (isMetric && trendsFilter?.metricShowChange === false ? 1 : 0) +
+ (isMetric && trendsFilter?.metricColorByDirection ? 1 : 0)
return (
<div
diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.scss b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
index 4acf3e4b7f9f..8fd8e8d6d0f9 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightViz.scss
+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
@@ -210,7 +210,8 @@
&--ActionsTable,
&--WorldMap,
- &--BoldNumber {
+ &--BoldNumber,
+ &--Metric {
min-height: auto;
margin: 0;
}
@@ -222,6 +223,11 @@
}
}
+// Drop the viz padding so the Metric sparkline can bleed to the card edges.
+.InsightVizDisplay__content:has(.Metric) {
+ padding: 0;
+}
+
.FunnelInsight {
display: flex;
flex: 1;
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 8b559bf64c4a..08d6121bf299 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -4183,6 +4183,10 @@
"const": "BoldNumber",
"type": "string"
},
+ {
+ "const": "Metric",
+ "type": "string"
+ },
{
"const": "ActionsPie",
"type": "string"
@@ -4306,6 +4310,7 @@
"ActionsAreaGraph",
"ActionsLineGraphCumulative",
"BoldNumber",
+ "Metric",
"ActionsPie",
"ActionsBarValue",
"ActionsTable",
@@ -11703,6 +11708,7 @@
"ActionsAreaGraph",
"ActionsLineGraphCumulative",
"BoldNumber",
+ "Metric",
"ActionsPie",
"ActionsBarValue",
"ActionsTable",
@@ -43529,6 +43535,32 @@
"default": false,
"type": "boolean"
},
+ "metricChangeDecreaseColor": {
+ "description": "Metric display: change pill color when the metric decreased. Defaults to red.",
+ "type": "string"
+ },
+ "metricChangeIncreaseColor": {
+ "description": "Metric display: change pill color when the metric increased. Defaults to green.",
+ "type": "string"
+ },
+ "metricColorByDirection": {
+ "default": false,
+ "description": "Metric display: color the sparkline by whether the metric increased or decreased.",
+ "type": "boolean"
+ },
+ "metricLineDecreaseColor": {
+ "description": "Metric display: line color when the metric decreased. Defaults to red.",
+ "type": "string"
+ },
+ "metricLineIncreaseColor": {
+ "description": "Metric display: line color when the metric increased. Defaults to green.",
+ "type": "string"
+ },
+ "metricShowChange": {
+ "default": true,
+ "description": "Show the period-over-period change pill on the Metric display.",
+ "type": "boolean"
+ },
"minDecimalPlaces": {
"type": "number"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index ccf4a4ec8e82..86d862d87f0d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1493,6 +1493,20 @@ export type TrendsFilter = {
hideWeekends?: boolean
/** @default true */
showAnnotations?: boolean
+ /** Show the period-over-period change pill on the Metric display.
+ * @default true */
+ metricShowChange?: boolean
+ /** Metric display: change pill color when the metric increased. Defaults to green. */
+ metricChangeIncreaseColor?: string
+ /** Metric display: change pill color when the metric decreased. Defaults to red. */
+ metricChangeDecreaseColor?: string
+ /** Metric display: color the sparkline by whether the metric increased or decreased.
+ * @default false */
+ metricColorByDirection?: boolean
+ /** Metric display: line color when the metric increased. Defaults to green. */
+ metricLineIncreaseColor?: string
+ /** Metric display: line color when the metric decreased. Defaults to red. */
+ metricLineDecreaseColor?: string
}
export type CalendarHeatmapFilter = {
@@ -1525,6 +1539,12 @@ export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>([
'excludeBoxPlotOutliers',
'hideWeekends',
'showAnnotations',
+ 'metricShowChange',
+ 'metricChangeIncreaseColor',
+ 'metricChangeDecreaseColor',
+ 'metricColorByDirection',
+ 'metricLineIncreaseColor',
+ 'metricLineDecreaseColor',
])
export interface BoxPlotDatum {
diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.ts
index bf6671e254b9..54068f8f8f4f 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.ts
@@ -206,6 +206,9 @@ export const calculateLayouts = (
} else if (isTrendsQuery(query) && query.trendsFilter?.display === ChartDisplayType.BoldNumber) {
defaultW = 2
defaultH = 2
+ } else if (isTrendsQuery(query) && query.trendsFilter?.display === ChartDisplayType.Metric) {
+ defaultW = 3
+ defaultH = 3
}
// Single-column layout width override
if (breakpoint === 'xs') {
diff --git a/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx b/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx
new file mode 100644
index 000000000000..fe45b4ca728b
--- /dev/null
+++ b/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx
@@ -0,0 +1,109 @@
+import { useActions, useValues } from 'kea'
+
+import { getSeriesColorPalette } from 'lib/colors'
+import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
+import { LemonColorPicker } from 'lib/lemon-ui/LemonColor'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import {
+ METRIC_COLOR_BY_DIRECTION_DEFAULT,
+ METRIC_DEFAULT_DECREASE_COLOR,
+ METRIC_DEFAULT_INCREASE_COLOR,
+ METRIC_SHOW_CHANGE_DEFAULT,
+} from 'scenes/insights/views/Metric/Metric.utils'
+
+import { insightLogic } from '../insightLogic'
+
+const PRESET_COLORS = getSeriesColorPalette()
+
+function DirectionColorPickers({
+ increaseColor,
+ decreaseColor,
+ onIncrease,
+ onDecrease,
+}: {
+ increaseColor: string
+ decreaseColor: string
+ onIncrease: (color: string) => void
+ onDecrease: (color: string) => void
+}): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1 pl-5">
+ <div className="flex items-center justify-between gap-2 p-1 px-2">
+ <span className="font-normal">Increase</span>
+ <LemonColorPicker
+ colors={PRESET_COLORS}
+ selectedColor={increaseColor}
+ onSelectColor={onIncrease}
+ showCustomColor
+ preventPopoverClose
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2 p-1 px-2">
+ <span className="font-normal">Decrease</span>
+ <LemonColorPicker
+ colors={PRESET_COLORS}
+ selectedColor={decreaseColor}
+ onSelectColor={onDecrease}
+ showCustomColor
+ preventPopoverClose
+ />
+ </div>
+ </div>
+ )
+}
+
+export function MetricShowChangeFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+
+ const showChange = trendsFilter?.metricShowChange ?? METRIC_SHOW_CHANGE_DEFAULT
+
+ return (
+ <div className="flex flex-col">
+ <LemonCheckbox
+ className="p-1 px-2"
+ checked={showChange}
+ onChange={() => updateInsightFilter({ metricShowChange: !showChange })}
+ label={<span className="font-normal">Show change</span>}
+ size="small"
+ />
+ {showChange && (
+ <DirectionColorPickers
+ increaseColor={trendsFilter?.metricChangeIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR}
+ decreaseColor={trendsFilter?.metricChangeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR}
+ onIncrease={(color) => updateInsightFilter({ metricChangeIncreaseColor: color })}
+ onDecrease={(color) => updateInsightFilter({ metricChangeDecreaseColor: color })}
+ />
+ )}
+ </div>
+ )
+}
+
+export function MetricColorFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+
+ const colorByDirection = trendsFilter?.metricColorByDirection ?? METRIC_COLOR_BY_DIRECTION_DEFAULT
+
+ return (
+ <div className="flex flex-col">
+ <LemonCheckbox
+ className="p-1 px-2"
+ checked={colorByDirection}
+ onChange={() => updateInsightFilter({ metricColorByDirection: !colorByDirection })}
+ label={<span className="font-normal">Color by trend</span>}
+ size="small"
+ />
+ {colorByDirection && (
+ <DirectionColorPickers
+ increaseColor={trendsFilter?.metricLineIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR}
+ decreaseColor={trendsFilter?.metricLineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR}
+ onIncrease={(color) => updateInsightFilter({ metricLineIncreaseColor: color })}
+ onDecrease={(color) => updateInsightFilter({ metricLineDecreaseColor: color })}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index b4eeb69f9492..8380efec28a8 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -497,6 +497,28 @@ describe('insightVizDataLogic', () => {
layout: FunnelLayout.horizontal,
})
})
+
+ it('clears the breakdown when switching to the Metric display', async () => {
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateBreakdownFilter({
+ breakdown_type: 'event',
+ breakdown: '$browser',
+ })
+ }).toFinishAllListeners()
+ expect((builtInsightVizDataLogic.values.querySource as TrendsQuery).breakdownFilter).toEqual({
+ breakdown_type: 'event',
+ breakdown: '$browser',
+ })
+
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateInsightFilter({ display: ChartDisplayType.Metric })
+ }).toFinishAllListeners()
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({
+ trendsFilter: { display: ChartDisplayType.Metric },
+ })
+ expect((builtInsightVizDataLogic.values.querySource as TrendsQuery).breakdownFilter).toBeUndefined()
+ })
})
describe('activeUsersMath', () => {
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 44ebb72bbfdf..f5191d41c958 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -958,6 +958,11 @@ const handleQuerySourceUpdateSideEffects = (
;(mergedUpdate as TrendsQuery).breakdownFilter = undefined
}
+ // Remove breakdown filter if display type is Metric because it is single-series
+ if (kind === NodeKind.TrendsQuery && maybeChangedDisplay === ChartDisplayType.Metric) {
+ ;(mergedUpdate as TrendsQuery).breakdownFilter = undefined
+ }
+
// Remove breakdown filter if display type is Heatmap because it is not supported
if (kind === NodeKind.TrendsQuery && maybeChangedDisplay === ChartDisplayType.CalendarHeatmap) {
;(mergedUpdate as TrendsQuery).breakdownFilter = undefined
diff --git a/frontend/src/scenes/insights/stories/TrendsMetric.stories.tsx b/frontend/src/scenes/insights/stories/TrendsMetric.stories.tsx
new file mode 100644
index 000000000000..818164309cac
--- /dev/null
+++ b/frontend/src/scenes/insights/stories/TrendsMetric.stories.tsx
@@ -0,0 +1,50 @@
+import { samplePersonProperties, sampleRetentionPeopleResponse } from 'scenes/insights/__mocks__/insight.mocks'
+
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'
+
+import { mswDecorator } from '~/mocks/browser'
+
+type Story = StoryObj<{}>
+const meta: Meta = {
+ title: 'Scenes-App/Insights/TrendsMetric',
+ parameters: {
+ layout: 'fullscreen',
+ testOptions: {
+ snapshotBrowsers: ['chromium'],
+ viewport: {
+ width: 1300,
+ height: 720,
+ },
+ },
+ viewMode: 'story',
+ mockDate: '2022-04-01',
+ featureFlags: [FEATURE_FLAGS.METRIC_INSIGHT],
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/persons/retention': sampleRetentionPeopleResponse,
+ '/api/environments/:team_id/persons/properties': samplePersonProperties,
+ '/api/projects/:team_id/groups_types': [],
+ },
+ post: {
+ '/api/projects/:team_id/cohorts/': { id: 1 },
+ },
+ }),
+ ],
+}
+export default meta
+/* eslint-disable @typescript-eslint/no-var-requires */
+export const TrendsMetric: Story = createInsightStory(
+ require('../../../mocks/fixtures/api/projects/team_id/insights/trendsMetric.json')
+)
+TrendsMetric.parameters = { testOptions: { waitForSelector: '.Metric canvas' } }
+export const TrendsMetricEdit: Story = createInsightStory(
+ require('../../../mocks/fixtures/api/projects/team_id/insights/trendsMetric.json'),
+ 'edit'
+)
+TrendsMetricEdit.parameters = { testOptions: { waitForSelector: '.Metric canvas' } }
+/* eslint-enable @typescript-eslint/no-var-requires */
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index 930bfcf833fe..6fe5b2492ead 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -182,6 +182,7 @@ const groupedChartDisplayTypes: Record<ChartDisplayType, ChartDisplayType> = {
[ChartDisplayType.ActionsUnstackedBar]: ChartDisplayType.ActionsLineGraph,
[ChartDisplayType.ActionsStackedBar]: ChartDisplayType.ActionsLineGraph,
[ChartDisplayType.TwoDimensionalHeatmap]: ChartDisplayType.ActionsLineGraph,
+ [ChartDisplayType.Metric]: ChartDisplayType.ActionsLineGraph,
// cumulative time series
[ChartDisplayType.ActionsLineGraphCumulative]: ChartDisplayType.ActionsLineGraphCumulative,
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.tsx b/frontend/src/scenes/insights/views/Metric/Metric.tsx
new file mode 100644
index 000000000000..0c9d53a22aba
--- /dev/null
+++ b/frontend/src/scenes/insights/views/Metric/Metric.tsx
@@ -0,0 +1,92 @@
+import clsx from 'clsx'
+import { useValues } from 'kea'
+
+import { MetricCard, useChartTheme } from '@posthog/quill-charts'
+
+import { dayjs } from 'lib/dayjs'
+import { hexToRGBA } from 'lib/utils/colors'
+import { formatDate } from 'lib/utils/datetime'
+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
+import { InsightEmptyState } from 'scenes/insights/EmptyStates'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ChartParams, TrendResult } from '~/types'
+
+import { insightLogic } from '../../insightLogic'
+import {
+ computeMetricChange,
+ METRIC_COLOR_BY_DIRECTION_DEFAULT,
+ METRIC_DEFAULT_DECREASE_COLOR,
+ METRIC_DEFAULT_INCREASE_COLOR,
+ METRIC_SHOW_CHANGE_DEFAULT,
+} from './Metric.utils'
+
+const makeChangeColor = (hex: string): { background: string; foreground: string } => ({
+ background: hexToRGBA(hex, 0.1),
+ foreground: hex,
+})
+
+export function Metric({ inCardView }: ChartParams): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { insightData, trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { baseCurrency } = useValues(teamLogic)
+ const theme = useChartTheme()
+
+ const resultSeries = insightData?.result?.[0] as TrendResult | undefined
+
+ // `count` is typed as a number but can be absent at runtime, which would render a blank tile.
+ if (!resultSeries || resultSeries.count == null) {
+ return <InsightEmptyState />
+ }
+
+ const headlineValue = resultSeries.count
+ const showChange = trendsFilter?.metricShowChange ?? METRIC_SHOW_CHANGE_DEFAULT
+
+ const { change, startValue } = computeMetricChange(resultSeries.data)
+ const comparisonSubtitle =
+ startValue != null
+ ? `vs. ${formatAggregationAxisValue(trendsFilter, startValue, baseCurrency)} at start`
+ : undefined
+
+ const isIncrease = (change?.value ?? 0) >= 0
+ const pillColors = {
+ positiveColor: makeChangeColor(trendsFilter?.metricChangeIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR),
+ negativeColor: makeChangeColor(trendsFilter?.metricChangeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR),
+ }
+ const lineIncreaseColor = trendsFilter?.metricLineIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR
+ const lineDecreaseColor = trendsFilter?.metricLineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR
+ let lineColor: string | undefined
+ if ((trendsFilter?.metricColorByDirection ?? METRIC_COLOR_BY_DIRECTION_DEFAULT) && change != null) {
+ lineColor = isIncrease ? lineIncreaseColor : lineDecreaseColor
+ }
+
+ // Format the backend day labels the app's way ("June 16, 2026" rather than "16-Jun-2026").
+ const labels = resultSeries.days?.map((day) => formatDate(dayjs(day))) ?? resultSeries.labels
+
+ return (
+ <div className={clsx('Metric ph-no-capture flex flex-col w-full p-2', inCardView && 'flex-1')}>
+ <MetricCard
+ className={inCardView ? 'flex-1' : undefined}
+ sparklineFill={inCardView}
+ // No title — the insight/card header already shows the name.
+ title={null}
+ value={headlineValue}
+ changeSize="md"
+ changeInline
+ change={change}
+ {...pillColors}
+ subtitle={comparisonSubtitle}
+ data={resultSeries.data}
+ labels={labels}
+ theme={theme}
+ color={lineColor}
+ showChange={showChange}
+ formatValue={(value) => formatAggregationAxisValue(trendsFilter, value, baseCurrency)}
+ sparklineHeight={120}
+ sparklineClassName="mt-4 -mx-2"
+ dataAttr="metric-value"
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
new file mode 100644
index 000000000000..61f6f321bd32
--- /dev/null
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
@@ -0,0 +1,57 @@
+import { computeMetricChange, MetricChangeResult } from './Metric.utils'
+
+describe('computeMetricChange', () => {
+ const cases: { name: string; data: number[] | undefined; expected: MetricChangeResult }[] = [
+ { name: 'undefined data → no change', data: undefined, expected: { change: undefined, startValue: undefined } },
+ { name: 'empty series → no change', data: [], expected: { change: undefined, startValue: undefined } },
+ { name: 'single point → no change', data: [5], expected: { change: undefined, startValue: undefined } },
+ {
+ name: 'filtering drops below two finite points → no change',
+ data: [NaN, Infinity],
+ expected: { change: undefined, startValue: undefined },
+ },
+ { name: 'increase', data: [100, 150], expected: { change: { value: 50 }, startValue: 100 } },
+ { name: 'decrease', data: [200, 100], expected: { change: { value: -50 }, startValue: 200 } },
+ {
+ name: 'zero start, positive end → +∞',
+ data: [0, 50],
+ expected: { change: { value: 1, label: '∞' }, startValue: 0 },
+ },
+ { name: 'zero start, zero end → no movement', data: [0, 0], expected: { change: null, startValue: 0 } },
+ {
+ name: 'zero start, negative end → -∞',
+ data: [0, -5],
+ expected: { change: { value: -1, label: '∞' }, startValue: 0 },
+ },
+ {
+ name: 'just below cap → real % with no ∞ label',
+ data: [100, 10000],
+ expected: { change: { value: 9900 }, startValue: 100 },
+ },
+ {
+ name: 'exactly at cap → ∞',
+ data: [1, 101],
+ expected: { change: { value: 10000, label: '∞' }, startValue: 1 },
+ },
+ {
+ name: 'large positive over cap → ∞ (value preserved)',
+ data: [1, 100000],
+ expected: { change: { value: 9999900, label: '∞' }, startValue: 1 },
+ },
+ {
+ name: 'large negative over cap → ∞ (Math.abs triggers on decreases too)',
+ data: [100, -10000],
+ expected: { change: { value: -10100, label: '∞' }, startValue: 100 },
+ },
+ {
+ name: 'non-finite values filtered out',
+ data: [NaN, 100, 200],
+ expected: { change: { value: 100 }, startValue: 100 },
+ },
+ { name: 'negative start increasing', data: [-100, -50], expected: { change: { value: 50 }, startValue: -100 } },
+ ]
+
+ it.each(cases)('$name', ({ data, expected }) => {
+ expect(computeMetricChange(data)).toEqual(expected)
+ })
+})
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
new file mode 100644
index 000000000000..ffdcb38eaa30
--- /dev/null
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
@@ -0,0 +1,32 @@
+import { type MetricChange } from '@posthog/quill-charts'
+
+// Above this magnitude the exact percentage is noise (it comes from a near-zero start), so show ∞ instead.
+export const MAX_CHANGE_PERCENT = 10_000 // ≈100×
+
+export const METRIC_SHOW_CHANGE_DEFAULT = true
+export const METRIC_COLOR_BY_DIRECTION_DEFAULT = false
+export const METRIC_DEFAULT_INCREASE_COLOR = '#388600'
+export const METRIC_DEFAULT_DECREASE_COLOR = '#db3707'
+
+export interface MetricChangeResult {
+ // `undefined` → no pill (fewer than two finite points); `null` → no movement worth showing.
+ change: MetricChange | null | undefined
+ startValue: number | undefined
+}
+
+// Change from the first to the last finite point. Renders ∞ when the start is zero (infinite) or near-zero.
+export function computeMetricChange(data: number[] | undefined): MetricChangeResult {
+ const finite = (data ?? []).filter((value) => Number.isFinite(value))
+ if (finite.length < 2) {
+ return { change: undefined, startValue: undefined }
+ }
+ const startValue = finite[0]
+ const endValue = finite[finite.length - 1]
+ if (startValue === 0) {
+ const change = endValue === 0 ? null : { value: endValue > 0 ? 1 : -1, label: '∞' }
+ return { change, startValue }
+ }
+ const percent = ((endValue - startValue) / Math.abs(startValue)) * 100
+ const change = Math.abs(percent) >= MAX_CHANGE_PERCENT ? { value: percent, label: '∞' } : { value: percent }
+ return { change, startValue }
+}
diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsx
index c9a079782b5c..89a1aabbdbfe 100644
--- a/frontend/src/scenes/trends/Trends.tsx
+++ b/frontend/src/scenes/trends/Trends.tsx
@@ -7,6 +7,7 @@ import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/Wrapping
import { insightLogic } from 'scenes/insights/insightLogic'
import { BoldNumber } from 'scenes/insights/views/BoldNumber'
import { InsightsTable } from 'scenes/insights/views/InsightsTable/InsightsTable'
+import { Metric } from 'scenes/insights/views/Metric/Metric'
import { InsightVizNode } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
@@ -111,6 +112,9 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
if (display === ChartDisplayType.BoldNumber) {
return <BoldNumber {...commonProps} />
}
+ if (display === ChartDisplayType.Metric) {
+ return <Metric {...commonProps} />
+ }
if (display === ChartDisplayType.ActionsTable) {
return (
<InsightsTable
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 32380962e2ba..073fadb650ff 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2875,6 +2875,7 @@ export enum ChartDisplayType {
ActionsAreaGraph = 'ActionsAreaGraph',
ActionsLineGraphCumulative = 'ActionsLineGraphCumulative',
BoldNumber = 'BoldNumber',
+ Metric = 'Metric',
ActionsPie = 'ActionsPie',
ActionsBarValue = 'ActionsBarValue',
ActionsTable = 'ActionsTable',
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 82700d2e4b34..241685c7b050 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -71,6 +71,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, defaultHiddenKeys, onToggleSeries }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
+- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop 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 change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.
diff --git a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
index 346bd832b488..a39d42a76a33 100644
--- a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
+++ b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
@@ -14,6 +14,8 @@ export interface SparklineProps {
theme: ChartTheme
color?: string
height?: number
+ /** Fill the parent's height (flex child) instead of using a fixed `height`. */
+ fill?: boolean
/** Peak opacity of the gradient fill under the line. Range 0–1. */
fillOpacity?: number
/** Fires the hovered index, or -1 when not hovering. */
@@ -28,7 +30,8 @@ const SPARKLINE_CONFIG: LineChartConfig = {
hideYAxis: true,
showCrosshair: true,
tooltip: { enabled: false },
- margins: { top: 0, right: 0, bottom: 0, left: 0 },
+ // Reserve room for the hover highlight ring (radius + 2 = 6px) so it isn't clipped at the top/bottom edge.
+ margins: { top: 6, right: 0, bottom: 6, left: 0 },
}
export function Sparkline(props: SparklineProps): React.ReactElement {
@@ -46,6 +49,7 @@ function SparklineInner({
theme,
color,
height = 120,
+ fill = false,
fillOpacity = 0.35,
onHoverIndexChange,
className,
@@ -68,10 +72,14 @@ function SparklineInner({
],
[data, resolvedColor, fillOpacity]
)
- const wrapperStyle = useMemo<React.CSSProperties>(() => ({ height }), [height])
+ const wrapperStyle = useMemo<React.CSSProperties | undefined>(() => (fill ? undefined : { height }), [fill, height])
return (
- <div className={`relative flex flex-col ${className ?? ''}`} style={wrapperStyle} data-attr={dataAttr}>
+ <div
+ className={`relative flex flex-col ${fill ? 'flex-1 min-h-0' : ''} ${className ?? ''}`}
+ style={wrapperStyle}
+ data-attr={dataAttr}
+ >
<LineChart series={series} labels={resolvedLabels} theme={theme} config={SPARKLINE_CONFIG}>
{onHoverIndexChange ? <HoverWatcher onHoverChange={onHoverIndexChange} /> : null}
</LineChart>
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx
index eb2fe7544c35..62647bfdad9d 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx
@@ -270,7 +270,7 @@ describe('MetricCard', () => {
/>
)
expect(container.textContent).toContain(change.label)
- const pill = container.querySelector('.rounded-full') as HTMLElement | null
+ const pill = container.querySelector('[data-attr="metric-card-change-pill"]') as HTMLElement | null
expect(pill?.style.color).toBe(expectedColor)
})
@@ -278,7 +278,7 @@ describe('MetricCard', () => {
const { container } = render(
<MetricCard title="Revenue" value={8800} change={{ value: -4.2, label: '-4.2%' }} />
)
- const chevron = container.querySelector('.rounded-full svg')
+ const chevron = container.querySelector('[data-attr="metric-card-change-pill"] svg')
expect(chevron?.getAttribute('class')).toContain('rotate-180')
})
@@ -287,4 +287,50 @@ describe('MetricCard', () => {
expect(container.querySelector('[data-attr="metric-revenue"]')).not.toBeNull()
})
})
+
+ describe('inline change pill, fill, and subtitle', () => {
+ it('renders the change pill exactly once with changeInline (no header duplicate)', () => {
+ const { container } = renderHogChart(
+ <MetricCard
+ title="Total"
+ data={[100, 200, 300, 400]}
+ labels={LABELS}
+ theme={THEME}
+ animationMs={0}
+ hoverIntentMs={0}
+ changeInline
+ change={{ value: 12.5, label: '+12.5%' }}
+ />
+ )
+ expect(container.querySelectorAll('[data-attr="metric-card-change-pill"]')).toHaveLength(1)
+ })
+
+ it('drops the fixed sparkline height when sparklineFill is set', () => {
+ const fixed = renderHogChart(
+ <MetricCard title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} sparklineHeight={120} />
+ )
+ expect((fixed.container.querySelector('[data-attr="metric-card-sparkline"]') as HTMLElement).style.height).toBe(
+ '120px'
+ )
+
+ const filled = renderHogChart(
+ <MetricCard title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} sparklineFill />
+ )
+ expect(
+ (filled.container.querySelector('[data-attr="metric-card-sparkline"]') as HTMLElement).style.height
+ ).toBe('')
+ })
+
+ it('renders the subtitle when provided and omits the row when empty', () => {
+ const withSubtitle = renderHogChart(
+ <MetricCard title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} subtitle="Last 7 days" />
+ )
+ expect(withSubtitle.container.querySelector('[data-attr="metric-card-subtitle"]')?.textContent).toBe(
+ 'Last 7 days'
+ )
+
+ const valueOnly = render(<MetricCard title={null} value={42} />)
+ expect(valueOnly.container.querySelector('[data-attr="metric-card-subtitle"]')).toBeNull()
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
index a5f3bb10823d..5e4b383c52ae 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
@@ -1,9 +1,9 @@
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 { Sparkline } from '../../charts/Sparkline/Sparkline'
import { type MetricChange, resolveDelta } from './resolveDelta'
import { useAnimatedNumber } from './useAnimatedNumber'
import { useHoverIntent } from './useHoverIntent'
@@ -30,6 +30,8 @@ export interface MetricCardProps {
/** Sparkline line + fill color. Falls back to `theme.colors[0]`. */
color?: string
sparklineHeight?: number
+ /** Fill the card's remaining height with the sparkline instead of using a fixed `sparklineHeight`. */
+ sparklineFill?: boolean
sparklineFillOpacity?: number
sparklineClassName?: string
formatValue?: (value: number) => string
@@ -38,6 +40,10 @@ export interface MetricCardProps {
/** Fixed comparison pill. Supplied → no hover-driven fallback. Pass `null` to suppress. */
change?: MetricChange | null
goodDirection?: 'up' | 'down'
+ /** Size of the change pill. Defaults to `sm`. */
+ changeSize?: 'sm' | 'md'
+ /** Render the change pill inline next to the headline instead of in the header row. */
+ changeInline?: boolean
positiveColor?: ChangeColor
negativeColor?: ChangeColor
/** Caption under the headline. Defaults to `labels[activeIndex]` when a sparkline is present. */
@@ -77,6 +83,7 @@ function MetricCardInner({
theme,
color,
sparklineHeight = 120,
+ sparklineFill = false,
sparklineFillOpacity = 0.35,
sparklineClassName = 'mt-4',
formatValue = DEFAULT_FORMAT_VALUE,
@@ -84,6 +91,8 @@ function MetricCardInner({
showChange = true,
change,
goodDirection = 'up',
+ changeSize = 'sm',
+ changeInline = false,
positiveColor = DEFAULT_POSITIVE_COLOR,
negativeColor = DEFAULT_NEGATIVE_COLOR,
subtitle,
@@ -117,22 +126,46 @@ function MetricCardInner({
const delta = resolveDelta({ showChange, change, fallbackChangePercent, formatChange })
const headlineDisplay = sparklineData ? formatValue(animatedValue) : formatValue(restingValue)
- const resolvedSubtitle = subtitle ?? labels?.[activeIndex] ?? ' '
+ const resolvedSubtitle = subtitle ?? labels?.[activeIndex]
const positive = delta != null && delta.value >= 0
const isGood = goodDirection === 'up' ? positive : !positive
const pillColors = isGood ? positiveColor : negativeColor
+ const headerDelta = delta != null && !changeInline ? delta : null
+ const showHeader = title != null || headerDelta != null
+ const headerJustify = title != null ? 'justify-between' : 'justify-end'
+ const renderedHeadline = (
+ <div className={`text-4xl font-bold tracking-tight tabular-nums${showHeader ? ' mt-2' : ''}`}>
+ {headlineDisplay}
+ </div>
+ )
+
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>
+ {showHeader && (
+ <div className={`flex items-start gap-2 ${headerJustify}`}>
+ {title != null && <div className="text-sm font-medium">{title}</div>}
+ {headerDelta != null && (
+ <ChangePill positive={positive} label={headerDelta.label} colors={pillColors} size={changeSize} />
+ )}
+ </div>
+ )}
- <div className="mt-2 text-4xl font-bold tracking-tight tabular-nums">{headlineDisplay}</div>
+ {changeInline && delta != null ? (
+ <div className="flex items-center justify-between gap-2">
+ {renderedHeadline}
+ <ChangePill positive={positive} label={delta.label} colors={pillColors} size={changeSize} />
+ </div>
+ ) : (
+ renderedHeadline
+ )}
- <div className="mt-1 text-sm opacity-60">{resolvedSubtitle}</div>
+ {resolvedSubtitle != null && resolvedSubtitle !== '' && (
+ <div className="mt-1 text-sm opacity-60" data-attr="metric-card-subtitle">
+ {resolvedSubtitle}
+ </div>
+ )}
{sparklineData && theme && (
<Sparkline
@@ -141,9 +174,11 @@ function MetricCardInner({
theme={theme}
color={color}
height={sparklineHeight}
+ fill={sparklineFill}
fillOpacity={sparklineFillOpacity}
onHoverIndexChange={setHoverIndex}
className={sparklineClassName}
+ dataAttr="metric-card-sparkline"
/>
)}
</div>
@@ -154,25 +189,28 @@ interface ChangePillProps {
positive: boolean
label: React.ReactNode
colors: ChangeColor
+ size?: 'sm' | 'md'
}
-function ChangePill({ positive, label, colors }: ChangePillProps): React.ReactElement {
+function ChangePill({ positive, label, colors, size = 'sm' }: ChangePillProps): React.ReactElement {
+ const sizeClasses = size === 'md' ? 'gap-1.5 px-2.5 py-1 text-sm' : 'gap-1 px-2 py-0.5 text-xs'
return (
<div
- className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium transition-colors"
+ className={`inline-flex items-center rounded-full font-medium transition-colors ${sizeClasses}`}
style={{ background: colors.background, color: colors.foreground }}
+ data-attr="metric-card-change-pill"
>
- <Chevron up={positive} />
+ <Chevron up={positive} size={size === 'md' ? 12 : 10} />
<span className="tabular-nums">{label}</span>
</div>
)
}
-function Chevron({ up }: { up: boolean }): React.ReactElement {
+function Chevron({ up, size = 10 }: { up: boolean; size?: number }): React.ReactElement {
return (
<svg
- width="10"
- height="10"
+ width={size}
+ height={size}
viewBox="0 0 10 10"
fill="none"
stroke="currentColor"
diff --git a/posthog/constants.py b/posthog/constants.py
index f14249cf4ebc..b825bdc623c5 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -66,6 +66,7 @@ TRENDS_BAR = "ActionsBar"
TRENDS_BAR_VALUE = "ActionsBarValue"
TRENDS_WORLD_MAP = "WorldMap"
TRENDS_BOLD_NUMBER = "BoldNumber"
+TRENDS_METRIC = "Metric"
TRENDS_CALENDAR_HEATMAP = "CalendarHeatmap"
TRENDS_BOX_PLOT = "BoxPlot"
@@ -79,7 +80,7 @@ NON_TIME_SERIES_DISPLAY_TYPES = [
TRENDS_CALENDAR_HEATMAP,
]
# Sync with frontend NON_BREAKDOWN_DISPLAY_TYPES
-NON_BREAKDOWN_DISPLAY_TYPES = [TRENDS_BOLD_NUMBER, TRENDS_CALENDAR_HEATMAP, TRENDS_BOX_PLOT]
+NON_BREAKDOWN_DISPLAY_TYPES = [TRENDS_BOLD_NUMBER, TRENDS_METRIC, TRENDS_CALENDAR_HEATMAP, TRENDS_BOX_PLOT]
# CONSTANTS
INSIGHT_TRENDS = "TRENDS"
@@ -109,6 +110,7 @@ DISPLAY_TYPES = Literal[
"ActionsBarValue",
"WorldMap",
"BoldNumber",
+ "Metric",
"CalendarHeatmap",
]
diff --git a/posthog/schema.py b/posthog/schema.py
index 1e35aa330dcd..0cff57fe93b1 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -7675,6 +7675,30 @@ class TrendsFilter(BaseModel):
goalLines: list[GoalLine] | None = Field(default=None, description="Goal Lines")
hiddenLegendIndexes: list[int] | None = None
hideWeekends: bool | None = False
+ metricChangeDecreaseColor: str | None = Field(
+ default=None,
+ description=("Metric display: change pill color when the metric decreased. Defaults to red."),
+ )
+ metricChangeIncreaseColor: str | None = Field(
+ default=None,
+ description=("Metric display: change pill color when the metric increased. Defaults to green."),
+ )
+ metricColorByDirection: bool | None = Field(
+ default=False,
+ description=("Metric display: color the sparkline by whether the metric increased or decreased."),
+ )
+ metricLineDecreaseColor: str | None = Field(
+ default=None,
+ description=("Metric display: line color when the metric decreased. Defaults to red."),
+ )
+ metricLineIncreaseColor: str | None = Field(
+ default=None,
+ description=("Metric display: line color when the metric increased. Defaults to green."),
+ )
+ metricShowChange: bool | None = Field(
+ default=True,
+ description="Show the period-over-period change pill on the Metric display.",
+ )
minDecimalPlaces: float | None = None
movingAverageIntervals: float | None = None
resultCustomizationBy: ResultCustomizationBy | None = Field(
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 7ca7d6f6a16d..d01762c21766 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -430,6 +430,7 @@ class Display(StrEnum):
ACTIONS_AREA_GRAPH = "ActionsAreaGraph"
ACTIONS_LINE_GRAPH_CUMULATIVE = "ActionsLineGraphCumulative"
BOLD_NUMBER = "BoldNumber"
+ METRIC = "Metric"
ACTIONS_PIE = "ActionsPie"
ACTIONS_BAR_VALUE = "ActionsBarValue"
ACTIONS_TABLE = "ActionsTable"
@@ -561,6 +562,7 @@ class ChartDisplayType(StrEnum):
ACTIONS_AREA_GRAPH = "ActionsAreaGraph"
ACTIONS_LINE_GRAPH_CUMULATIVE = "ActionsLineGraphCumulative"
BOLD_NUMBER = "BoldNumber"
+ METRIC = "Metric"
ACTIONS_PIE = "ActionsPie"
ACTIONS_BAR_VALUE = "ActionsBarValue"
ACTIONS_TABLE = "ActionsTable"
diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.py
index 5519b6e4eb8d..9c1ec9848bf1 100644
--- a/posthog/schema_helpers.py
+++ b/posthog/schema_helpers.py
@@ -169,6 +169,7 @@ def grouped_chart_display_types(display: ChartDisplayType) -> ChartDisplayType:
| ChartDisplayType.ACTIONS_UNSTACKED_BAR
| ChartDisplayType.ACTIONS_STACKED_BAR
| ChartDisplayType.TWO_DIMENSIONAL_HEATMAP
+ | ChartDisplayType.METRIC
):
# standard time series
return ChartDisplayType.ACTIONS_LINE_GRAPH
diff --git a/posthog/test/test_schema_helpers.py b/posthog/test/test_schema_helpers.py
index f016e5587ec9..b091bd757938 100644
--- a/posthog/test/test_schema_helpers.py
+++ b/posthog/test/test_schema_helpers.py
@@ -145,6 +145,10 @@ class TestSchemaHelpers(TestCase):
},
)
+ # metric (groups to ActionsLineGraph, the default, so display is removed)
+ query = TrendsQuery(**{**base_trends, "trendsFilter": {"display": "Metric"}})
+ self.assertEqual(to_dict(query), {"kind": "TrendsQuery", "series": []})
+
def _assert_filter(self, key: str, num_keys: int, q1: BaseModel, q2: BaseModel):
self.assertEqual(to_dict(q1), to_dict(q2))
if num_keys == 0:
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 76776790f605..149d9a3652b1 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2008,6 +2008,7 @@ export const ChartDisplayTypeApi = {
ActionsAreaGraph: 'ActionsAreaGraph',
ActionsLineGraphCumulative: 'ActionsLineGraphCumulative',
BoldNumber: 'BoldNumber',
+ Metric: 'Metric',
ActionsPie: 'ActionsPie',
ActionsBarValue: 'ActionsBarValue',
ActionsTable: 'ActionsTable',
@@ -2125,6 +2126,18 @@ export interface TrendsFilterApi {
goalLines?: GoalLineApi[] | null
hiddenLegendIndexes?: number[] | null
hideWeekends?: boolean | null
+ /** Metric display: change pill color when the metric decreased. Defaults to red. */
+ metricChangeDecreaseColor?: string | null
+ /** Metric display: change pill color when the metric increased. Defaults to green. */
+ metricChangeIncreaseColor?: string | null
+ /** Metric display: color the sparkline by whether the metric increased or decreased. */
+ metricColorByDirection?: boolean | null
+ /** Metric display: line color when the metric decreased. Defaults to red. */
+ metricLineDecreaseColor?: string | null
+ /** Metric display: line color when the metric increased. Defaults to green. */
+ metricLineIncreaseColor?: string | null
+ /** Show the period-over-period change pill on the Metric display. */
+ metricShowChange?: boolean | null
minDecimalPlaces?: number | null
movingAverageIntervals?: number | null
/** Wether result datasets are associated by their values or by their order. */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 2839d5015977..a4e17fc92af0 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1448,6 +1448,7 @@ export const ChartDisplayTypeApi = {
ActionsAreaGraph: 'ActionsAreaGraph',
ActionsLineGraphCumulative: 'ActionsLineGraphCumulative',
BoldNumber: 'BoldNumber',
+ Metric: 'Metric',
ActionsPie: 'ActionsPie',
ActionsBarValue: 'ActionsBarValue',
ActionsTable: 'ActionsTable',
@@ -1565,6 +1566,18 @@ export interface TrendsFilterApi {
goalLines?: GoalLineApi[] | null
hiddenLegendIndexes?: number[] | null
hideWeekends?: boolean | null
+ /** Metric display: change pill color when the metric decreased. Defaults to red. */
+ metricChangeDecreaseColor?: string | null
+ /** Metric display: change pill color when the metric increased. Defaults to green. */
+ metricChangeIncreaseColor?: string | null
+ /** Metric display: color the sparkline by whether the metric increased or decreased. */
+ metricColorByDirection?: boolean | null
+ /** Metric display: line color when the metric decreased. Defaults to red. */
+ metricLineDecreaseColor?: string | null
+ /** Metric display: line color when the metric increased. Defaults to green. */
+ metricLineIncreaseColor?: string | null
+ /** Show the period-over-period change pill on the Metric display. */
+ metricShowChange?: boolean | null
minDecimalPlaces?: number | null
movingAverageIntervals?: number | null
/** Wether result datasets are associated by their values or by their order. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8475bfcc14fb..ed773cb89bfd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2265,6 +2265,7 @@ export namespace Schemas {
ActionsAreaGraph: 'ActionsAreaGraph',
ActionsLineGraphCumulative: 'ActionsLineGraphCumulative',
BoldNumber: 'BoldNumber',
+ Metric: 'Metric',
ActionsPie: 'ActionsPie',
ActionsBarValue: 'ActionsBarValue',
ActionsTable: 'ActionsTable',
@@ -2383,6 +2384,18 @@ export namespace Schemas {
goalLines?: GoalLine[] | null;
hiddenLegendIndexes?: number[] | null;
hideWeekends?: boolean | null;
+ /** Metric display: change pill color when the metric decreased. Defaults to red. */
+ metricChangeDecreaseColor?: string | null;
+ /** Metric display: change pill color when the metric increased. Defaults to green. */
+ metricChangeIncreaseColor?: string | null;
+ /** Metric display: color the sparkline by whether the metric increased or decreased. */
+ metricColorByDirection?: boolean | null;
+ /** Metric display: line color when the metric decreased. Defaults to red. */
+ metricLineDecreaseColor?: string | null;
+ /** Metric display: line color when the metric increased. Defaults to green. */
+ metricLineIncreaseColor?: string | null;
+ /** Show the period-over-period change pill on the Metric display. */
+ metricShowChange?: boolean | null;
minDecimalPlaces?: number | null;
movingAverageIntervals?: number | null;
/** Wether result datasets are associated by their values or by their order. */
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index f40b1a424c7a..4acf4e34fdfc 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -502,6 +502,7 @@ const AssistantTrendsFilter = z.object({
'ActionsAreaGraph',
'ActionsLineGraphCumulative',
'BoldNumber',
+ 'Metric',
'ActionsPie',
'ActionsBarValue',
'ActionsTable',
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
index 69671540b26c..482418c74750 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
@@ -3804,6 +3804,7 @@
"ActionsAreaGraph",
"ActionsLineGraphCumulative",
"BoldNumber",
+ "Metric",
"ActionsPie",
"ActionsBarValue",
"ActionsTable",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
index 47eb67b2e94f..b94a15ef3eaa 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
@@ -3616,6 +3616,7 @@
"ActionsAreaGraph",
"ActionsLineGraphCumulative",
"BoldNumber",
+ "Metric",
"ActionsPie",
"ActionsBarValue",
"ActionsTable",