: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
fix(charts): correct CI-band axis, resize flash, and gap handling (#63486)
Sam Pennington5a4eeef658f9
diff --git a/packages/quill/packages/charts/src/core/bar-layout.test.ts b/packages/quill/packages/charts/src/core/bar-layout.test.tsindex 46a98f524424..7d199eae3a38 100644--- a/packages/quill/packages/charts/src/core/bar-layout.test.ts+++ b/packages/quill/packages/charts/src/core/bar-layout.test.ts@@ -103,6 +103,20 @@ describe('hog-charts bar-layout', () => {const scales = createBarScales([visible, excluded], ['a'], dimensions, { barLayout: 'grouped' })expect(layoutOf({ series: excluded, scales })[0]).toBeNull()})++ it('clamps the bar baseline into the plot when a fixed valueDomain excludes 0', () => {+ // valueScale(0) extrapolates below the plot for domain [50, 100]; the baseline must be+ // clamped so the bar stops at the plot edge instead of bleeding through the bottom margin.+ const s = makeSeries({ key: 's', data: [75] })+ const scales = createBarScales([s], ['a'], dimensions, {+ barLayout: 'grouped',+ valueDomain: [50, 100],+ })+ const bar = layoutOf({ series: s, scales })[0]!+ const plotBottom = dimensions.plotTop + dimensions.plotHeight+ // bottom edge of a vertical bar is y + height; it must not exceed the plot bottom.+ expect(bar.y + bar.height).toBeLessThanOrEqual(plotBottom + 0.001)+ })})describe('computeSeriesBars — stacked', () => {@@ -206,8 +220,18 @@ describe('hog-charts bar-layout', () => {stackedSeries,})const opts = { labels, scales, layout: 'stacked' as const, isHorizontal: false }- const lower = computeSeriesBars({ ...opts, series: a, stackedBand: stacks.get('a'), isTopOfStack: false })[0]!- const upper = computeSeriesBars({ ...opts, series: b, stackedBand: stacks.get('b'), isTopOfStack: true })[0]!+ const lower = computeSeriesBars({+ ...opts,+ series: a,+ stackedBand: stacks.get('a'),+ isTopOfStack: false,+ })[0]!+ const upper = computeSeriesBars({+ ...opts,+ series: b,+ stackedBand: stacks.get('b'),+ isTopOfStack: true,+ })[0]!// Bottom segment sits exactly on the baseline — no 0.5px overpaint past the axis.expect(lower.y + lower.height).toBeCloseTo(PIXEL_TEST_DIMENSIONS.plotHeight, 5)// Interior (upper) segment extends its baseline edge 0.5px past the lower segment's top.@@ -503,7 +527,6 @@ describe('hog-charts bar-layout', () => {})})-describe('bandCenter', () => {it.each([{ label: 'a', expected: 50 },@@ -526,22 +549,24 @@ describe('hog-charts bar-layout', () => {})})-describe('groupedBarCenter', () => {it.each([{ seriesKey: 'a', expected: 25 },{ seriesKey: 'b', expected: 75 },- ])("returns the center $expected for series $seriesKey's sub-band in a grouped layout", ({ seriesKey, expected }) => {- const a = makeSeries({ key: 'a', data: [10, 20] })- const b = makeSeries({ key: 'b', data: [20, 10] })- const scales = createBarScales([a, b], ['L1', 'L2'], PIXEL_TEST_DIMENSIONS, {- barLayout: 'grouped',- bandPadding: 0,- groupPadding: 0,- })- // a@L1 slot x:0 w:50 → center 25; b@L1 slot x:50 w:50 → center 75 (see grouped pixel case).- expect(groupedBarCenter(scales, 'L1', seriesKey)).toBeCloseTo(expected, 5)- })+ ])(+ "returns the center $expected for series $seriesKey's sub-band in a grouped layout",+ ({ seriesKey, expected }) => {+ const a = makeSeries({ key: 'a', data: [10, 20] })+ const b = makeSeries({ key: 'b', data: [20, 10] })+ const scales = createBarScales([a, b], ['L1', 'L2'], PIXEL_TEST_DIMENSIONS, {+ barLayout: 'grouped',+ bandPadding: 0,+ groupPadding: 0,+ })+ // a@L1 slot x:0 w:50 → center 25; b@L1 slot x:50 w:50 → center 75 (see grouped pixel case).+ expect(groupedBarCenter(scales, 'L1', seriesKey)).toBeCloseTo(expected, 5)+ }+ )it('returns undefined when the series is not in the group scale', () => {const a = makeSeries({ key: 'a', data: [10] })diff --git a/packages/quill/packages/charts/src/core/bar-layout.ts b/packages/quill/packages/charts/src/core/bar-layout.tsindex 1ba072bc2285..f01ff757bcac 100644--- a/packages/quill/packages/charts/src/core/bar-layout.ts+++ b/packages/quill/packages/charts/src/core/bar-layout.ts@@ -175,7 +175,11 @@ export function computeBarAtIndex({return null}const corners = cornersFor(isHorizontal, raw >= 0, shouldRoundCap)- return makeBarRect(isHorizontal, slot.x, slot.width, valueScale(0), valuePixel, corners, dataIndex)+ // A fixed `valueDomain` (e.g. [50, 100]) makes `valueScale(0)` extrapolate outside the+ // plot, so the bar would bleed through the axis. Clamp the baseline to the scale's range.+ const [r0, r1] = valueScale.range()+ const baseline = Math.min(Math.max(valueScale(0), Math.min(r0, r1)), Math.max(r0, r1))+ return makeBarRect(isHorizontal, slot.x, slot.width, baseline, valuePixel, corners, dataIndex)}const topPixel = scales.value(stackedBand!.top[dataIndex])diff --git a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.tsindex d109b70a285d..36c54109567c 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartCanvas.ts@@ -98,7 +98,12 @@ export function useChartCanvas(options: UseChartCanvasOptions): UseChartCanvasRereturn () => {observer.disconnect()}- }, [marginsRef.current])+ // Bind the observer once. `marginsRef` is a ref so `updateSize` always reads the+ // latest margins; depending on `marginsRef.current` here would disconnect and re-run+ // `updateSize` on every margins change, synchronously clearing the canvas bitmap+ // (a visible blank flash). The effect below handles margins-only updates instead.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])// When margins change without a resize, recompute dimensions from the cached rect.useEffect(() => {diff --git a/packages/quill/packages/charts/src/core/interaction.test.ts b/packages/quill/packages/charts/src/core/interaction.test.tsindex 7ce28caa80b9..480e0846532d 100644--- a/packages/quill/packages/charts/src/core/interaction.test.ts+++ b/packages/quill/packages/charts/src/core/interaction.test.ts@@ -172,6 +172,22 @@ describe('hog-charts interaction', () => {expect(result?.position.y).toBe(5)})+ it('skips a series whose value at the hovered index is a gap (null/NaN) instead of showing 0', () => {+ // The renderer draws no point for a gap; the tooltip must not fabricate a `0` row.+ const present = makeSeries({ key: 'present', data: [10, 20] })+ const gapped = makeSeries({ key: 'gapped', data: [5, null as unknown as number] })+ const result = buildTooltipContext(+ 1,+ [present, gapped],+ ['a', 'b'],+ xConst,+ yConst,+ fakeCanvasBounds,+ defaultResolveValue+ )+ expect(result?.seriesData.map((d) => d.series.key)).toEqual(['present'])+ })+it('includes correct pixel position from xScale and minimum yScale output', () => {const s1 = makeSeries({ key: 's1', data: [10] })const s2 = makeSeries({ key: 's2', data: [50] })diff --git a/packages/quill/packages/charts/src/core/interaction.ts b/packages/quill/packages/charts/src/core/interaction.tsindex ec75e4486e08..abc4f9385488 100644--- a/packages/quill/packages/charts/src/core/interaction.ts+++ b/packages/quill/packages/charts/src/core/interaction.ts@@ -102,7 +102,10 @@ export function buildTooltipContext<Meta = unknown>(}// `resolveValue` is the value shown to the user (the segment); `resolvePositionValue`// is where to anchor (the stacked top). They diverge only for stacked charts.- if (s.visibility?.tooltip !== false) {+ // A gap (`data[i]` non-finite) draws no point/bar, so don't fabricate a `0` row for it —+ // skip it the same way the renderer does.+ const rawValue = s.data[dataIndex]+ if (s.visibility?.tooltip !== false && rawValue != null && isFinite(rawValue)) {// A per-bar series carries each bar's identity in `bars[i]` — surface it so the tooltip// reads the right color/meta/label rather than the shared series-level ones.const bar = s.bars?.[dataIndex]diff --git a/packages/quill/packages/charts/src/core/scales.test.ts b/packages/quill/packages/charts/src/core/scales.test.tsindex 913820184abb..0407b1a0f63c 100644--- a/packages/quill/packages/charts/src/core/scales.test.ts+++ b/packages/quill/packages/charts/src/core/scales.test.ts@@ -106,6 +106,21 @@ describe('hog-charts scales', () => {expect(domainMax).toBeLessThan(100)})+ it('widens the domain to cover a confidence ribbon lower bound below the data', () => {+ // The ribbon top is the series data; fill.lowerData is the bottom of the band and+ // must influence the axis, otherwise the band clips at the series line.+ const band = makeSeries({ key: 'ci', data: [50, 60, 70], fill: { lowerData: [-20, -10, 30] } })+ const [domainMin] = createYScale([band], dimensions).domain()+ expect(domainMin).toBeLessThanOrEqual(-20)+ })++ it('lets a ribbon lower bound below 0 suppress the positive-data zero baseline clamp', () => {+ // Without folding lowerData in, all `data` are positive so min would clamp to 0.+ const band = makeSeries({ key: 'ci', data: [10, 20, 30], fill: { lowerData: [-5, -15, 5] } })+ const [domainMin] = createYScale([band], dimensions).domain()+ expect(domainMin).toBeLessThan(0)+ })+it.each([{description: 'clips baseline to 0 when an overlay dips below 0 but primary data is non-negative',@@ -264,6 +279,16 @@ describe('hog-charts scales', () => {expect(domainMin).toBeLessThan(domainMax)expect(scale(-100)).not.toBeCloseTo(scale(-10), 0)})++ it('stays well-formed on all-zero data (degenerate linear fallback)', () => {+ // No positive values → linear fallback; min === max === 0 would collapse to a+ // [0, 0] domain mapping everything to NaN without the bracketing guard.+ const series = [makeSeries({ key: 's1', data: [0, 0, 0] })]+ const scale = createYScale(series, dimensions, { scaleType: 'log' })+ const [domainMin, domainMax] = scale.domain()+ expect(domainMin).toBeLessThan(domainMax)+ expect(isFinite(scale(0))).toBe(true)+ })})describe('createYScale — percent stack mode', () => {diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex b215b0afc493..ce3027a1b7a0 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -51,7 +51,9 @@ export function seriesValueRange(series: Series[]): SeriesValueRange {if (s.visibility?.excluded) {continue}- for (const v of s.data) {+ // A confidence ribbon's lower bound (`fill.lowerData`) is part of the data's visible+ // extent, so it must widen the axis too — otherwise the band clips at the top series.+ for (const v of s.fill?.lowerData ? [...s.data, ...s.fill.lowerData] : s.data) {if (v == null || !isFinite(v)) {continue}@@ -167,8 +169,16 @@ export function createYScale(if (scaleType === 'log') {if (!isFinite(range.minPositive)) {+ // No positive values for a log scale (e.g. all-zero data). Fall back to linear, and+ // bracket a degenerate `min === max` domain so it doesn't collapse to NaN.+ let logMin = min+ let logMax = max+ if (logMin === logMax) {+ logMin = Math.min(0, logMin)+ logMax = Math.max(0, logMax, logMin + 1)+ }return scaleLinear()- .domain([min, max])+ .domain([logMin, logMax]).nice(tickCount).range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])}diff --git a/packages/quill/packages/charts/src/utils/statistics.test.ts b/packages/quill/packages/charts/src/utils/statistics.test.tsindex 96ac30fe3b2a..c0be5ab02cd6 100644--- a/packages/quill/packages/charts/src/utils/statistics.test.ts+++ b/packages/quill/packages/charts/src/utils/statistics.test.ts@@ -43,6 +43,22 @@ describe('trendLine', () => {}})+ it('fits over finite points only, ignoring gaps (NaN)', () => {+ // The fit should follow y = x from the finite points; the gap must not poison it.+ const result = trendLine([0, 1, NaN, 3, 4])+ expect(result).toHaveLength(5)+ for (let i = 0; i < result.length; i++) {+ expect(result[i]).toBeCloseTo(i)+ }+ })++ it('returns a finite-length copy when fewer than 2 finite points', () => {+ const input = [NaN, 5]+ const result = trendLine(input)+ expect(result).toEqual(input)+ expect(result).not.toBe(input)+ })+describe('fitUpTo', () => {it('fits the regression to a prefix and extrapolates to the full length', () => {// First 3 points are y = x; tail is noisy. fitUpTo=3 → trend continues as y=x.@@ -95,6 +111,19 @@ describe('movingAverage', () => {const explicit = movingAverage([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7)expect(result).toEqual(explicit)})++ it('averages over finite values in the window, ignoring gaps (NaN)', () => {+ // A single NaN must not drag the whole window average to NaN.+ const result = movingAverage([5, 5, NaN, 5, 5, 5, 5, 5], 3)+ expect(result.every((v) => isFinite(v))).toBe(true)+ })++ it('returns a copy rather than the same array when below the window size', () => {+ const input = [1, 2, 3]+ const result = movingAverage(input, 7)+ expect(result).toEqual(input)+ expect(result).not.toBe(input)+ })})describe('ciRanges', () => {@@ -137,4 +166,24 @@ describe('ciRanges', () => {expect(wide[1][i] - wide[0][i]).toBeGreaterThan(narrow[1][i] - narrow[0][i])}})++ it('estimates spread from finite values only, leaving the gap in place', () => {+ const values = [10, 12, NaN, 14, 9, 11, 13]+ const [lower, upper] = ciRanges(values)+ expect(lower).toHaveLength(values.length)+ // The band half-width is derived from the finite sample, so finite points stay bounded.+ const halfBand = upper[0] - values[0]+ expect(isFinite(halfBand)).toBe(true)+ expect(halfBand).toBeGreaterThan(0)+ // The gap is preserved (not fabricated into a value).+ expect(isFinite(lower[2])).toBe(false)+ expect(isFinite(upper[2])).toBe(false)+ })++ it('returns distinct array copies (not aliased) for the sub-2 case', () => {+ const [lower, upper] = ciRanges([5])+ expect(lower).toEqual([5])+ expect(upper).toEqual([5])+ expect(lower).not.toBe(upper)+ })})diff --git a/packages/quill/packages/charts/src/utils/statistics.ts b/packages/quill/packages/charts/src/utils/statistics.tsindex f3d011649704..7b2e41c71fbe 100644--- a/packages/quill/packages/charts/src/utils/statistics.ts+++ b/packages/quill/packages/charts/src/utils/statistics.ts@@ -9,14 +9,15 @@ export function linearRegression(data: ReadonlyArray<readonly [number, number]>)/** Symmetric confidence interval bounds for a sample of values, using the normal* approximation (`±z·SE`). Returns `[lower, upper]` arrays, both the same length- * as the input. */+ * as the input. Non-finite values (gaps) are excluded from the spread estimate but+ * preserved in place in the output. */export function ciRanges(values: number[], ci: number = 0.95): [number[], number[]] {- const n = values.length- if (n < 2) {- return [values, values]+ const finite = values.filter((v) => isFinite(v))+ if (finite.length < 2) {+ return [values.slice(), values.slice()]}- const sd = standardDeviation(values)- const se = sd / Math.sqrt(n)+ const sd = standardDeviation(finite)+ const se = sd / Math.sqrt(finite.length)const z = probit((1 + ci) / 2)const h = z * seconst upper = values.map((v) => v + h)@@ -26,11 +27,15 @@ export function ciRanges(values: number[], ci: number = 0.95): [number[], numberexport function trendLine(values: number[], fitUpTo?: number): number[] {const n = values.length- if (n < 2) {- return values- }const fitEnd = fitUpTo != null ? Math.max(2, Math.min(fitUpTo, n)) : n- const coordinates: [number, number][] = values.slice(0, fitEnd).map((y, x) => [x, y])+ // Fit only over finite points so a single gap doesn't poison the regression.+ const coordinates: [number, number][] = values+ .slice(0, fitEnd)+ .map((y, x): [number, number] => [x, y])+ .filter(([, y]) => isFinite(y))+ if (coordinates.length < 2) {+ return values.slice()+ }const { m, b } = linearRegression(coordinates)return values.map((_, x) => m * x + b)}@@ -38,13 +43,14 @@ export function trendLine(values: number[], fitUpTo?: number): number[] {export function movingAverage(values: number[], intervals: number = 7): number[] {const n = values.lengthif (n < intervals) {- return values+ return values.slice()}- return values.map((_, index) => {+ return values.map((value, index) => {const start = Math.max(0, index - Math.floor(intervals / 2))const end = Math.min(n, start + intervals)const actualStart = Math.max(0, end - intervals)- const slice = values.slice(actualStart, end)- return slice.reduce((sum, val) => sum + val, 0) / slice.length+ // Average only finite values in the window; a gap shouldn't drag the mean to NaN.+ const slice = values.slice(actualStart, end).filter((v) => isFinite(v))+ return slice.length > 0 ? slice.reduce((sum, val) => sum + val, 0) / slice.length : value})}