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(metrics): hide shared series labels and scroll long ones (#117057)

Frank Hamandaf0d984b8463
diff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsx
index ef915be10f5f..095726161d88 100644
--- a/products/metrics/frontend/components/MetricsSamplesPanel.tsx
+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx
@@ -1,6 +1,6 @@
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
-import { Fragment, useState } from 'react'
+import { Fragment, useEffect, useRef, useState } from 'react'
import { IconCollapse, IconExpand } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
@@ -9,11 +9,13 @@ import { getColorVar } from 'lib/colors'
import { TZLabel } from 'lib/components/TZLabel'
import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
-import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbers'
import { teamLogic } from 'scenes/teamLogic'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { LogRowScrollButtons } from 'products/logs/frontend/components/VirtualizedLogsList/LogRowScrollButtons'
+
import { type MetricsSeriesRow, type MetricsPanelTab, metricsSamplesLogic } from './metricsSamplesLogic'
import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'
import { metricsViewerLogic } from './metricsViewerLogic'
@@ -109,28 +111,68 @@ function SamplesTab(): JSX.Element {
)
}
-const SEPARATOR_SEGMENTS = /[^/._:-]*[/._:-]?/g
+const SCROLL_INTERVAL_MS = 16
+const SCROLL_STEP_PX = 8
+
+/** Scrolls long labels sideways, with hold-to-scroll buttons on hover as in the logs table. */
+function HorizontalScroll({ children, className }: { children: React.ReactNode; className?: string }): JSX.Element {
+ const scrollRef = useRef<HTMLDivElement>(null)
+ const contentRef = useRef<HTMLDivElement>(null)
+ const intervalRef = useRef<number | null>(null)
+ const [canScroll, setCanScroll] = useState(false)
-/** 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 stopScrolling = (): void => {
+ if (intervalRef.current !== null) {
+ clearInterval(intervalRef.current)
+ intervalRef.current = null
+ }
}
- const value = part.slice(separatorIndex + 1)
- const segments = wrap ? (value.match(SEPARATOR_SEGMENTS)?.filter(Boolean) ?? [value]) : [value]
+ const startScrolling = (direction: 'left' | 'right'): void => {
+ stopScrolling()
+ const step = (): void =>
+ scrollRef.current?.scrollBy({ left: direction === 'left' ? -SCROLL_STEP_PX : SCROLL_STEP_PX })
+ step()
+ intervalRef.current = window.setInterval(step, SCROLL_INTERVAL_MS)
+ }
+ useEffect(() => stopScrolling, [])
+
+ return (
+ <div
+ className={clsx('relative min-w-0 group/scroll', className)}
+ onMouseEnter={() => {
+ const element = scrollRef.current
+ const content = contentRef.current
+ setCanScroll(!!element && !!content && content.offsetWidth > element.clientWidth)
+ }}
+ >
+ <div ref={scrollRef} className="overflow-x-auto hide-scrollbar whitespace-nowrap">
+ <div className="flex w-max">
+ <div ref={contentRef}>{children}</div>
+ {/* Lets the end of the text scroll clear of the buttons. */}
+ {canScroll && <div className="w-20 shrink-0" />}
+ </div>
+ </div>
+ {canScroll && (
+ <LogRowScrollButtons
+ onStartScrolling={startScrolling}
+ onStopScrolling={stopScrolling}
+ className="group-hover/scroll:opacity-100"
+ />
+ )}
+ </div>
+ )
+}
+
+function LabelValue({ value }: { value: string }): JSX.Element {
+ return value ? <>{value}</> : <span className="text-tertiary italic">(empty)</span>
+}
+
+/** Compact so the series column keeps its width. The tooltip has the exact value. */
+function SeriesValue({ value }: { value: number }): JSX.Element {
return (
- <>
- <span className="text-tertiary">{part.slice(0, separatorIndex + 1)}</span>
- {segments.map((segment, index) => (
- <Fragment key={index}>
- {wrap && <wbr />}
- {segment}
- </Fragment>
- ))}
- </>
+ <Tooltip title={humanFriendlyNumber(value, 2)}>
+ <span className="font-mono">{humanFriendlyLargeNumber(value)}</span>
+ </Tooltip>
)
}
@@ -139,6 +181,8 @@ function SeriesTab(): JSX.Element {
const { queryLoading, hasMetricName } = useValues(metricsViewerLogic)
const { seriesRowExpanded } = useActions(metricsUsageTrackingLogic)
const [expandedNames, setExpandedNames] = useState<string[]>([])
+ // A row can lose its distinct labels after a filter change while its name stays in expandedNames.
+ const isRowExpanded = (row: MetricsSeriesRow): boolean => row.labels.length > 0 && expandedNames.includes(row.name)
return (
<LemonTable
@@ -147,22 +191,22 @@ function SeriesTab(): JSX.Element {
size="small"
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)}
+ rowClassName={(row) => (isRowExpanded(row) ? '[&>td]:align-top' : null)}
columns={[
{
key: 'toggle',
width: 0,
render: (_, row) => {
- if (!row.hasLabels) {
+ if (!row.labels.length) {
return null
}
- const isExpanded = expandedNames.includes(row.name)
+ const isExpanded = isRowExpanded(row)
return (
<LemonButton
noPadding
active={isExpanded}
icon={isExpanded ? <IconCollapse /> : <IconExpand />}
- title={isExpanded ? 'Show less' : 'Show full series name'}
+ title={isExpanded ? 'Show less' : 'Show the labels of this series'}
onClick={() => {
if (isExpanded) {
setExpandedNames(expandedNames.filter((name) => name !== row.name))
@@ -181,7 +225,7 @@ function SeriesTab(): JSX.Element {
key: 'series',
width: '100%',
render: (_, row) => {
- const isExpanded = expandedNames.includes(row.name)
+ const isExpanded = isRowExpanded(row)
return (
<span className={clsx('flex gap-1.5', isExpanded ? 'items-start' : 'items-center')}>
<span
@@ -189,26 +233,33 @@ function SeriesTab(): JSX.Element {
// 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>
- )}
+ <HorizontalScroll className="w-0 flex-1">
+ {isExpanded ? (
+ <div className="flex flex-col gap-1">
+ {row.labels.map(([key, value], index) => (
+ <span key={key}>
+ {index === 0 && row.prefix}
+ <span className="text-tertiary">{key}=</span>
+ <LabelValue value={value} />
+ </span>
+ ))}
+ </div>
+ ) : (
+ <span title={row.name}>
+ {row.labels.length
+ ? [
+ row.prefix,
+ ...row.labels.map(([key, value], index) => (
+ <Fragment key={key}>
+ {index > 0 && <span className="text-tertiary"> · </span>}
+ <LabelValue value={value} />
+ </Fragment>
+ )),
+ ]
+ : row.fallbackName}
+ </span>
+ )}
+ </HorizontalScroll>
</span>
)
},
@@ -217,13 +268,13 @@ function SeriesTab(): JSX.Element {
title: 'Latest',
key: 'latest',
align: 'right',
- render: (_, row) => <span className="font-mono">{humanFriendlyNumber(row.latest, 2)}</span>,
+ render: (_, row) => <SeriesValue value={row.latest} />,
},
{
title: 'Total',
key: 'total',
align: 'right',
- render: (_, row) => <span className="font-mono">{humanFriendlyNumber(row.total, 2)}</span>,
+ render: (_, row) => <SeriesValue value={row.total} />,
},
]}
/>
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
index fa503fac64fa..b854bbf5d940 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -15,7 +15,13 @@ import type {
} from 'products/metrics/frontend/generated/api.schemas'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
-import { formatSeriesNamesParts, seriesColor } from './metricsSeries'
+import {
+ type SeriesLabel,
+ distinctSeriesLabels,
+ formatSeriesNames,
+ seriesColor,
+ seriesNamePrefixes,
+} from './metricsSeries'
import { type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'
// The side panel next to the chart: per-series totals, or the raw emissions
@@ -27,10 +33,14 @@ export const SAMPLES_LIMIT = 50
// One row of the Series tab: a series with its headline numbers.
export interface MetricsSeriesRow {
+ /** Full name with every label, also the row key. */
name: string
- /** One `key=value` label per entry, for the expanded row. */
- nameParts: string[]
- hasLabels: boolean
+ /** Clause alias ("a · "), set when the chart plots more than one clause. */
+ prefix: string
+ /** Labels that differ between series. */
+ labels: SeriesLabel[]
+ /** Shown when no label differs: the clause alias or the metric name. */
+ fallbackName: string
color: string
latest: number
total: number
@@ -257,15 +267,18 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
seriesRows: [
(s) => [s.queryResults, s.metricName],
(queryResults: MetricsViewerSeries[], metricName: string): MetricsSeriesRow[] => {
- const nameParts = formatSeriesNamesParts(queryResults, metricName)
+ const names = formatSeriesNames(queryResults, metricName)
+ const prefixes = seriesNamePrefixes(queryResults)
+ const distinctLabels = distinctSeriesLabels(queryResults)
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: nameParts[index].join(', '),
- nameParts: nameParts[index],
- hasLabels: Object.keys(series.labels ?? {}).length > 0,
+ name: names[index],
+ prefix: prefixes[index],
+ labels: distinctLabels[index],
+ fallbackName: (prefixes[index] && series.clause) || series.metric_name || metricName,
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.test.ts b/products/metrics/frontend/components/metricsSeries.test.ts
new file mode 100644
index 000000000000..4bcf1e929ec2
--- /dev/null
+++ b/products/metrics/frontend/components/metricsSeries.test.ts
@@ -0,0 +1,32 @@
+import { type SeriesLabel, distinctSeriesLabels } from './metricsSeries'
+
+describe('distinctSeriesLabels', () => {
+ it.each<{ name: string; labels: Record<string, string>[]; distinct: SeriesLabel[][] }>([
+ {
+ name: 'drops labels with the same value on every series',
+ labels: [
+ { app: 'checkout', route: '/cart' },
+ { app: 'checkout', route: '/pay' },
+ ],
+ distinct: [[['route', '/cart']], [['route', '/pay']]],
+ },
+ {
+ name: 'keeps a label that one series does not have',
+ labels: [{ app: 'checkout', route: '/cart' }, { route: '/pay' }],
+ distinct: [
+ [
+ ['app', 'checkout'],
+ ['route', '/cart'],
+ ],
+ [['route', '/pay']],
+ ],
+ },
+ {
+ name: 'keeps every label of a single series',
+ labels: [{ app: 'checkout' }],
+ distinct: [[['app', 'checkout']]],
+ },
+ ])('$name', ({ labels, distinct }) => {
+ expect(distinctSeriesLabels(labels.map((seriesLabels) => ({ labels: seriesLabels })))).toEqual(distinct)
+ })
+})
diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.ts
index 2a93f86b8b4c..259a2255cbb7 100644
--- a/products/metrics/frontend/components/metricsSeries.ts
+++ b/products/metrics/frontend/components/metricsSeries.ts
@@ -19,25 +19,43 @@ export const seriesColor = (index: number): string => `data-color-${(index % SER
type NamableSeries = Pick<_MetricSeriesApi, 'labels' | 'metric_name'> & { clause?: string | null }
-// Human-readable series name parts from its label map (e.g. ["service.name=checkout", "env=prod"]),
+export type SeriesLabel = [key: string, value: string]
+
+/** Clause alias prefix ("a · ") per series. Empty unless the list plots more than one clause. */
+export const seriesNamePrefixes = (seriesList: NamableSeries[]): string[] => {
+ const showClause = new Set(seriesList.map((s) => s.clause).filter(Boolean)).size > 1
+ return seriesList.map((series) => (showClause && series.clause ? `${series.clause} · ` : ''))
+}
+
+// Human-readable series name 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 formatSeriesNameParts = (series: NamableSeries, fallback: string, showClause: boolean): string[] => {
- const prefix = showClause && series.clause ? `${series.clause} · ` : ''
+const formatSeriesName = (series: NamableSeries, fallback: string, prefix: string): string => {
const entries = Object.entries(series.labels ?? {})
- const parts =
- entries.length > 0 ? entries.map(([key, value]) => `${key}=${value}`) : [series.metric_name ?? fallback]
- return [prefix + parts[0], ...parts.slice(1)]
+ if (entries.length > 0) {
+ return prefix + entries.map(([key, value]) => `${key}=${value}`).join(', ')
+ }
+ return prefix + (series.metric_name ?? fallback)
}
/** 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[] =>
- formatSeriesNamesParts(seriesList, fallback).map((parts) => parts.join(', '))
+ * and deciding here keeps every consumer (legend, series table) in agreement. */
+export const formatSeriesNames = (seriesList: NamableSeries[], fallback: string): string[] => {
+ const prefixes = seriesNamePrefixes(seriesList)
+ return seriesList.map((series, index) => formatSeriesName(series, fallback, prefixes[index]))
+}
-/** 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) => formatSeriesNameParts(series, fallback, showClause))
+/** Per series, the labels that differ between series. Labels with the same value on every series
+ * (e.g. Kubernetes app labels) are dropped. A single series keeps all its labels. */
+export const distinctSeriesLabels = (seriesList: Pick<NamableSeries, 'labels'>[]): SeriesLabel[][] => {
+ const [first, ...rest] = seriesList
+ const sharedKeys = new Set(
+ rest.length > 0
+ ? Object.entries(first.labels ?? {})
+ .filter(([key, value]) => rest.every((series) => series.labels?.[key] === value))
+ .map(([key]) => key)
+ : []
+ )
+ return seriesList.map((series) => Object.entries(series.labels ?? {}).filter(([key]) => !sharedKeys.has(key)))
}