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.

refactor(hog-charts): dedupe helpers and tighten overlay rendering (#58147)

Sam Pennington2199010b70b8
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index 885e1d7f6cc2..5d449fd96f38 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -6,6 +6,7 @@ import { type BarRect, drawBarHighlight, drawBars, drawGrid, type DrawContext }
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import {
+ buildStackedResolveValue,
computePercentStackData,
computeStackData,
createBarScales,
@@ -299,20 +300,7 @@ function BarChartInner<Meta = unknown>({
[stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius]
)
- const resolveValue = useMemo(() => {
- if (!stackedData) {
- return undefined
- }
- // Return the stacked top so the tooltip anchor lands at the visual top of each segment, not the raw series value.
- return (s: Series, dataIndex: number): number => {
- const stacked = stackedData.get(s.key)?.top[dataIndex]
- if (stacked != null && Number.isFinite(stacked)) {
- return stacked
- }
- const raw = s.data[dataIndex]
- return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0
- }
- }, [stackedData])
+ const resolveValue = useMemo(() => buildStackedResolveValue(stackedData), [stackedData])
return (
<Chart
diff --git a/frontend/src/lib/hog-charts/charts/LineChart.tsx b/frontend/src/lib/hog-charts/charts/LineChart.tsx
index 2bff12476da5..944321ded6a7 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart.tsx
@@ -5,9 +5,11 @@ import type { DrawContext } from '../core/canvas-renderer'
import { Chart } from '../core/Chart'
import { ChartErrorBoundary } from '../core/ChartErrorBoundary'
import {
+ buildStackedResolveValue,
computePercentStackData,
computeStackData,
createScales as createLineScales,
+ resolveYScaleForSeries,
yTickCountForHeight,
} from '../core/scales'
import type { ScaleSet, StackedBand } from '../core/scales'
@@ -205,10 +207,6 @@ function LineChartInner<Meta = unknown>({
if (hoverIndex < 0) {
return
}
- const resolveChartYScale = (s: ResolvedSeries): ((value: number) => number) => {
- const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID
- return scales.yAxes?.[axisId]?.scale ?? scales.y
- }
for (const s of coloredSeries) {
if (s.visibility?.excluded || s.fill?.lowerData) {
continue
@@ -221,7 +219,7 @@ function LineChartInner<Meta = unknown>({
}
const data = stackedData?.get(s.key)?.top ?? s.data
const x = scales.x(drawLabels[hoverIndex])
- const y = resolveChartYScale(s)(data[hoverIndex])
+ const y = resolveYScaleForSeries(scales, s)(data[hoverIndex])
if (x != null && isFinite(y)) {
drawHighlightPoint(ctx, x, y, s.color, theme.backgroundColor ?? '#ffffff')
}
@@ -230,19 +228,7 @@ function LineChartInner<Meta = unknown>({
[stackedData]
)
- const resolveValue = useMemo(() => {
- if (!stackedData) {
- return undefined
- }
- return (s: Series, dataIndex: number): number => {
- const stacked = stackedData.get(s.key)?.top[dataIndex]
- if (stacked != null && Number.isFinite(stacked)) {
- return stacked
- }
- const raw = s.data[dataIndex]
- return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0
- }
- }, [stackedData])
+ const resolveValue = useMemo(() => buildStackedResolveValue(stackedData), [stackedData])
return (
<Chart
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index 2c9cb02181ec..3e277d2cbb56 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -18,11 +18,11 @@ import {
type YAxisConfig,
} from '../../utils/use-axis-formatters'
import { BarChart } from '../BarChart/BarChart'
-
-export interface ValueLabelsConfig {
- seriesKeys?: string[]
- formatter?: (value: number) => string
-}
+import {
+ resolveValueLabelsConfig,
+ useSeriesWithValueLabelAllowlist,
+ type ValueLabelsConfig,
+} from '../utils/use-value-labels'
export interface TimeSeriesBarChartConfig {
xAxis?: XAxisConfig
@@ -54,16 +54,6 @@ export interface TimeSeriesBarChartProps<Meta = unknown> {
onError?: (error: Error, info: React.ErrorInfo) => void
}
-function resolveValueLabelsConfig(valueLabels: TimeSeriesBarChartConfig['valueLabels']): ValueLabelsConfig | null {
- if (valueLabels === undefined || valueLabels === false) {
- return null
- }
- if (valueLabels === true) {
- return {}
- }
- return valueLabels
-}
-
export function TimeSeriesBarChart<Meta = unknown>({
series,
labels,
@@ -91,21 +81,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
const yTickFormatter = useYTickFormatter(yAxis)
const valueLabelsConfig = resolveValueLabelsConfig(valueLabels)
-
- // Stable primitive key so callers can pass `valueLabels: { seriesKeys: ['a'] }` inline
- // without re-running the transform on every render.
- const seriesKeysSignature = valueLabelsConfig?.seriesKeys?.join(' ')
- const seriesAfterValueLabels = useMemo(() => {
- const seriesKeys = valueLabelsConfig?.seriesKeys
- if (!seriesKeys) {
- return series
- }
- const allowed = new Set(seriesKeys)
- return series.map((s) =>
- allowed.has(s.key) ? s : { ...s, visibility: { ...s.visibility, valueLabel: false } }
- )
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [series, seriesKeysSignature])
+ const seriesAfterValueLabels = useSeriesWithValueLabelAllowlist(series, valueLabelsConfig?.seriesKeys)
const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefined
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 1a619325e9a6..f5c52e0be8a1 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -18,6 +18,11 @@ import {
type YAxisConfig,
} from '../../utils/use-axis-formatters'
import { LineChart } from '../LineChart'
+import {
+ resolveValueLabelsConfig,
+ useSeriesWithValueLabelAllowlist,
+ type ValueLabelsConfig,
+} from '../utils/use-value-labels'
import {
useDerivedSeries,
type ConfidenceIntervalConfig,
@@ -25,11 +30,6 @@ import {
type TrendLineConfig,
} from './utils/use-derived-series'
-export interface ValueLabelsConfig {
- seriesKeys?: string[]
- formatter?: (value: number) => string
-}
-
export type { ConfidenceIntervalConfig, MovingAverageConfig, TrendLineConfig }
export interface TimeSeriesLineChartConfig {
@@ -63,16 +63,6 @@ export interface TimeSeriesLineChartProps<Meta = unknown> {
onError?: (error: Error, info: React.ErrorInfo) => void
}
-function resolveValueLabelsConfig(valueLabels: TimeSeriesLineChartConfig['valueLabels']): ValueLabelsConfig | null {
- if (valueLabels === undefined || valueLabels === false) {
- return null
- }
- if (valueLabels === true) {
- return {}
- }
- return valueLabels
-}
-
export function TimeSeriesLineChart<Meta = unknown>({
series,
labels,
@@ -102,21 +92,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
const yTickFormatter = useYTickFormatter(yAxis)
const valueLabelsConfig = resolveValueLabelsConfig(valueLabels)
-
- // Stable primitive key so callers can pass `valueLabels: { seriesKeys: ['a'] }` inline
- // without re-running the transform on every render.
- const seriesKeysSignature = valueLabelsConfig?.seriesKeys?.join(' ')
- const seriesAfterValueLabels = useMemo(() => {
- const seriesKeys = valueLabelsConfig?.seriesKeys
- if (!seriesKeys) {
- return series
- }
- const allowed = new Set(seriesKeys)
- return series.map((s) =>
- allowed.has(s.key) ? s : { ...s, visibility: { ...s.visibility, valueLabel: false } }
- )
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [series, seriesKeysSignature])
+ const seriesAfterValueLabels = useSeriesWithValueLabelAllowlist(series, valueLabelsConfig?.seriesKeys)
const finalSeries = useDerivedSeries(seriesAfterValueLabels, {
confidenceIntervals,
diff --git a/frontend/src/lib/hog-charts/charts/utils/use-value-labels.ts b/frontend/src/lib/hog-charts/charts/utils/use-value-labels.ts
new file mode 100644
index 000000000000..a6f9c7b64051
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/utils/use-value-labels.ts
@@ -0,0 +1,39 @@
+import { useMemo } from 'react'
+
+import type { Series } from '../../core/types'
+
+export interface ValueLabelsConfig {
+ seriesKeys?: string[]
+ formatter?: (value: number) => string
+}
+
+export function resolveValueLabelsConfig(input: boolean | ValueLabelsConfig | undefined): ValueLabelsConfig | null {
+ if (input === undefined || input === false) {
+ return null
+ }
+ if (input === true) {
+ return {}
+ }
+ return input
+}
+
+export function useSeriesWithValueLabelAllowlist<Meta>(
+ series: Series<Meta>[],
+ seriesKeys: string[] | undefined
+): Series<Meta>[] {
+ // Stable primitive key so callers can pass `valueLabels: { seriesKeys: ['a'] }` inline
+ // without re-running the transform on every render. JSON.stringify (rather than
+ // `join(' ')`) so a key that contains a space doesn't collide with two keys split on
+ // it (`['a b']` vs `['a','b']`).
+ const seriesKeysSignature = JSON.stringify(seriesKeys ?? null)
+ return useMemo(() => {
+ if (!seriesKeys) {
+ return series
+ }
+ const allowed = new Set(seriesKeys)
+ return series.map((s) =>
+ allowed.has(s.key) ? s : { ...s, visibility: { ...s.visibility, valueLabel: false } }
+ )
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [series, seriesKeysSignature])
+}
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts
index 6b33d55fb5f8..03961dec2978 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts
@@ -3,7 +3,7 @@ import { renderHook } from '@testing-library/react'
import type { Series } from '../types'
import { DEFAULT_MARGINS, useChartMargins } from './useChartMargins'
-jest.mock('../../overlays/AxisLabels', () => ({
+jest.mock('../../utils/text-measure', () => ({
measureLabelWidth: (text: string) => text.length * 10,
}))
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
index bbae6655733d..13d421877c47 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
@@ -1,7 +1,7 @@
import * as d3 from 'd3'
import { useMemo } from 'react'
-import { measureLabelWidth } from '../../overlays/AxisLabels'
+import { measureLabelWidth } from '../../utils/text-measure'
import { autoFormatterFor, seriesValueRange } from '../scales'
import { DEFAULT_Y_AXIS_ID } from '../types'
import type { ChartMargins, Series } from '../types'
diff --git a/frontend/src/lib/hog-charts/core/scales.test.ts b/frontend/src/lib/hog-charts/core/scales.test.ts
index 4a3936033843..1db780b735fd 100644
--- a/frontend/src/lib/hog-charts/core/scales.test.ts
+++ b/frontend/src/lib/hog-charts/core/scales.test.ts
@@ -1,13 +1,16 @@
import { dimensions, makeSeries } from '../testing'
import {
autoFormatYTick,
+ buildStackedResolveValue,
computePercentStackData,
computeStackData,
createScales,
createXScale,
createYScale,
+ niceLogDomain,
yTickCountForHeight,
} from './scales'
+import type { StackedBand } from './scales'
import { DEFAULT_Y_AXIS_ID } from './types'
describe('hog-charts scales', () => {
@@ -493,4 +496,60 @@ describe('hog-charts scales', () => {
expect(autoFormatYTick(-5, 10)).toBe('-5')
})
})
+
+ describe('niceLogDomain', () => {
+ it.each([
+ { minPositive: 740, max: 4200, expected: [100, 5000] },
+ { minPositive: 1, max: 100, expected: [0.1, 100] },
+ { minPositive: 0.5, max: 9, expected: [0.1, 9] },
+ { minPositive: 25, max: 25, expected: [10, 30] },
+ { minPositive: 1000, max: 9999, expected: [100, 10000] },
+ ])('rounds [$minPositive, $max] to $expected', ({ minPositive, max, expected }) => {
+ const [niceMin, niceMax] = niceLogDomain(minPositive, max)
+ expect(niceMin).toBeCloseTo(expected[0], 5)
+ expect(niceMax).toBeCloseTo(expected[1], 5)
+ })
+
+ it('always rounds minPositive down past it (next decade lower)', () => {
+ const [niceMin] = niceLogDomain(50, 1000)
+ expect(niceMin).toBeLessThanOrEqual(50)
+ })
+ })
+
+ describe('buildStackedResolveValue', () => {
+ const series = makeSeries({ key: 'a', data: [10, 20, 30] })
+
+ it('returns undefined when stackedData is undefined', () => {
+ expect(buildStackedResolveValue(undefined)).toBeUndefined()
+ })
+
+ it('returns the stacked top when present and finite', () => {
+ const stacked = new Map<string, StackedBand>([['a', { top: [100, 200, 300], bottom: [0, 0, 0] }]])
+ const resolve = buildStackedResolveValue(stacked)!
+ expect(resolve(series, 0)).toBe(100)
+ expect(resolve(series, 2)).toBe(300)
+ })
+
+ it('falls back to the raw value when the series is not in the stack', () => {
+ const stacked = new Map<string, StackedBand>()
+ const resolve = buildStackedResolveValue(stacked)!
+ expect(resolve(series, 1)).toBe(20)
+ })
+
+ it('falls back to the raw value when the stacked top is non-finite', () => {
+ const stacked = new Map<string, StackedBand>([['a', { top: [NaN, Infinity, 50], bottom: [0, 0, 0] }]])
+ const resolve = buildStackedResolveValue(stacked)!
+ expect(resolve(series, 0)).toBe(10)
+ expect(resolve(series, 1)).toBe(20)
+ expect(resolve(series, 2)).toBe(50)
+ })
+
+ it('returns 0 when both stacked top and raw value are non-finite', () => {
+ const nanSeries = makeSeries({ key: 'a', data: [NaN, Infinity, 0] })
+ const stacked = new Map<string, StackedBand>([['a', { top: [NaN, NaN, 0], bottom: [0, 0, 0] }]])
+ const resolve = buildStackedResolveValue(stacked)!
+ expect(resolve(nanSeries, 0)).toBe(0)
+ expect(resolve(nanSeries, 1)).toBe(0)
+ })
+ })
})
diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.ts
index 94f27f83a494..7d5c8689de08 100644
--- a/frontend/src/lib/hog-charts/core/scales.ts
+++ b/frontend/src/lib/hog-charts/core/scales.ts
@@ -1,6 +1,6 @@
import * as d3 from 'd3'
-import type { ChartDimensions, Series } from './types'
+import type { ChartDimensions, ChartScales, ResolveValueFn, Series } from './types'
import { DEFAULT_Y_AXIS_ID } from './types'
type D3YScale = d3.ScaleLinear<number, number> | d3.ScaleLogarithmic<number, number>
@@ -57,6 +57,15 @@ export function seriesValueRange(series: Series[]): SeriesValueRange {
return { min, max, minPositive, count }
}
+/** Round `minPositive` down to the previous decade, `max` up to the next round multiple
+ * of its top decade (e.g. 740 → 800, 4200 → 5000). */
+export function niceLogDomain(minPositive: number, max: number): [number, number] {
+ const niceMin = Math.pow(10, Math.ceil(Math.log10(minPositive)) - 1)
+ const maxDecade = Math.pow(10, Math.floor(Math.log10(max)))
+ const niceMax = Math.ceil(max / maxDecade) * maxDecade
+ return [niceMin, niceMax]
+}
+
export function createXScale(labels: string[], dimensions: ChartDimensions): d3.ScalePoint<string> {
return d3
.scalePoint<string>()
@@ -107,12 +116,9 @@ export function createYScale(
.nice(tickCount)
.range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
}
- const niceMin = Math.pow(10, Math.ceil(Math.log10(range.minPositive)) - 1)
- const maxDecade = Math.pow(10, Math.floor(Math.log10(max)))
- const niceMax = Math.ceil(max / maxDecade) * maxDecade
return d3
.scaleLog()
- .domain([niceMin, niceMax])
+ .domain(niceLogDomain(range.minPositive, max))
.range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
.clamp(true)
}
@@ -242,6 +248,25 @@ export function computePercentStackData(series: Series[], labels: string[]): Map
return buildStackData(series, labels, d3.stackOffsetExpand)
}
+/** Returns the stacked top of each series so the tooltip anchor lands at the visual
+ * top of each segment, not the raw series value. Falls back to the raw value when the
+ * series isn't part of the stack (e.g. trend-line overlays, CI bands). */
+export function buildStackedResolveValue(
+ stackedData: Map<string, StackedBand> | undefined
+): ResolveValueFn | undefined {
+ if (!stackedData) {
+ return undefined
+ }
+ return (s, dataIndex) => {
+ const stacked = stackedData.get(s.key)?.top[dataIndex]
+ if (stacked != null && Number.isFinite(stacked)) {
+ return stacked
+ }
+ const raw = s.data[dataIndex]
+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0
+ }
+}
+
export interface BarScaleSet {
band: d3.ScaleBand<string>
value: D3YScale
@@ -320,10 +345,7 @@ function buildBarValueScale(
const min = range.min > 0 ? 0 : range.min
const max = range.max < 0 ? 0 : range.max
if (scaleType === 'log' && isFinite(range.minPositive)) {
- const niceMin = Math.pow(10, Math.ceil(Math.log10(range.minPositive)) - 1)
- const maxDecade = Math.pow(10, Math.floor(Math.log10(max)))
- const niceMax = Math.ceil(max / maxDecade) * maxDecade
- return d3.scaleLog().domain([niceMin, niceMax]).range(valueRange).clamp(true)
+ return d3.scaleLog().domain(niceLogDomain(range.minPositive, max)).range(valueRange).clamp(true)
}
return d3.scaleLinear().domain([min, max]).nice(tickCount).range(valueRange)
}
@@ -342,3 +364,10 @@ export function autoFormatterFor(ticks: number[]): (value: number) => string {
const domainMax = ticks.length > 0 ? Math.max(...ticks.map((t) => Math.abs(t))) : 1
return (v) => autoFormatYTick(v, domainMax)
}
+
+export function resolveYScaleForSeries(
+ scales: Pick<ChartScales, 'y' | 'yAxes'>,
+ series: Pick<Series, 'yAxisId'>
+): (value: number) => number {
+ return scales.yAxes?.[series.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? scales.y
+}
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index 63f50ff53b07..6d8c69afdecc 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -10,8 +10,8 @@ export type {
TimeSeriesLineChartConfig,
TimeSeriesLineChartProps,
TrendLineConfig,
- ValueLabelsConfig,
} from './charts/TimeSeriesLineChart/TimeSeriesLineChart'
+export type { ValueLabelsConfig } from './charts/utils/use-value-labels'
export { TimeSeriesBarChart } from './charts/TimeSeriesBarChart/TimeSeriesBarChart'
export type { TimeSeriesBarChartConfig, TimeSeriesBarChartProps } from './charts/TimeSeriesBarChart/TimeSeriesBarChart'
diff --git a/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx b/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx
index 2cd4f160af99..2e5792f08a03 100644
--- a/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx
+++ b/frontend/src/lib/hog-charts/overlays/AxisLabels.tsx
@@ -1,6 +1,7 @@
import React, { useMemo } from 'react'
import { useChartLayout } from '../core/chart-context'
+import { AXIS_LABEL_FONT, getTextMeasureCtx } from '../utils/text-measure'
interface AxisLabelsProps {
xTickFormatter?: (value: string, index: number) => string | null
@@ -16,27 +17,8 @@ interface AxisLabelsProps {
labelToCoord?: (label: string) => number | undefined
}
-export const LABEL_FONT =
- '12px -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif'
const LABEL_PADDING = 20
-let measureCtx: CanvasRenderingContext2D | null = null
-function getMeasureCtx(): CanvasRenderingContext2D | null {
- if (!measureCtx) {
- measureCtx = document.createElement('canvas').getContext('2d')
- }
- return measureCtx
-}
-
-export function measureLabelWidth(text: string, font: string = LABEL_FONT): number {
- const ctx = getMeasureCtx()
- if (!ctx) {
- return text.length * 7
- }
- ctx.font = font
- return ctx.measureText(text).width
-}
-
export function computeVisibleXLabels(
labels: string[],
xScale: (label: string) => number | undefined,
@@ -59,11 +41,11 @@ export function computeVisibleXLabels(
return []
}
- const ctx = getMeasureCtx()
+ const ctx = getTextMeasureCtx()
if (!ctx) {
return candidates
}
- ctx.font = LABEL_FONT
+ ctx.font = AXIS_LABEL_FONT
const widths = candidates.map((c) => ctx.measureText(c.text).width)
@@ -90,6 +72,71 @@ const TICK_STYLE_BASE: React.CSSProperties = {
whiteSpace: 'nowrap',
}
+const TICK_GAP = 8
+
+interface ChartBox {
+ width: number
+ plotLeft: number
+ plotTop: number
+ plotWidth: number
+ plotHeight: number
+}
+
+function YTickLabel({
+ y,
+ side,
+ box,
+ text,
+ color,
+ dataAttr,
+}: {
+ y: number
+ side: 'left' | 'right'
+ box: ChartBox
+ text: string
+ color: string
+ dataAttr: 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 }}>
+ {text}
+ </div>
+ )
+}
+
+function XTickLabel({
+ x,
+ box,
+ text,
+ color,
+ dataAttr,
+}: {
+ x: number
+ box: ChartBox
+ text: string
+ color: string
+ dataAttr: string
+}): React.ReactElement {
+ return (
+ <div
+ data-attr={dataAttr}
+ style={{
+ ...TICK_STYLE_BASE,
+ left: x,
+ top: box.plotTop + box.plotHeight + TICK_GAP,
+ transform: 'translateX(-50%)',
+ color,
+ }}
+ >
+ {text}
+ </div>
+ )
+}
+
export function AxisLabels({
xTickFormatter,
yTickFormatter,
@@ -136,19 +183,15 @@ export function AxisLabels({
return null
}
return (
- <div
+ <YTickLabel
key={`y-cat-${i}`}
- data-attr="hog-chart-axis-tick-y"
- style={{
- ...TICK_STYLE_BASE,
- right: dimensions.width - dimensions.plotLeft + 8,
- top: y,
- transform: 'translateY(-50%)',
- color: axisColor,
- }}
- >
- {text}
- </div>
+ y={y}
+ side="left"
+ box={dimensions}
+ text={text}
+ color={axisColor}
+ dataAttr="hog-chart-axis-tick-y"
+ />
)
})}
{!hideXAxis &&
@@ -159,19 +202,14 @@ export function AxisLabels({
}
const label = yTickFormatter ? yTickFormatter(tick) : String(tick)
return (
- <div
+ <XTickLabel
key={`x-val-${tick}`}
- data-attr="hog-chart-axis-tick-x"
- style={{
- ...TICK_STYLE_BASE,
- left: x,
- top: dimensions.plotTop + dimensions.plotHeight + 8,
- transform: 'translateX(-50%)',
- color: axisColor,
- }}
- >
- {label}
- </div>
+ x={x}
+ box={dimensions}
+ text={label}
+ color={axisColor}
+ dataAttr="hog-chart-axis-tick-x"
+ />
)
})}
</>
@@ -188,19 +226,15 @@ export function AxisLabels({
}
const label = yTickFormatter ? yTickFormatter(tick) : String(tick)
return (
- <div
+ <YTickLabel
key={`y-${tick}`}
- data-attr="hog-chart-axis-tick-y"
- style={{
- ...TICK_STYLE_BASE,
- right: dimensions.width - dimensions.plotLeft + 8,
- top: y,
- transform: 'translateY(-50%)',
- color: axisColor,
- }}
- >
- {label}
- </div>
+ y={y}
+ side="left"
+ box={dimensions}
+ text={label}
+ color={axisColor}
+ dataAttr="hog-chart-axis-tick-y"
+ />
)
})}
@@ -213,36 +247,27 @@ export function AxisLabels({
}
const label = rightFormatter ? rightFormatter(tick) : String(tick)
return (
- <div
+ <YTickLabel
key={`yr-${tick}`}
- data-attr="hog-chart-axis-tick-yr"
- style={{
- ...TICK_STYLE_BASE,
- left: dimensions.plotLeft + dimensions.plotWidth + 8,
- top: y,
- transform: 'translateY(-50%)',
- color: axisColor,
- }}
- >
- {label}
- </div>
+ y={y}
+ side="right"
+ box={dimensions}
+ text={label}
+ color={axisColor}
+ dataAttr="hog-chart-axis-tick-yr"
+ />
)
})}
{visibleXLabels.map(({ index, text, x }) => (
- <div
+ <XTickLabel
key={`x-${index}`}
- data-attr="hog-chart-axis-tick-x"
- style={{
- ...TICK_STYLE_BASE,
- left: x,
- top: dimensions.plotTop + dimensions.plotHeight + 8,
- transform: 'translateX(-50%)',
- color: axisColor,
- }}
- >
- {text}
- </div>
+ x={x}
+ box={dimensions}
+ text={text}
+ color={axisColor}
+ dataAttr="hog-chart-axis-tick-x"
+ />
))}
</>
)
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
index c38fd0d4d5b3..24009d17f095 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
@@ -1,8 +1,9 @@
import React, { useMemo } from 'react'
import { useChartLayout } from '../core/chart-context'
-import { DEFAULT_Y_AXIS_ID } from '../core/types'
+import { resolveYScaleForSeries } from '../core/scales'
import type { ChartScales, ResolvedSeries, ResolveValueFn } from '../core/types'
+import { getTextMeasureCtx } from '../utils/text-measure'
export type ValueLabelsMode = 'per-segment' | 'stack-total'
@@ -22,14 +23,6 @@ const LABEL_BORDER = 2
const LABEL_HORIZONTAL_CHROME = (LABEL_PADDING_X + LABEL_BORDER) * 2
const STACK_TOTAL_KEY = '__stack_total__'
-let measureCtx: CanvasRenderingContext2D | null = null
-function getMeasureCtx(): CanvasRenderingContext2D | null {
- if (!measureCtx) {
- measureCtx = document.createElement('canvas').getContext('2d')
- }
- return measureCtx
-}
-
interface Candidate {
key: string
seriesIndex: number
@@ -41,11 +34,6 @@ interface Candidate {
above: boolean
}
-function resolveYScale(s: { yAxisId?: string }, scales: ChartScales): (value: number) => number {
- const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID
- return scales.yAxes?.[axisId]?.scale ?? scales.y
-}
-
function defaultLocaleFormatter(v: number): string {
return v.toLocaleString()
}
@@ -88,7 +76,7 @@ function pushCandidate(
}
function buildCandidates(args: BuildCandidatesArgs): Candidate[] {
- const ctx = getMeasureCtx()
+ const ctx = getTextMeasureCtx()
if (ctx) {
ctx.font = LABEL_FONT
}
@@ -129,7 +117,7 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
return out
}
const topSeries = visible[visible.length - 1]
- const yScale = resolveYScale(topSeries, scales)
+ const yScale = resolveYScaleForSeries(scales, topSeries)
const topColor = topSeries.color
for (let dIdx = 0; dIdx < labels.length; dIdx++) {
@@ -167,7 +155,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (s.visibility?.excluded || s.visibility?.valueLabel === false) {
continue
}
- const yScale = resolveYScale(s, scales)
+ const yScale = resolveYScaleForSeries(scales, s)
for (let dIdx = 0; dIdx < s.data.length && dIdx < labels.length; dIdx++) {
const rawValue = s.data[dIdx]
if (typeof rawValue !== 'number' || !isFinite(rawValue) || rawValue === 0) {
diff --git a/frontend/src/lib/hog-charts/utils/text-measure.ts b/frontend/src/lib/hog-charts/utils/text-measure.ts
new file mode 100644
index 000000000000..e59bbb358693
--- /dev/null
+++ b/frontend/src/lib/hog-charts/utils/text-measure.ts
@@ -0,0 +1,23 @@
+// Cached offscreen canvas — createElement+getContext is slow, measureText is fast.
+// Callers must set ctx.font themselves before measuring.
+
+export const AXIS_LABEL_FONT =
+ '12px -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif'
+
+let measureCtx: CanvasRenderingContext2D | null = null
+export function getTextMeasureCtx(): CanvasRenderingContext2D | null {
+ if (!measureCtx) {
+ measureCtx = document.createElement('canvas').getContext('2d')
+ }
+ return measureCtx
+}
+
+/** Falls back to length × 7 when the canvas context is unavailable (SSR). */
+export function measureLabelWidth(text: string, font: string = AXIS_LABEL_FONT): number {
+ const ctx = getTextMeasureCtx()
+ if (!ctx) {
+ return text.length * 7
+ }
+ ctx.font = font
+ return ctx.measureText(text).width
+}