:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): rename aggregates tab to series and expand rows to show full name (#116261)
Frank Hamand1f7d9a67a5ad
diff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsxindex 40591e6dbebe..b2b8c1011bb1 100644--- a/products/metrics/frontend/components/MetricsSamplesPanel.tsx+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx@@ -1,6 +1,9 @@+import clsx from 'clsx'import { useActions, useValues } from 'kea'+import { Fragment, useState } from 'react'-import { LemonSegmentedButton, LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'+import { IconCollapse, IconExpand } from '@posthog/icons'+import { LemonButton, LemonSegmentedButton, LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'import { getColorVar } from 'lib/colors'import { TZLabel } from 'lib/components/TZLabel'@@ -12,7 +15,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { traceUrl } from 'products/tracing/frontend/traceLinks'-import { type MetricsAggregateRow, type MetricsPanelTab, metricsSamplesLogic } from './metricsSamplesLogic'+import { type MetricsSeriesRow, type MetricsPanelTab, metricsSamplesLogic } from './metricsSamplesLogic'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import { metricsViewerLogic } from './metricsViewerLogic'import { SampleAttributes } from './SampleAttributes'@@ -107,35 +110,109 @@ function SamplesTab(): JSX.Element {)}-function AggregatesTab(): JSX.Element {- const { aggregateRows } = useValues(metricsSamplesLogic)+const SEPARATOR_SEGMENTS = /[^/._:-]*[/._:-]?/g++/** One `key=value` label with the key muted, so the values are easy to scan.+ * With `wrap`, `<wbr>` lets a long value break after `=` and after separators instead of mid-word.+ * Chrome breaks at `<wbr>` even in nowrap text, so truncated names must not get it. */+function SeriesNamePart({ part, wrap = false }: { part: string; wrap?: boolean }): JSX.Element {+ const separatorIndex = part.indexOf('=')+ if (separatorIndex < 1) {+ return <>{part}</>+ }+ const value = part.slice(separatorIndex + 1)+ const segments = wrap ? (value.match(SEPARATOR_SEGMENTS)?.filter(Boolean) ?? [value]) : [value]+ return (+ <>+ <span className="text-tertiary">{part.slice(0, separatorIndex + 1)}</span>+ {segments.map((segment, index) => (+ <Fragment key={index}>+ {wrap && <wbr />}+ {segment}+ </Fragment>+ ))}+ </>+ )+}++function SeriesTab(): JSX.Element {+ const { seriesRows } = useValues(metricsSamplesLogic)const { queryLoading, hasMetricName } = useValues(metricsViewerLogic)+ const { seriesRowExpanded } = useActions(metricsUsageTrackingLogic)+ const [expandedNames, setExpandedNames] = useState<string[]>([])return (<LemonTable- dataSource={aggregateRows}+ dataSource={seriesRows}loading={queryLoading}size="small"- rowKey={(row: MetricsAggregateRow) => row.name}- emptyState={- hasMetricName ? 'No series in the selected range.' : 'Pick a metric to see per-series aggregates.'- }+ rowKey={(row: MetricsSeriesRow) => row.name}+ emptyState={hasMetricName ? 'No series in the selected range.' : 'Pick a metric to see its series.'}+ rowClassName={(row) => (expandedNames.includes(row.name) ? '[&>td]:align-top' : null)}columns={[+ {+ key: 'toggle',+ width: 0,+ render: (_, row) => {+ if (!row.hasLabels) {+ return null+ }+ const isExpanded = expandedNames.includes(row.name)+ return (+ <LemonButton+ noPadding+ active={isExpanded}+ icon={isExpanded ? <IconCollapse /> : <IconExpand />}+ title={isExpanded ? 'Show less' : 'Show full series name'}+ onClick={() => {+ if (isExpanded) {+ setExpandedNames(expandedNames.filter((name) => name !== row.name))+ } else {+ setExpandedNames([...expandedNames, row.name])+ seriesRowExpanded()+ }+ }}+ data-attr="metrics-series-row-toggle"+ />+ )+ },+ },{title: 'Series',key: 'series',- render: (_, row) => (- <span className="flex items-center gap-1.5">- <span- className="w-2 h-2 rounded-full shrink-0"- // Dynamic per-series colour can't be a Tailwind class.- style={{ backgroundColor: getColorVar(row.color) }}- />- <span className="truncate max-w-40" title={row.name}>- {row.name}+ width: '100%',+ render: (_, row) => {+ const isExpanded = expandedNames.includes(row.name)+ return (+ <span className={clsx('flex gap-1.5', isExpanded ? 'items-start' : 'items-center')}>+ <span+ className={clsx('w-2 h-2 rounded-full shrink-0', isExpanded && 'mt-1.5')}+ // Dynamic per-series colour can't be a Tailwind class.+ style={{ backgroundColor: getColorVar(row.color) }}+ />+ {isExpanded ? (+ // wrap-anywhere keeps the min-content width small, so long values wrap instead of widening the column.+ <span className="flex-1 min-w-0 flex flex-col gap-1">+ {row.nameParts.map((part, index) => (+ <span key={index} className="wrap-anywhere pl-3 -indent-3">+ <SeriesNamePart part={part} wrap />+ </span>+ ))}+ </span>+ ) : (+ // w-0 + min-w-full fills the column without the text widening it.+ <span className="w-0 min-w-full truncate" title={row.name}>+ {row.nameParts.map((part, index) => (+ <Fragment key={index}>+ {index > 0 && ', '}+ <SeriesNamePart part={part} />+ </Fragment>+ ))}+ </span>+ )}</span>- </span>- ),+ )+ },},{title: 'Latest',@@ -154,7 +231,7 @@ function AggregatesTab(): JSX.Element {)}-/** Side panel next to the chart: per-series aggregates, or the raw emissions+/** Side panel next to the chart: per-series totals, or the raw emissions* behind the chart with a link to the trace each one was recorded in. */export function MetricsSamplesPanel(): JSX.Element {const { activeTab } = useValues(metricsSamplesLogic)@@ -169,7 +246,7 @@ export function MetricsSamplesPanel(): JSX.Element {return (<div className="border rounded p-2 overflow-y-auto">{/* Samples and the anomaly badge describe one series at a time; with several- clauses this picks which one they follow. Aggregates always cover all series. */}+ clauses this picks which one they follow. The Series tab always covers all series. */}{viewerClauses.length > 1 && (<div className="flex flex-wrap items-center gap-2 pb-1"><span className="text-xs text-secondary">Samples follow series</span>@@ -201,8 +278,8 @@ export function MetricsSamplesPanel(): JSX.Element {tabs={[{key: 'aggregates',- label: 'Aggregates',- content: <AggregatesTab />,+ label: 'Series',+ content: <SeriesTab />,'data-attr': 'metrics-samples-panel-tab-aggregates',disabledReason: metricsViewerDisabledReason ?? undefined,},diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsxindex 1c8ab9ba5df4..fa503fac64fa 100644--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx@@ -15,18 +15,22 @@ import type {} from 'products/metrics/frontend/generated/api.schemas'import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'-import { formatSeriesNames, seriesColor } from './metricsSeries'+import { formatSeriesNamesParts, seriesColor } from './metricsSeries'import { type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'-// The side panel next to the chart: per-series aggregates, or the raw emissions+// The side panel next to the chart: per-series totals, or the raw emissions// behind the chart with their trace linkage (the metric->trace pivot).+// pinned: "aggregates" is the Series tab key and an analytics event value. Renaming it breaks dashboards.export type MetricsPanelTab = 'aggregates' | 'samples'export const SAMPLES_LIMIT = 50-// One row of the Aggregates tab: a series with its headline numbers.-export interface MetricsAggregateRow {+// One row of the Series tab: a series with its headline numbers.+export interface MetricsSeriesRow {name: string+ /** One `key=value` label per entry, for the expanded row. */+ nameParts: string[]+ hasLabels: booleancolor: stringlatest: numbertotal: number@@ -52,11 +56,11 @@ export interface metricsSamplesLogicValues {currentTeamId: number | null // teamLogictimezone: string // teamLogicactiveTab: MetricsPanelTab- aggregateRows: MetricsAggregateRow[]errorSpikes: _MetricErrorSpikeApi[]errorSpikesLoading: booleansamples: _MetricEventSampleApi[]samplesLoading: boolean+ seriesRows: MetricsSeriesRow[]showErrorSpikes: booleantraceExemplars: MetricsTraceExemplar[]}@@ -138,10 +142,10 @@ export interface metricsSamplesLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricsSamplesLogicMeta {__keaTypeGenInternalSelectorTypes: {- aggregateRows: (+ seriesRows: (queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[],metricName: string- ) => MetricsAggregateRow[]+ ) => MetricsSeriesRow[]traceExemplars: (samples: _MetricEventSampleApi[]) => MetricsTraceExemplar[]}}@@ -248,18 +252,20 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([],})),selectors({- // Rows for the Aggregates tab, derived from the chart's series so both+ // Rows for the Series tab, derived from the chart's series so both// views always describe the same query (colors match the chart legend).- aggregateRows: [+ seriesRows: [(s) => [s.queryResults, s.metricName],- (queryResults: MetricsViewerSeries[], metricName: string): MetricsAggregateRow[] => {- const names = formatSeriesNames(queryResults, metricName)+ (queryResults: MetricsViewerSeries[], metricName: string): MetricsSeriesRow[] => {+ const nameParts = formatSeriesNamesParts(queryResults, metricName)return queryResults.map((series, index) => {// Null points are gaps (unrepresentable buckets) — skip them// rather than counting them as zero.const values = series.points.map((point) => point.value).filter((value) => value !== null)return {- name: names[index],+ name: nameParts[index].join(', '),+ nameParts: nameParts[index],+ hasLabels: Object.keys(series.labels ?? {}).length > 0,color: seriesColor(index),latest: values.length ? values[values.length - 1] : 0,total: values.reduce((sum, value) => sum + value, 0),diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.tsindex a8e637e56910..158526e8fa03 100644--- a/products/metrics/frontend/components/metricsSeries.ts+++ b/products/metrics/frontend/components/metricsSeries.ts@@ -19,22 +19,25 @@ export const seriesColor = (index: number): string => `data-color-${(index % SERtype NamableSeries = Pick<_MetricSeriesApi, 'labels' | 'metric_name'> & { clause?: string | null }-// Human-readable series name from its label map (e.g. "service.name=checkout, env=prod"),+// Human-readable series name parts from its label map (e.g. ["service.name=checkout", "env=prod"]),// falling back to the metric name then a provided default for ungrouped/unlabelled series.-const formatSeriesName = (series: NamableSeries, fallback: string, showClause: boolean): string => {+const formatSeriesNameParts = (series: NamableSeries, fallback: string, showClause: boolean): string[] => {const prefix = showClause && series.clause ? `${series.clause} · ` : ''const entries = Object.entries(series.labels ?? {})- if (entries.length > 0) {- return prefix + entries.map(([key, value]) => `${key}=${value}`).join(', ')- }- return prefix + (series.metric_name ?? fallback)+ const parts =+ entries.length > 0 ? entries.map(([key, value]) => `${key}=${value}`) : [series.metric_name ?? fallback]+ return [prefix + parts[0], ...parts.slice(1)]}/** Display names for a whole chart's series, index-aligned with the input. The clause* alias prefixes each name (e.g. "a · env=prod") only when the list plots more than* one clause — that is the case where two ungrouped series would otherwise collide,* and deciding here keeps every consumer (legend, aggregates table) in agreement. */-export const formatSeriesNames = (seriesList: NamableSeries[], fallback: string): string[] => {+export const formatSeriesNames = (seriesList: NamableSeries[], fallback: string): string[] =>+ formatSeriesNamesParts(seriesList, fallback).map((parts) => parts.join(', '))++/** Like `formatSeriesNames`, but keeps each `key=value` label as its own part. */+export const formatSeriesNamesParts = (seriesList: NamableSeries[], fallback: string): string[][] => {const showClause = new Set(seriesList.map((s) => s.clause).filter(Boolean)).size > 1- return seriesList.map((series) => formatSeriesName(series, fallback, showClause))+ return seriesList.map((series) => formatSeriesNameParts(series, fallback, showClause))}diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.tsindex b093d7a5c2ff..80d468855913 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts@@ -151,6 +151,9 @@ export interface metricsUsageTrackingLogicActions {sampleRowExpanded: (sample: _MetricEventSampleApi) => {sample: _MetricEventSampleApi}+ seriesRowExpanded: () => {+ value: true+ }tracePivotClicked: (sample: _MetricEventSampleApi) => {sample: _MetricEventSampleApi}@@ -226,6 +229,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([})),actions({// Component-only interactions with no source-logic action to listen to.+ seriesRowExpanded: true,sampleRowExpanded: (sample: _MetricEventSampleApi) => ({ sample }),tracePivotClicked: (sample: _MetricEventSampleApi) => ({ sample }),exemplarDotClicked: (hasSpanId: boolean) => ({ hasSpanId }),@@ -372,6 +376,9 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([trace_coverage: samples.length ? Math.round((100 * withTrace) / samples.length) : 0,})},+ seriesRowExpanded: () => {+ posthog.capture('metrics series row expanded')+ },sampleRowExpanded: ({ sample }) => {posthog.capture('metrics sample row expanded', {attribute_count: Object.keys(sample.attributes).length + Object.keys(sample.resource_attributes).length,