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.

fix(insights): truncate long breakdown labels in hog-charts bar chart (#61116)

Sam Pennington520a68a4eb0e
diff --git a/frontend/src/lib/hog-charts/core/Chart.tsx b/frontend/src/lib/hog-charts/core/Chart.tsx
index aca74efc2210..745c93fa3d72 100644
--- a/frontend/src/lib/hog-charts/core/Chart.tsx
+++ b/frontend/src/lib/hog-charts/core/Chart.tsx
@@ -147,6 +147,7 @@ export function Chart<Meta = unknown>({
isPercent = false,
animateHover,
margins: marginsOverride,
+ maxCategoryLabelWidth,
} = config ?? {}
const hoverAnimationMs = resolveHoverAnimationMs(animateHover)
const interactionAxis: 'x' | 'y' = axisOrientation === 'horizontal' ? 'y' : 'x'
@@ -168,6 +169,7 @@ export function Chart<Meta = unknown>({
axisOrientation,
override: marginsOverride,
valueRangeSeries,
+ maxCategoryLabelWidth,
})
const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({ margins })
@@ -310,6 +312,7 @@ export function Chart<Meta = unknown>({
axisColor={axisColor}
orientation={axisOrientation}
labelToCoord={labelToCoord}
+ maxCategoryLabelWidth={maxCategoryLabelWidth}
/>
<AxisTitles
xAxisLabel={xAxisLabel}
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
index 739c40a31c5f..60be84b80c96 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
@@ -34,11 +34,15 @@ interface UseChartMarginsOptions {
* passes the whisker min/max samples so the y-tick column fits the actual range, not just
* the medians it draws on `series.data`. yAxis-id discovery still reads from `series`. */
valueRangeSeries?: Series[]
+ /** When set, clamp the reserved category-label width to this ceiling so a single long label
+ * can't grow the axis margin without bound. Mirrors AxisLabels' display truncation. */
+ maxCategoryLabelWidth?: number
}
function widestCategoryLabelWidth(
labels: string[],
- xTickFormatter: ((value: string, index: number) => string | null) | undefined
+ xTickFormatter: ((value: string, index: number) => string | null) | undefined,
+ maxCategoryLabelWidth = 0
): number {
let widest = 0
for (let i = 0; i < labels.length; i++) {
@@ -48,7 +52,7 @@ function widestCategoryLabelWidth(
}
widest = Math.max(widest, measureLabelWidth(text))
}
- return widest
+ return maxCategoryLabelWidth > 0 ? Math.min(widest, maxCategoryLabelWidth) : widest
}
function widestValueLabelWidth(series: Series[], yTickFormatter: ((value: number) => string) | undefined): number {
@@ -82,6 +86,7 @@ export function useChartMargins({
axisOrientation = 'vertical',
override,
valueRangeSeries,
+ maxCategoryLabelWidth = 0,
}: UseChartMarginsOptions): ChartMargins {
const isHorizontal = axisOrientation === 'horizontal'
const valueSeries = valueRangeSeries ?? series
@@ -100,10 +105,10 @@ export function useChartMargins({
return 0
}
if (isHorizontal) {
- return widestCategoryLabelWidth(labels, xTickFormatter)
+ return widestCategoryLabelWidth(labels, xTickFormatter, maxCategoryLabelWidth)
}
return widestValueLabelWidth(valueSeries, yTickFormatter)
- }, [valueSeries, yTickFormatter, hideYAxis, isHorizontal, labels, xTickFormatter])
+ }, [valueSeries, yTickFormatter, hideYAxis, isHorizontal, labels, xTickFormatter, maxCategoryLabelWidth])
const xLabelHalfWidth = useMemo<number>(() => {
if (hideXAxis) {
@@ -116,8 +121,8 @@ export function useChartMargins({
if (labels.length === 0) {
return 0
}
- return Math.ceil(widestCategoryLabelWidth(labels, xTickFormatter) / 2)
- }, [labels, xTickFormatter, hideXAxis, isHorizontal, valueSeries, yTickFormatter])
+ return Math.ceil(widestCategoryLabelWidth(labels, xTickFormatter, maxCategoryLabelWidth) / 2)
+ }, [labels, xTickFormatter, hideXAxis, isHorizontal, valueSeries, yTickFormatter, maxCategoryLabelWidth])
return useMemo<ChartMargins>(() => {
const bottom = hideXAxis
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 97be43aba06e..d6b3c548ca66 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -192,6 +192,10 @@ export interface ChartConfig {
* that want the plot area flush with the canvas edges (e.g. `{ left: 0, right: 0, top: 0, bottom: 0 }`).
* Should be referentially stable — pass a module-level constant rather than an inline object. */
margins?: Partial<ChartMargins>
+ /** Max pixel width for category (band) tick labels before they're truncated with an ellipsis,
+ * with the full value revealed on hover. Also clamps the axis margin to this width so a long
+ * label can't push the plot off screen. Omit (default) to render labels untruncated. */
+ maxCategoryLabelWidth?: number
}
export interface TooltipConfig {
diff --git a/frontend/src/lib/hog-charts/overlays/AxisLabels.test.ts b/frontend/src/lib/hog-charts/overlays/AxisLabels.test.ts
new file mode 100644
index 000000000000..c334525088d6
--- /dev/null
+++ b/frontend/src/lib/hog-charts/overlays/AxisLabels.test.ts
@@ -0,0 +1,41 @@
+import { measureLabelWidth } from '../utils/text-measure'
+import { computeVisibleXLabels } from './AxisLabels'
+
+describe('computeVisibleXLabels', () => {
+ const longUrl = 'https://app.posthog.com/project/1/insights/abc123/edit?with=a&very=long&query=string'
+ // Spread labels far apart so the overlap filter keeps every candidate — we only assert truncation here.
+ const wideScale =
+ (labels: string[]) =>
+ (label: string): number =>
+ labels.indexOf(label) * 10000
+
+ it('leaves title undefined for every label when no max width is set', () => {
+ const labels = ['short', longUrl]
+ const visible = computeVisibleXLabels(labels, wideScale(labels), undefined, 0)
+
+ expect(visible).toHaveLength(2)
+ expect(visible.every((v) => v.title === undefined)).toBe(true)
+ expect(visible.every((v) => v.text === labels[v.index])).toBe(true)
+ })
+
+ it('sets title to the full value only on labels that were truncated', () => {
+ const labels = ['short', longUrl]
+ // Budget fits "short" but not the URL, so only the URL truncates.
+ const budget = measureLabelWidth(longUrl) / 2
+ const visible = computeVisibleXLabels(labels, wideScale(labels), undefined, budget)
+
+ const short = visible.find((v) => v.index === 0)
+ const long = visible.find((v) => v.index === 1)
+ expect(short?.title).toBeUndefined()
+ expect(short?.text).toBe('short')
+ expect(long?.title).toBe(longUrl)
+ expect(long?.text.endsWith('…')).toBe(true)
+ })
+
+ it('drops labels whose scale returns null', () => {
+ const labels = ['a', 'b']
+ const visible = computeVisibleXLabels(labels, (label) => (label === 'a' ? 0 : undefined))
+
+ expect(visible.map((v) => v.index)).toEqual([0])
+ })
+})
diff --git a/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx b/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx
index 2e5792f08a03..4b6f535e29a2 100644
--- a/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx
+++ b/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx
@@ -1,7 +1,7 @@
import React, { useMemo } from 'react'
import { useChartLayout } from '../core/chart-context'
-import { AXIS_LABEL_FONT, getTextMeasureCtx } from '../utils/text-measure'
+import { AXIS_LABEL_FONT, getTextMeasureCtx, truncateToWidth } from '../utils/text-measure'
interface AxisLabelsProps {
xTickFormatter?: (value: string, index: number) => string | null
@@ -15,26 +15,47 @@ interface AxisLabelsProps {
/** Optional override for label → coord mapping. Falls back to `scales.x`, which chart types
* serving horizontal orientation are expected to set to a label→band-center function. */
labelToCoord?: (label: string) => number | undefined
+ /** When set, truncate category tick labels wider than this (px) with an ellipsis and reveal
+ * the full value on hover. Omitted (default) renders labels untruncated. */
+ maxCategoryLabelWidth?: number
}
const LABEL_PADDING = 20
+interface XLabelCandidate {
+ index: number
+ /** Display text — truncated to `maxCategoryLabelWidth` when one is set. */
+ text: string
+ /** Full value, present only when `text` was truncated, so hover can reveal it. */
+ title?: string
+ x: number
+}
+
+/** Truncate a category label for display; carry the full value as `title` only when it was cut. */
+function truncateWithTitle(fullText: string, maxCategoryLabelWidth: number): { text: string; title?: string } {
+ const text = truncateToWidth(fullText, maxCategoryLabelWidth)
+ return { text, title: text === fullText ? undefined : fullText }
+}
+
export function computeVisibleXLabels(
labels: string[],
xScale: (label: string) => number | undefined,
- formatter?: (value: string, index: number) => string | null
-): { index: number; text: string; x: number }[] {
- const candidates: { index: number; text: string; x: number }[] = []
+ formatter?: (value: string, index: number) => string | null,
+ maxCategoryLabelWidth = 0
+): XLabelCandidate[] {
+ const candidates: XLabelCandidate[] = []
for (let i = 0; i < labels.length; i++) {
const x = xScale(labels[i])
if (x == null) {
continue
}
- const text = formatter ? formatter(labels[i], i) : labels[i]
- if (text === null) {
+ const fullText = formatter ? formatter(labels[i], i) : labels[i]
+ if (fullText === null) {
continue
}
- candidates.push({ index: i, text, x })
+ // The truncated text drives both display and overlap measurement below.
+ const { text, title } = truncateWithTitle(fullText, maxCategoryLabelWidth)
+ candidates.push({ index: i, text, title, x })
}
if (candidates.length === 0) {
@@ -49,7 +70,7 @@ export function computeVisibleXLabels(
const widths = candidates.map((c) => ctx.measureText(c.text).width)
- const visible: { index: number; text: string; x: number }[] = []
+ const visible: XLabelCandidate[] = []
let lastRightEdge = -Infinity
for (let i = 0; i < candidates.length; i++) {
@@ -82,6 +103,12 @@ interface ChartBox {
plotHeight: number
}
+// When a label is truncated, `title` carries the full value so it can be revealed on hover.
+// Hovering needs pointer events, which the base style disables, so re-enable them just for titled labels.
+const TITLE_POINTER_STYLE: React.CSSProperties = { pointerEvents: 'auto' }
+const NO_POINTER_STYLE: React.CSSProperties = {}
+const titleStyle = (title?: string): React.CSSProperties => (title ? TITLE_POINTER_STYLE : NO_POINTER_STYLE)
+
function YTickLabel({
y,
side,
@@ -89,6 +116,7 @@ function YTickLabel({
text,
color,
dataAttr,
+ title,
}: {
y: number
side: 'left' | 'right'
@@ -96,13 +124,18 @@ function YTickLabel({
text: string
color: string
dataAttr: string
+ title?: string
}): React.ReactElement {
const edge =
side === 'left'
? { right: box.width - box.plotLeft + TICK_GAP }
: { left: box.plotLeft + box.plotWidth + TICK_GAP }
return (
- <div data-attr={dataAttr} style={{ ...TICK_STYLE_BASE, ...edge, top: y, transform: 'translateY(-50%)', color }}>
+ <div
+ data-attr={dataAttr}
+ title={title}
+ style={{ ...TICK_STYLE_BASE, ...titleStyle(title), ...edge, top: y, transform: 'translateY(-50%)', color }}
+ >
{text}
</div>
)
@@ -114,18 +147,22 @@ function XTickLabel({
text,
color,
dataAttr,
+ title,
}: {
x: number
box: ChartBox
text: string
color: string
dataAttr: string
+ title?: string
}): React.ReactElement {
return (
<div
data-attr={dataAttr}
+ title={title}
style={{
...TICK_STYLE_BASE,
+ ...titleStyle(title),
left: x,
top: box.plotTop + box.plotHeight + TICK_GAP,
transform: 'translateX(-50%)',
@@ -137,7 +174,7 @@ function XTickLabel({
)
}
-export function AxisLabels({
+export const AxisLabels = React.memo(function AxisLabels({
xTickFormatter,
yTickFormatter,
yRightTickFormatter,
@@ -146,6 +183,7 @@ export function AxisLabels({
axisColor = 'rgba(0, 0, 0, 0.5)',
orientation = 'vertical',
labelToCoord,
+ maxCategoryLabelWidth = 0,
}: AxisLabelsProps): React.ReactElement | null {
const { scales, dimensions, labels } = useChartLayout()
const yTicks = scales.yTicks()
@@ -160,8 +198,10 @@ export function AxisLabels({
const visibleXLabels = useMemo(
() =>
- hideXAxis || orientation === 'horizontal' ? [] : computeVisibleXLabels(labels, scales.x, xTickFormatter),
- [hideXAxis, labels, scales.x, xTickFormatter, orientation]
+ hideXAxis || orientation === 'horizontal'
+ ? []
+ : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth),
+ [hideXAxis, labels, scales.x, xTickFormatter, orientation, maxCategoryLabelWidth]
)
const rightFormatter = yRightTickFormatter ?? yTickFormatter
@@ -174,14 +214,15 @@ export function AxisLabels({
<>
{!hideYAxis &&
labels.map((labelText, i) => {
- const text = xTickFormatter ? xTickFormatter(labelText, i) : labelText
- if (text === null) {
+ const fullText = xTickFormatter ? xTickFormatter(labelText, i) : labelText
+ if (fullText === null) {
return null
}
const y = labelToY(labelText)
if (y == null || !isFinite(y)) {
return null
}
+ const { text, title } = truncateWithTitle(fullText, maxCategoryLabelWidth)
return (
<YTickLabel
key={`y-cat-${i}`}
@@ -189,6 +230,7 @@ export function AxisLabels({
side="left"
box={dimensions}
text={text}
+ title={title}
color={axisColor}
dataAttr="hog-chart-axis-tick-y"
/>
@@ -259,16 +301,17 @@ export function AxisLabels({
)
})}
- {visibleXLabels.map(({ index, text, x }) => (
+ {visibleXLabels.map(({ index, text, title, x }) => (
<XTickLabel
key={`x-${index}`}
x={x}
box={dimensions}
text={text}
+ title={title}
color={axisColor}
dataAttr="hog-chart-axis-tick-x"
/>
))}
</>
)
-}
+})
diff --git a/frontend/src/lib/hog-charts/utils/text-measure.test.ts b/frontend/src/lib/hog-charts/utils/text-measure.test.ts
new file mode 100644
index 000000000000..32e9de6a97ed
--- /dev/null
+++ b/frontend/src/lib/hog-charts/utils/text-measure.test.ts
@@ -0,0 +1,30 @@
+import { ELLIPSIS, MAX_CATEGORY_LABEL_WIDTH, measureLabelWidth, truncateToWidth } from './text-measure'
+
+describe('truncateToWidth', () => {
+ const longUrl = 'https://app.posthog.com/project/1/insights/abc123/edit?with=a&very=long&query=string'
+
+ it('returns the original string when it already fits', () => {
+ expect(truncateToWidth('short', MAX_CATEGORY_LABEL_WIDTH)).toBe('short')
+ })
+
+ it('returns the original string for a non-positive max width', () => {
+ expect(truncateToWidth(longUrl, 0)).toBe(longUrl)
+ expect(truncateToWidth(longUrl, -10)).toBe(longUrl)
+ })
+
+ it('truncates with a trailing ellipsis and fits within the budget', () => {
+ // Derive the budget from the actual measured width so the assertion holds regardless of the
+ // canvas measurement backend (real canvas vs jsdom mock vs SSR fallback).
+ const budget = measureLabelWidth(longUrl) / 2
+ const result = truncateToWidth(longUrl, budget)
+ expect(result).not.toBe(longUrl)
+ expect(result.endsWith(ELLIPSIS)).toBe(true)
+ expect(result.length).toBeLessThan(longUrl.length)
+ expect(measureLabelWidth(result)).toBeLessThanOrEqual(budget)
+ })
+
+ it('collapses to a bare ellipsis when the budget is narrower than the ellipsis', () => {
+ const ellipsisWidth = measureLabelWidth(ELLIPSIS)
+ expect(truncateToWidth(longUrl, ellipsisWidth - 0.01)).toBe(ELLIPSIS)
+ })
+})
diff --git a/frontend/src/lib/hog-charts/utils/text-measure.ts b/frontend/src/lib/hog-charts/utils/text-measure.ts
index e59bbb358693..df43291d9602 100644
--- a/frontend/src/lib/hog-charts/utils/text-measure.ts
+++ b/frontend/src/lib/hog-charts/utils/text-measure.ts
@@ -4,6 +4,13 @@
export const AXIS_LABEL_FONT =
'12px -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif'
+export const ELLIPSIS = '…'
+
+/** Largest pixel width a category (breakdown) tick label may occupy before it's truncated
+ * with an ellipsis. Without this, long breakdown values — most notably URLs — grow the axis
+ * margin to fit the widest label and push the plot off screen. */
+export const MAX_CATEGORY_LABEL_WIDTH = 160
+
let measureCtx: CanvasRenderingContext2D | null = null
export function getTextMeasureCtx(): CanvasRenderingContext2D | null {
if (!measureCtx) {
@@ -21,3 +28,26 @@ export function measureLabelWidth(text: string, font: string = AXIS_LABEL_FONT):
ctx.font = font
return ctx.measureText(text).width
}
+
+/** Truncate `text` with a trailing ellipsis so its rendered width fits within `maxWidth`.
+ * Returns the original string when it already fits, or when `maxWidth` is non-positive. */
+export function truncateToWidth(text: string, maxWidth: number, font: string = AXIS_LABEL_FONT): string {
+ if (maxWidth <= 0 || measureLabelWidth(text, font) <= maxWidth) {
+ return text
+ }
+ if (measureLabelWidth(ELLIPSIS, font) >= maxWidth) {
+ return ELLIPSIS
+ }
+ let low = 0
+ let high = text.length
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2)
+ const candidate = `${text.slice(0, mid).trimEnd()}${ELLIPSIS}`
+ if (measureLabelWidth(candidate, font) <= maxWidth) {
+ low = mid
+ } else {
+ high = mid - 1
+ }
+ }
+ return `${text.slice(0, low).trimEnd()}${ELLIPSIS}`
+}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index 424a4c5fdb50..880cd43ca077 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -11,6 +11,7 @@ import {
ValueLabels,
} from 'lib/hog-charts'
import type { BarChartConfig, PointClickData, TimeSeriesBarChartConfig, TooltipContext } from 'lib/hog-charts'
+import { MAX_CATEGORY_LABEL_WIDTH } from 'lib/hog-charts/utils/text-measure'
import { percentage } from 'lib/utils'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
@@ -237,6 +238,9 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
xTickFormatter,
xAxisLabel: trendsFilter?.xAxisLabel,
yAxisLabel: trendsFilter?.yAxisLabel,
+ // Breakdown values become category (y-axis) labels here; truncate long ones (e.g. URLs)
+ // so they don't grow the margin and push the plot off screen. Full value shows on hover.
+ maxCategoryLabelWidth: MAX_CATEGORY_LABEL_WIDTH,
// On a dashboard the tile is a fixed height: fit the rows that fit instead of growing
// the tile and scrolling. On the full insight page, keep the grow-to-fit-all behavior.
bars: { fitToHeight: isInDashboardContext },