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): share scale and y-axis helpers across BarChart/LineChart (#63984)

Sam Penningtond5de0f4925cb
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index 0eafb2341202..2329f3e427b5 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -10,8 +10,10 @@ import {
computeDivergingStackData,
computePercentStackData,
computeStackData,
+ computeTopStackedKeyByAxis,
createBarScales,
type StackedBand,
+ toYAxisScales,
yTickCountForHeight,
} from '../../core/scales'
import type {
@@ -26,9 +28,7 @@ import type {
ResolvedSeries,
Series,
TooltipContext,
- YAxisScale,
} from '../../core/types'
-import { DEFAULT_Y_AXIS_ID } from '../../core/types'
import { BarTooltip } from './BarTooltip'
import { computeWrapperMinHeight, HORIZONTAL_MIN_BAND_SIZE_DEFAULT } from './utils/bar-config'
import { groupedBandSlotAtCursor } from './utils/bars-under-cursor'
@@ -114,20 +114,10 @@ function BarChartInner<Meta = unknown>({
// Cap rounding is per-axis: buildStackData stacks each yAxisId independently, so each
// axis has its own topmost visible series. Iteration order matches d3.stack's key order,
// so the last write per axis is that axis's top layer.
- const topStackedKeyByAxis = useMemo<Map<string, string>>(() => {
- const m = new Map<string, string>()
- if (barLayout === 'grouped') {
- return m
- }
- for (const s of series) {
- if (s.visibility?.excluded) {
- continue
- }
- const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID
- m.set(axisId, s.key)
- }
- return m
- }, [barLayout, series])
+ const topStackedKeyByAxis = useMemo<Map<string, string>>(
+ () => (barLayout === 'grouped' ? new Map() : computeTopStackedKeyByAxis(series)),
+ [barLayout, series]
+ )
const chartConfig = useMemo<BarChartConfig>(() => {
const base = { ...config, isPercent: barLayout === 'percent' }
@@ -182,17 +172,7 @@ function BarChartInner<Meta = unknown>({
// Expose per-axis scales so AxisLabels renders the right-hand axis and the tooltip /
// value-label overlays resolve each series against its own axis.
- let yAxes: Record<string, YAxisScale> | undefined
- if (d3Scales.yAxes) {
- yAxes = {}
- for (const [axisId, { scale, position }] of Object.entries(d3Scales.yAxes)) {
- yAxes[axisId] = {
- scale: (value: number) => scale(value),
- ticks: () => scale.ticks?.(yTickCount) ?? [],
- position,
- }
- }
- }
+ const yAxes = d3Scales.yAxes ? toYAxisScales(d3Scales.yAxes, yTickCount) : undefined
// Stash the raw d3 scales in the private slot so drawStatic/drawHover/click routing
// can read them from the committed ChartScales — every render gets a self-contained
diff --git a/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts b/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts
index 8e12e562adc1..0605a4edc0b2 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts
+++ b/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts
@@ -2,6 +2,7 @@ import { color as d3Color } from 'd3-color'
import { bandCenter, type BarChartPrivate, computeBarTrackRect, computeSeriesBars } from '../../../core/bar-layout'
import {
+ BAR_HIGHLIGHT_DARKEN,
BAR_TRACK_HOVER_ALPHA,
type BarRect,
type BarShadow,
@@ -226,7 +227,7 @@ export function drawBarHoverItems(
)
} else {
const barColor = barColorAt(s, bar.dataIndex)
- const highlightColor = d3Color(barColor)?.darker(0.6).toString() ?? barColor
+ const highlightColor = d3Color(barColor)?.darker(BAR_HIGHLIGHT_DARKEN).toString() ?? barColor
drawBarHighlight(ctx, bar, highlightColor, highlightRadius)
}
}
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index 28bf15b76f32..cbf4070f7535 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -1,7 +1,8 @@
import React, { useCallback, useMemo } from 'react'
-import { drawArea, drawAxes, drawGrid, drawHighlightPoint, drawLine, drawPoints } from '../../core/canvas-renderer'
+import { drawArea, drawAxes, drawGrid, drawLine, drawLineHoverPoints, drawPoints } from '../../core/canvas-renderer'
import type { DrawContext } from '../../core/canvas-renderer'
+import { withVerticalClip } from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import {
@@ -11,6 +12,7 @@ import {
computeStackData,
createScales as createLineScales,
resolveYScaleForSeries,
+ toYAxisScales,
yTickCountForHeight,
} from '../../core/scales'
import type { ScaleSet, StackedBand } from '../../core/scales'
@@ -26,7 +28,6 @@ import type {
ResolvedSeries,
Series,
TooltipContext,
- YAxisScale,
} from '../../core/types'
// Brand for the private ChartScales._private slot used by LineChart. The base Chart
@@ -124,17 +125,7 @@ function LineChartInner<Meta = unknown>({
const yTickCount = yTickCountForHeight(dimensions.plotHeight)
- let yAxes: Record<string, YAxisScale> | undefined
- if (d3Scales.yAxes) {
- yAxes = {}
- for (const [axisId, { scale, position }] of Object.entries(d3Scales.yAxes)) {
- yAxes[axisId] = {
- scale: (value: number) => scale(value),
- ticks: () => scale.ticks?.(yTickCount) ?? [],
- position,
- }
- }
- }
+ const yAxes = d3Scales.yAxes ? toYAxisScales(d3Scales.yAxes, yTickCount) : undefined
// Stash raw d3 scales in the private slot so drawStatic can read them without
// a side-channel ref — every render gets a self-contained ChartScales object,
@@ -181,31 +172,25 @@ function LineChartInner<Meta = unknown>({
// Clip vertically only: keep out-of-domain values (e.g. a trendline below 0) out of the
// axis-label gutters, but span the full width so edge point markers/line caps render whole.
- const CLIP_PAD = 8
- ctx.save()
- ctx.beginPath()
- ctx.rect(0, dimensions.plotTop - CLIP_PAD, dimensions.width, dimensions.plotHeight + CLIP_PAD * 2)
- ctx.clip()
-
- for (const s of coloredSeries) {
- if (s.visibility?.excluded) {
- continue
- }
+ withVerticalClip(ctx, dimensions, () => {
+ for (const s of coloredSeries) {
+ if (s.visibility?.excluded) {
+ continue
+ }
- const drawCtx: DrawContext = { ...baseDrawCtx, yScale: resolveYScale(s) }
- const band = stackedData?.get(s.key)
- const yValues = band?.top
+ const drawCtx: DrawContext = { ...baseDrawCtx, yScale: resolveYScale(s) }
+ const band = stackedData?.get(s.key)
+ const yValues = band?.top
- if (s.fill) {
- drawArea(drawCtx, s, yValues, s.fill.lowerData ?? band?.bottom)
- }
- if (!s.fill?.lowerData) {
- drawLine(drawCtx, s, yValues)
- drawPoints(drawCtx, s, yValues)
+ if (s.fill) {
+ drawArea(drawCtx, s, yValues, s.fill.lowerData ?? band?.bottom)
+ }
+ if (!s.fill?.lowerData) {
+ drawLine(drawCtx, s, yValues)
+ drawPoints(drawCtx, s, yValues)
+ }
}
- }
-
- ctx.restore()
+ })
},
[showGrid, showAxisLines, stackedData]
)
@@ -215,26 +200,17 @@ function LineChartInner<Meta = unknown>({
if (hoverIndex < 0) {
return false
}
- let drewAny = false
- for (const s of coloredSeries) {
- if (s.visibility?.excluded || s.fill?.lowerData) {
- continue
- }
- // Auxiliary overlays (moving averages, trend lines) opt out of stacking.
- // In percent-stack mode the y-scale domain is [0, 1], so mapping their raw
- // values produces a highlight ring far outside the plot — skip them entirely.
- if (s.overlay) {
- continue
- }
+ // Overlays (moving averages, trend lines) and fill-between lower bounds opt out — in
+ // percent-stack mode the y-domain is [0, 1], so their raw values would ring far off-plot.
+ // `drawLineHoverPoints` handles those skips; we supply the stacked-top y per series.
+ return drawLineHoverPoints(ctx, coloredSeries, theme.backgroundColor ?? '#ffffff', (s) => {
const data = stackedData?.get(s.key)?.top ?? s.data
const x = scales.x(drawLabels[hoverIndex])
- const y = resolveYScaleForSeries(scales, s)(data[hoverIndex])
- if (x != null && isFinite(y)) {
- drawHighlightPoint(ctx, x, y, s.color, theme.backgroundColor ?? '#ffffff')
- drewAny = true
+ if (x == null) {
+ return null
}
- }
- return drewAny
+ return { x, y: resolveYScaleForSeries(scales, s)(data[hoverIndex]) }
+ })
},
[stackedData]
)
diff --git a/packages/quill/packages/charts/src/core/bar-layout.ts b/packages/quill/packages/charts/src/core/bar-layout.ts
index f01ff757bcac..f5941cc2db87 100644
--- a/packages/quill/packages/charts/src/core/bar-layout.ts
+++ b/packages/quill/packages/charts/src/core/bar-layout.ts
@@ -182,8 +182,11 @@ export function computeBarAtIndex({
return makeBarRect(isHorizontal, slot.x, slot.width, baseline, valuePixel, corners, dataIndex)
}
- const topPixel = scales.value(stackedBand!.top[dataIndex])
- const bottomPixel = scales.value(stackedBand!.bottom[dataIndex])
+ // Resolve against the series' own axis (mirrors the grouped branch above), so a stacked bar on
+ // a non-default `yAxisId` — only ComboChart combines stacking with per-series axes — is hit-tested
+ // and drawn against the same scale. For single-axis charts `valueScale` is `scales.value`.
+ const topPixel = valueScale(stackedBand!.top[dataIndex])
+ const bottomPixel = valueScale(stackedBand!.bottom[dataIndex])
if (!isFinite(topPixel) || !isFinite(bottomPixel)) {
return null
}
@@ -196,7 +199,7 @@ export function computeBarAtIndex({
// The bottom-of-stack segment sits on the value-axis baseline, so it's left exact — extending it
// would only overpaint the axis. The cap (away-from-baseline) side is always exact so cap
// rounding and the stack's outer edge stay put.
- const sitsOnBaseline = Math.abs(bottomPixel - scales.value(0)) < 0.001
+ const sitsOnBaseline = Math.abs(bottomPixel - valueScale(0)) < 0.001
const overlappedBottom = sitsOnBaseline
? bottomPixel
: bottomPixel + STACK_SEGMENT_OVERLAP_PX * Math.sign(bottomPixel - topPixel)
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index 3f96d3eb0da8..2bfea4ed4c33 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -505,6 +505,56 @@ export interface BarRect {
export const DEFAULT_BAR_CORNER_RADIUS = 4
+/** d3 `.darker()` factor for a bar's hover highlight — shared by BarChart and ComboChart so the
+ * hovered-bar shade stays consistent. */
+export const BAR_HIGHLIGHT_DARKEN = 0.6
+
+/** Run `draw` with the canvas clipped to the plot area vertically (full width, padded `pad` px top
+ * and bottom). Keeps out-of-domain values (e.g. a trendline below 0) out of the axis gutters while
+ * leaving the left/right edges unclipped so line caps and edge point markers render whole. Shared
+ * by LineChart and ComboChart. `restore` always runs, even if `draw` throws. */
+export function withVerticalClip(
+ ctx: CanvasRenderingContext2D,
+ dimensions: ChartDimensions,
+ draw: () => void,
+ pad = 8
+): void {
+ ctx.save()
+ ctx.beginPath()
+ ctx.rect(0, dimensions.plotTop - pad, dimensions.width, dimensions.plotHeight + pad * 2)
+ ctx.clip()
+ try {
+ draw()
+ } finally {
+ ctx.restore()
+ }
+}
+
+/** Draw hover highlight rings for line/area series at the hovered index. Skips excluded,
+ * fill-between (`fill.lowerData`), and overlay series (trendlines/moving averages opt out of hover
+ * points). `pointFor` lets each chart supply its own anchor — LineChart resolves the point x and
+ * stacked-top y per series; ComboChart anchors at the band center with raw values. Returns whether
+ * any point was drawn. Shared by LineChart and ComboChart. */
+export function drawLineHoverPoints(
+ ctx: CanvasRenderingContext2D,
+ series: readonly ResolvedSeries[],
+ backgroundColor: string,
+ pointFor: (s: ResolvedSeries) => { x: number; y: number } | null
+): boolean {
+ let drew = false
+ for (const s of series) {
+ if (s.visibility?.excluded || s.fill?.lowerData || s.overlay) {
+ continue
+ }
+ const point = pointFor(s)
+ if (point && isFinite(point.x) && isFinite(point.y)) {
+ drawHighlightPoint(ctx, point.x, point.y, s.color, backgroundColor)
+ drew = true
+ }
+ }
+ return drew
+}
+
export interface BarShadow {
color: string
blur: number
diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.ts
index ce3027a1b7a0..5366f0c7e4d6 100644
--- a/packages/quill/packages/charts/src/core/scales.ts
+++ b/packages/quill/packages/charts/src/core/scales.ts
@@ -10,13 +10,13 @@ import {
} from 'd3-scale'
import { stack as stackGen, stackOffsetDiverging, stackOffsetExpand, stackOffsetNone } from 'd3-shape'
-import type { BandSlot, ChartDimensions, ChartScales, ResolveValueFn, Series, ValueDomain } from './types'
+import type { BandSlot, ChartDimensions, ResolveValueFn, Series, ValueDomain, YAxisScale } from './types'
import { DEFAULT_Y_AXIS_ID } from './types'
/** Inner padding fraction applied to the band scale when `BarChartConfig.bars.bandPadding` is unset. */
export const DEFAULT_BAND_PADDING = 0.2
-type D3YScale = ScaleLinear<number, number> | ScaleLogarithmic<number, number>
+export type D3YScale = ScaleLinear<number, number> | ScaleLogarithmic<number, number>
export interface ScaleSet {
x: ScalePoint<string>
@@ -159,10 +159,49 @@ export function createYScale(
const dataRange = seriesValueRange(series)
const range = include?.length ? extendValueRange(dataRange, include) : dataRange
+ // A negative `include` value (a goal line below 0) is explicit, so it must not be clamped away.
+ const hasExplicitNegativeGoal = include?.some((v) => v != null && isFinite(v) && v < 0) ?? false
+ const primaryRange = series.some((s) => s.overlay) ? seriesValueRange(series.filter((s) => !s.overlay)) : dataRange
+
+ return buildValueScale({
+ range,
+ primaryRange,
+ valueRange: [dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop],
+ tickCount,
+ scaleType,
+ allowNegativeBaseline: hasExplicitNegativeGoal,
+ })
+}
+
+/** Build a value (y, or x for horizontal) scale from a precomputed {@link SeriesValueRange}, applying
+ * the overlay-aware zero-baseline clamp, the degenerate `min === max` guard, and the log/no-positive
+ * fallback. Single source of truth shared by `createYScale` and the combo chart's per-axis scales so
+ * the baseline logic can't drift between them. */
+export function buildValueScale(options: {
+ range: SeriesValueRange
+ /** Pixel range `[lowEdge, highEdge]` — for a vertical y-scale this is `[bottom, top]`. */
+ valueRange: [number, number]
+ tickCount: number
+ scaleType?: 'linear' | 'log'
+ /** Range used for the overlay-aware zero-baseline clamp; defaults to `range`. Overlays
+ * (trendlines, moving averages) may dip below 0 when the underlying data doesn't — they
+ * shouldn't drag the baseline negative, since `d3.nice()` on a slightly-negative min yields a
+ * disproportionately large negative tick (e.g. [-1, 14500] → [-2000, 16000]). */
+ primaryRange?: SeriesValueRange
+ /** Keep a negative min even when the primary data is non-negative (an explicit negative goal). */
+ allowNegativeBaseline?: boolean
+}): D3YScale {
+ const {
+ range,
+ valueRange,
+ tickCount,
+ scaleType = 'linear',
+ primaryRange = range,
+ allowNegativeBaseline = false,
+ } = options
+
if (range.count === 0) {
- return scaleLinear()
- .domain([0, 1])
- .range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
+ return scaleLinear().domain([0, 1]).range(valueRange)
}
let { min, max } = range
@@ -177,42 +216,60 @@ export function createYScale(
logMin = Math.min(0, logMin)
logMax = Math.max(0, logMax, logMin + 1)
}
- return scaleLinear()
- .domain([logMin, logMax])
- .nice(tickCount)
- .range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
+ return scaleLinear().domain([logMin, logMax]).nice(tickCount).range(valueRange)
}
- return scaleLog()
- .domain(niceLogDomain(range.minPositive, max))
- .range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
- .clamp(true)
+ return scaleLog().domain(niceLogDomain(range.minPositive, max)).range(valueRange).clamp(true)
}
- // Auxiliary overlays (trendline projections, moving averages) may dip below 0
- // when the underlying data does not. They shouldn't drag the axis baseline below
- // 0 — d3.nice() applied to a slightly-negative min produces a disproportionately
- // large negative tick (e.g. [-1, 14500] → [-2000, 16000]). A negative `include`
- // value (a goal line below 0) is explicit, though, so it must not be clamped away.
- const hasExplicitNegativeGoal = include?.some((v) => v != null && isFinite(v) && v < 0) ?? false
- const primaryRange = series.some((s) => s.overlay) ? seriesValueRange(series.filter((s) => !s.overlay)) : dataRange
- if (primaryRange.count > 0 && primaryRange.min >= 0 && !hasExplicitNegativeGoal) {
+ if (primaryRange.count > 0 && primaryRange.min >= 0 && !allowNegativeBaseline) {
min = 0
} else if (max < 0) {
max = 0
}
- // With no real data, `include` (goal) values are the only contributors, so the range can
- // collapse to a single point (e.g. `[100, 100]`) — a degenerate domain that maps everything to
- // NaN. Bracket zero, then guarantee a unit span, so the axis stays well-formed.
+ // The range can collapse to a single point (e.g. all-equal data, or `include`-only goal values
+ // like `[100, 100]`) — a degenerate domain that maps everything to NaN. Bracket zero, then
+ // guarantee a unit span, so the axis stays well-formed.
if (min === max) {
min = Math.min(0, min)
max = Math.max(0, max, min + 1)
}
- return scaleLinear()
- .domain([min, max])
- .nice(tickCount)
- .range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
+ return scaleLinear().domain([min, max]).nice(tickCount).range(valueRange)
+}
+
+/** Map raw d3 per-axis scales into the public {@link YAxisScale} shape (value→pixel fn + tick
+ * accessor + side). Shared by every multi-axis chart's `createScales` so the wrapping is uniform. */
+export function toYAxisScales(
+ d3Axes: Record<string, { scale: D3YScale; position: 'left' | 'right' }>,
+ tickCount: number
+): Record<string, YAxisScale> {
+ const yAxes: Record<string, YAxisScale> = {}
+ for (const [axisId, { scale, position }] of Object.entries(d3Axes)) {
+ yAxes[axisId] = {
+ scale: (value: number) => scale(value),
+ ticks: () => scale.ticks?.(tickCount) ?? [],
+ position,
+ }
+ }
+ return yAxes
+}
+
+/** Topmost visible series key per axis id — the cap-rounded layer of each stack. Iteration order
+ * matches d3.stack's key order, so the last write per axis is that axis's top layer. `skip` lets a
+ * mixed-type chart exclude non-bar series so only bars determine the cap. */
+export function computeTopStackedKeyByAxis<S extends Pick<Series, 'key' | 'visibility' | 'yAxisId'>>(
+ series: readonly S[],
+ options: { skip?: (s: S) => boolean } = {}
+): Map<string, string> {
+ const m = new Map<string, string>()
+ for (const s of series) {
+ if (s.visibility?.excluded || options.skip?.(s)) {
+ continue
+ }
+ m.set(s.yAxisId ?? DEFAULT_Y_AXIS_ID, s.key)
+ }
+ return m
}
/** Order the visible series' axis ids — DEFAULT_Y_AXIS_ID first (when present), then the
@@ -621,9 +678,9 @@ export function autoFormatterFor(ticks: number[]): (value: number) => string {
return (v) => autoFormatYTick(v, domainMax)
}
-export function resolveYScaleForSeries(
- scales: Pick<ChartScales, 'y' | 'yAxes'>,
+export function resolveYScaleForSeries<S extends (value: number) => number>(
+ scales: { y: S; yAxes?: Record<string, { scale: S }> },
series: Pick<Series, 'yAxisId'>
-): (value: number) => number {
+): S {
return scales.yAxes?.[series.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? scales.y
}