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(quill-charts): reduce margins to primitives so inline config is safe (#125454)

Sam Pennington204fb9c2afc5
diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx
index 3e83e9dc71af..94e1842ccefb 100644
--- a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.test.tsx
@@ -4,7 +4,7 @@ import type { ChartTheme, Series } from '../../core/types'
import { createDefaultTooltipAccessor, renderChart } from '../../testing'
import { dimensions } from '../../testing/jsdom'
import { funnelFromCounts } from './funnel-data'
-import { FunnelChart, type FunnelStepClickData } from './FunnelChart'
+import { FunnelChart, type FunnelChartConfig, type FunnelStepClickData } from './FunnelChart'
const THEME: ChartTheme = {
colors: ['#1f77b4', '#ff7f0e'],
@@ -126,6 +126,21 @@ describe('FunnelChart', () => {
expect(chart.xTicks()).toHaveLength(0)
})
+ it.each([
+ { name: 'margins', config: (): FunnelChartConfig => ({ margins: { top: 4 } }) },
+ { name: 'tooltip', config: (): FunnelChartConfig => ({ tooltip: { pinnable: true } }) },
+ ])('does not repaint the static canvas when a re-render passes an equal inline $name', ({ config }) => {
+ const { chart, rerender } = renderChart(
+ <FunnelChart steps={STEPS} series={SERIES} theme={THEME} config={config()} />
+ )
+ let paints = 0
+ const observer = new MutationObserver((records) => (paints += records.length))
+ observer.observe(chart.canvas, { attributeFilter: ['data-hog-charts-paint'] })
+ rerender(<FunnelChart steps={STEPS} series={SERIES} theme={THEME} config={config()} />)
+ expect(paints + observer.takeRecords().length).toBe(0)
+ observer.disconnect()
+ })
+
it('never asks for a step footer past the current step count when a shorter funnel replaces a longer one', async () => {
const THREE_STEPS = ['Exposure', 'Add to cart', 'Purchase']
const requested: number[] = []
diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx
index ec49118fd19f..4da4b6e1630f 100644
--- a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx
+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx
@@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useChartLayout } from '../../core/chart-context'
+import { useStableMargins } from '../../core/hooks/useChartMargins'
import { useResolvedChartTheme } from '../../core/theme'
import type {
BarChartConfig,
@@ -97,6 +98,10 @@ export interface FunnelChartProps<Meta = unknown> {
onError?: (error: Error, info: React.ErrorInfo) => void
}
+function formatPercentTick(value: number): string {
+ return `${Math.round(value)}%`
+}
+
function formatPercent(value: number): string {
return `${parseFloat(value.toFixed(2))}%`
}
@@ -210,7 +215,7 @@ export function FunnelChart<Meta = unknown>({
tooltip: tooltipConfig,
legend,
animateHover,
- margins,
+ margins: marginsOverride,
showGrid = true,
barCornerRadius = DEFAULT_CORNER_RADIUS,
hideStepLabels,
@@ -222,6 +227,7 @@ export function FunnelChart<Meta = unknown>({
chartMinHeight,
stepFooterAlign = 'start',
} = config ?? {}
+ const margins = useStableMargins(marginsOverride)
const hasStepFooter = stepFooter != null
// Band labels are 1-based step indices so steps sharing a name don't collapse onto one
@@ -239,7 +245,7 @@ export function FunnelChart<Meta = unknown>({
hideYAxis: hideValueAxis,
maxCategoryLabelWidth,
xTickFormatter: stepLabelFromBand,
- yTickFormatter: (value) => `${Math.round(value)}%`,
+ yTickFormatter: formatPercentTick,
barCornerRadius,
legend,
tooltip: {
@@ -270,6 +276,7 @@ export function FunnelChart<Meta = unknown>({
tooltipConfig,
barCornerRadius,
bandPadding,
+ minBarSize,
maxBandRange,
]
)
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
index eb0fc6916078..bcc9167ee134 100644
--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
@@ -105,7 +105,7 @@ export interface HeatmapConfig {
/** Column indices drawn with a band behind their cells, for a column the consumer selected
* or is hovering. */
highlightedColumns?: number[]
- /** Per-side margin overrides. Should be referentially stable. */
+ /** Per-side margin overrides. */
margins?: Partial<ChartMargins>
tooltip?: {
/** Show the single-cell tooltip on hover. Defaults to true. */
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
index 245ee7019988..4f41c3d0ea3b 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
@@ -7,7 +7,7 @@ import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import { resolveCssColor } from '../../core/color-utils'
import { useChartCanvas } from '../../core/hooks/useChartCanvas'
import { useChartDraw } from '../../core/hooks/useChartDraw'
-import { applyMarginOverride } from '../../core/hooks/useChartMargins'
+import { applyMarginOverride, useStableMargins } from '../../core/hooks/useChartMargins'
import { useResolvedChartTheme } from '../../core/theme'
import type { ChartDrawArgs, ChartMargins, ChartScales } from '../../core/types'
import { defaultResolveValue } from '../../core/types'
@@ -110,11 +110,12 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
[showNodeLabels, lastColumnLabels, nodes, links, nodeAlign, showNodeValues, valueFormatter]
)
+ const stableMarginsOverride = useStableMargins(marginsOverride)
const margins = useMemo<ChartMargins>(() => {
- const applied = marginsOverride ? applyMarginOverride(BASE_MARGINS, marginsOverride) : BASE_MARGINS
+ const applied = applyMarginOverride(BASE_MARGINS, stableMarginsOverride)
// Column headers are sized for their room, so an override cannot take it away.
return { ...applied, top: applied.top + (hasColumnLabels ? COLUMN_LABEL_HEIGHT : 0) }
- }, [hasColumnLabels, marginsOverride])
+ }, [hasColumnLabels, stableMarginsOverride])
const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({ margins })
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
index 07bee8a14c7d..9d9c3e4bcba0 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/types.ts
@@ -54,7 +54,7 @@ export interface SankeyChartConfig {
* anchors it to the hovered node's right edge or the ribbon's midpoint. */
placement?: 'follow-data' | 'top' | 'cursor'
}
- /** Per-side margin overrides. Should be referentially stable. Column headers add their room to
+ /** Per-side margin overrides. Column headers add their room to
* the top margin, and `outside` labels to the right margin, on top of an override. */
margins?: Partial<ChartMargins>
}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
index 9dfa965ba416..b6f285067ff5 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
@@ -6,7 +6,7 @@ import { drawAxes, drawGrid, drawTickMarks, resolveAxisLineColor } from '../../c
import type { DrawContext } from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
-import { applyMarginOverride, DEFAULT_MARGINS } from '../../core/hooks/useChartMargins'
+import { applyMarginOverride, DEFAULT_MARGINS, useStableMargins } from '../../core/hooks/useChartMargins'
import { sanitizeFixedDomain } from '../../core/scales'
import { useResolvedChartTheme } from '../../core/theme'
import type {
@@ -98,8 +98,9 @@ function ScatterChartInner<Meta = unknown>({
showCrosshair = true,
showBestFit = false,
isPointHighlighted,
- margins,
+ margins: marginsOverride,
} = config ?? {}
+ const margins = useStableMargins(marginsOverride)
// Destructured to primitives, so an inline `config` literal can't re-run the scale build.
const { scaleType: xScaleType, domain: xDomain, startAtZero: xStartAtZero, tickFormatter: xTickFormatter } = xAxis
const { scaleType: yScaleType, domain: yDomain, startAtZero: yStartAtZero, tickFormatter: yTickFormatter } = yAxis
@@ -303,7 +304,7 @@ function ScatterChartInner<Meta = unknown>({
const computed: Partial<ChartMargins> = {
right: Math.max(DEFAULT_MARGINS.right, xLabelEdgeReserve(points, xDomain, xTickFormatter)),
}
- return margins ? applyMarginOverride(computed, margins) : computed
+ return applyMarginOverride(computed, margins)
}, [xAxis.hide, margins, points, xDomain, xTickFormatter])
const baseConfig = useMemo<ChartConfig>(
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
index a579fb2ecd46..bd37810deda3 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
@@ -73,7 +73,7 @@ export interface ScatterChartConfig<Meta = unknown> {
showBestFit?: boolean
legend?: ChartLegendConfig
tooltip?: ScatterTooltipConfig<Meta>
- /** Applied over the computed margins. Should be referentially stable (a module-level constant). */
+ /** Applied over the computed margins. */
margins?: Partial<ChartMargins>
}
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
index 939eb2901a1d..bc9960a0c071 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
@@ -3,7 +3,7 @@ import React, { useCallback, useMemo } from 'react'
import { ChartLegend } from '../../components/Legend/ChartLegend'
import { useChartLegend } from '../../components/Legend/useChartLegend'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
-import { applyMarginOverride } from '../../core/hooks/useChartMargins'
+import { applyMarginOverride, useStableMargins } from '../../core/hooks/useChartMargins'
import { useResolvedChartTheme } from '../../core/theme'
import type {
ChartConfig,
@@ -113,6 +113,7 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
pointRadius = DEFAULT_POINT_RADIUS,
valueDomain,
} = config ?? {}
+ const marginsOverride = useStableMargins(config?.margins)
const showsStart = useCallback(
(s: Series<Meta>): boolean => slopeLabelVisible(s, 'start', showStartLabels),
@@ -164,10 +165,10 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
const base: Partial<ChartMargins> = { left, right }
return {
- margins: applyMarginOverride(base, config?.margins ?? {}),
+ margins: applyMarginOverride(base, marginsOverride),
nameOffsetX: offset,
}
- }, [visibleSeries, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])
+ }, [visibleSeries, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, marginsOverride])
// When the last point is the current incomplete period, dash only the *second half* of the
// connector so it reads as "the end is provisional", not the whole comparison.
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
index 7c93f1e4749a..b035570ff763 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
@@ -86,6 +86,13 @@ export function applyMarginOverride(
return result
}
+/** Rebuilds a margin override from its four sides, so an inline `margins` object with the same values
+ * keeps one identity and does not re-run the memos that read it. */
+export function useStableMargins(margins: Partial<ChartMargins> | undefined): Partial<ChartMargins> {
+ const { top, right, bottom, left } = margins ?? {}
+ return useMemo(() => ({ top, right, bottom, left }), [top, right, bottom, left])
+}
+
interface CategoryLabelWidths {
first: number
last: number
@@ -151,7 +158,7 @@ export function useChartMargins({
yTickFormatter,
axisOrientation = 'vertical',
isPercent = false,
- override,
+ override: rawOverride,
valueRangeSeries,
maxCategoryLabelWidth = 0,
yAxisFormatters,
@@ -159,6 +166,7 @@ export function useChartMargins({
yAxisTitles,
yAxisHidden,
}: UseChartMarginsOptions): ChartMargins {
+ const override = useStableMargins(rawOverride)
const isHorizontal = axisOrientation === 'horizontal'
const valueSeries = useMemo(
() => (isPercent ? series.map((s) => ({ ...s, data: [0, 1] })) : (valueRangeSeries ?? series)),
@@ -322,12 +330,7 @@ export function useChartMargins({
const rightLabelReserve = (gutterReserves?.right ?? 0) + titleReserve.right
const right = Math.max(rightFloor, rightLabelReserve, xLabelEdgeReserves.right + X_LABEL_EDGE_PADDING)
const computed: ChartMargins = { top: DEFAULT_MARGINS.top, right, bottom, left }
- return override ? applyMarginOverride(computed, override) : computed
- // Depend on the individual sides, not `override` by identity — callers are expected to build
- // the override object inline and conditionally (`{ top: reserveOrUndefined }`), which is a
- // fresh identity every render, and keying off it here would reintroduce the referential churn
- // this hook's memoization is meant to contain.
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ return applyMarginOverride(computed, override)
}, [
hideXAxis,
hideYAxis,
@@ -338,9 +341,6 @@ export function useChartMargins({
xLabelExtraBottom,
normalizedXAxisLabel,
titleReserve,
- override?.top,
- override?.right,
- override?.bottom,
- override?.left,
+ override,
])
}
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index d86aa6facb11..9b48a52b77e8 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -292,8 +292,7 @@ export interface ChartConfig {
/** Fade-in the hover overlay when the hovered point changes. `true` = ~150ms. */
animateHover?: boolean | number
/** Per-side overrides applied on top of the computed chart margins. Useful for sparklines
- * 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. */
+ * that want the plot area flush with the canvas edges (e.g. `{ left: 0, right: 0, top: 0, bottom: 0 }`). */
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
diff --git a/packages/quill/packages/charts/src/docs/axes.md b/packages/quill/packages/charts/src/docs/axes.md
index a7656f4e389b..f881746449be 100644
--- a/packages/quill/packages/charts/src/docs/axes.md
+++ b/packages/quill/packages/charts/src/docs/axes.md
@@ -65,7 +65,7 @@ A single object stays single-axis.
- Charts fill their container and need a parent with real dimensions. A zero-height flex child renders nothing. Give the wrapper an explicit height (`h-64`, or `flex-1` in a sized column). `Sparkline` alone takes `height` and `width` props.
- A wrapper that measures under one pixel wide or high does not resize the chart. `useChartCanvas` keeps the last painted frame and waits for the next real size, so a chart whose container collapses for a moment (an ancestor set to `display: none`, Chromium capturing a screenshot taller than the viewport) does not go blank or lay out again.
-- `ChartConfig.margins` (also available on all `TimeSeries*` configs) overrides only the sides it sets. A side left `undefined` keeps the computed margin, so an object built conditionally (`{ top: reserveOrUndefined }`) is safe. `SlopeChart` merges consumer margins over its computed label gutters with the same rule (`applyMarginOverride`). Pass a module-level constant.
+- `ChartConfig.margins` (also available on all `TimeSeries*` configs) overrides only the sides it sets. A side left `undefined` keeps the computed margin, so an object built conditionally (`{ top: reserveOrUndefined }`) is safe. `SlopeChart` merges consumer margins over its computed label gutters with the same rule (`applyMarginOverride`). An inline object is fine: charts compare the four sides, not the object.
## When the plot is blank