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.

feat(quill-charts): floor bar size and expose bar layout config (#77641)

Sam Penningtonc836705d2460
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 62f8dc8391a9..c993acda9845 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -968,6 +968,10 @@ snapshots:
hash: v1.k794b7964.8a532c663ed9af5e8866bc9bbc9f93f6d37319988fc4ba8d18d3c7a50b6ffff1.XVu-dGfZAeBu1WZnAJ4H7wYPLqWq_o3XIyd229OJr5Q
components-hogcharts-timeseriesbarchart--grouped-multiple-y-axes--light:
hash: v1.k794b7964.f7743b72fdae4415ac4188d34efea5812da8f0e2e6a904c06962de424191430e.X2dh8u-yOJjWGWkmMxeJTcRGZHjs88svjLov6K5Q2Vg
+ components-hogcharts-timeseriesbarchart--min-bar-size--dark:
+ hash: v1.k794b7964.cbaa74d1ed9462784fbca2283d0cf7e83880d0f26b01ff6122cada17c7392f04.2atjki8iBMtLyVRWYtv9ykdia9HdWzxHI8HfOeiK44g
+ components-hogcharts-timeseriesbarchart--min-bar-size--light:
+ hash: v1.k794b7964.20625f592f09a686f6ab12271d88f5c2e8d43d765d1c599748a3bca19f0b39c3.lawk_0gdTKp6vqU-Xcoy23fQJ1mgGybq4b6k8bdNkHg
components-hogcharts-timeseriesbarchart--percent--dark:
hash: v1.k794b7964.3f142f3d58f1bbcab86f0e1acdd41786fb469fdfc199808ed1c39c3539c59b5d.IPQnKR7_vDrRDZ_MQTgUjHmkQHo5yHbAGC5RULADyjU
components-hogcharts-timeseriesbarchart--percent--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index aff848e45eca..6418cde97eb3 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -47,6 +47,8 @@ const series: Series[] = [
- `key` (React key + stacking identity), `label` (legend/tooltip), `data` are required.
- Line-only options: `points`, `stroke.pattern` (dashes/projections), `fill.opacity` / `fill.gradient` (area), `fill.lowerData` (ribbon).
- Bar-only options: `bars` (per-bar `color`/`label`/`meta` overrides, plus `hatch: true` to fill that bar with a diagonal-hatch pattern in its resolved color — flags individual not-final bars, e.g. buckets still being ingested, at arbitrary indices; for a contiguous trailing range `stroke.partial.fromIndex` does the same); `trackData` caps each bar's interactive extent at a per-bar ceiling in value units — the region beyond `trackData[i]` is a fully inert gap: no hover, tooltip, pointer cursor, highlight, or click (the chart vetoes the hover there via `resolveHoverIndex`). On grouped charts with `bars.track` the hatched "share of a whole" track also fills only to the ceiling; on stacked charts no track is drawn — the ceiling only bounds interactivity. Funnel compare uses it to draw a shorter period's volume gap as empty space rather than drop-off, in both its grouped (left-to-right) and stacked (top-to-bottom) charts.
+- `BarChartConfig.bars.minBarSize` (px) floors each non-zero bar's thickness along the value axis so a single-occurrence bucket stays visible beside a spike three orders of magnitude taller (the old chart.js `minBarLength`) — zero-valued bars are never floored, so empty buckets stay empty. On a stacked chart only the outermost segment is floored — flooring an interior one would oversize a rect the segment above overpaints while still capturing its hover and clicks — so a breakdown stack floors only its top segment, and the option is aimed at single-series volume charts and grouped bars; `Sparkline` doesn't expose the prop. `TimeSeriesBarChart` takes `minBarSize`, `bandPadding`, and `margins` as top-level config keys (alongside `barCornerRadius`/`fillStyle`) rather than under `bars`.
+- `ChartConfig.margins` overrides only the sides it sets — a side left `undefined` keeps the chart's 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`), so an `undefined` side keeps the gutter its value/name labels reserved.
- `yAxisId` scales a series against a second axis; `meta` carries arbitrary data into tooltips.
## Sizing
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index 4d29a22cdaf9..01e13657410c 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -97,6 +97,7 @@ function BarChartInner<Meta = unknown>({
maxBandRange,
bandPadding,
minBandSize,
+ minBarSize,
fitToHeight = false,
valueDomain,
valuePadding,
@@ -189,6 +190,7 @@ function BarChartInner<Meta = unknown>({
bandPadding,
fitToHeight,
minBandSize: resolvedMinBandSize,
+ minBarSize,
valueDomain,
valuePadding,
axes: configYAxes,
@@ -263,6 +265,7 @@ function BarChartInner<Meta = unknown>({
bandPadding,
fitToHeight,
resolvedMinBandSize,
+ minBarSize,
valueDomain,
valuePadding,
configYAxes,
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
index 2357b4fd4678..f3b35ce63a15 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -115,6 +115,21 @@ describe('SlopeChart', () => {
)
expect(chart.slopeValueLabels().every((l) => l.text.endsWith('%'))).toBe(true)
})
+
+ it('keeps the computed label gutter when a margins override side is undefined', () => {
+ // A conditionally built override (`{ top: reserveOrUndefined }`) must not wipe the
+ // start-label gutter SlopeChart computed — a plain spread would, clipping the labels.
+ const startLabelLeft = (config?: Parameters<typeof SlopeChart>[0]['config']): string => {
+ const { container } = renderHogChart(
+ <SlopeChart series={SERIES} labels={LABELS} config={config} theme={THEME} />
+ )
+ const label = container.querySelector<HTMLElement>(
+ '[data-attr="hog-chart-slope-value-label"][data-slope-side="start"]'
+ )
+ return label!.style.left
+ }
+ expect(startLabelLeft({ margins: { top: 20, left: undefined } })).toBe(startLabelLeft())
+ })
})
describe('series labels', () => {
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
index c067188fa54f..ec169ab2fb74 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
@@ -3,6 +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 type {
ChartConfig,
ChartLegendConfig,
@@ -159,7 +160,7 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
const base: Partial<ChartMargins> = { left, right }
return {
- margins: { ...base, ...config?.margins },
+ margins: applyMarginOverride(base, config?.margins ?? {}),
nameOffsetX: offset,
}
}, [visibleSeries, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx
index f246483578a0..bc69f9c17f9c 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx
@@ -180,6 +180,41 @@ export const YAxisFormats: Story = {
),
}
+// Single occurrences (1) alongside a spike three orders of magnitude taller (1400) — without
+// minBarSize the small bars collapse to a sub-pixel sliver next to the spike.
+const MIN_BAR_SIZE_SERIES: Series[] = [{ key: 'errors', label: 'Errors', data: [1, 0, 2, 1400, 3, 0, 1] }]
+
+interface MinBarSizeCellProps {
+ title: string
+ series: Series[]
+ minBarSize?: number
+}
+
+function MinBarSizeCell({ title, series, minBarSize }: MinBarSizeCellProps): JSX.Element {
+ const theme = useReactiveTheme()
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
+ <span className="text-xs text-muted-foreground">{title}</span>
+ <Stage>
+ <TimeSeriesBarChart series={series} labels={DAYS} theme={theme} config={{ minBarSize }} />
+ </Stage>
+ </div>
+ )
+}
+
+/** `minBarSize` floors each non-zero bar's thickness along the value axis, so single-occurrence
+ * buckets stay visible next to a spike three orders of magnitude taller. Empty buckets stay empty. */
+export const MinBarSize: Story = {
+ render: () => (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, auto)', gap: 24 }}>
+ <MinBarSizeCell title="default" series={MIN_BAR_SIZE_SERIES} />
+ <MinBarSizeCell title="minBarSize: 6" series={MIN_BAR_SIZE_SERIES} minBarSize={6} />
+ </div>
+ ),
+}
+
export const DateAxis: Story = {
render: () => {
const cells: { interval: TimeInterval; labels: string[]; series: Series[]; title: string }[] = [
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
index cffe7c751ea6..f2fc0922b213 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
@@ -324,6 +324,29 @@ describe('TimeSeriesBarChart', () => {
})
})
+ describe('config.margins', () => {
+ // Guards against `margins` being misplaced under `bars` instead of top-level, where `Chart`
+ // reads it as `marginsOverride` — a misplacement like that would silently no-op with a green
+ // suite otherwise, since nothing else here reaches `useChartMargins`' override path.
+ it('widens the left gutter and shifts the y-axis ticks over', () => {
+ const { chart: defaultChart } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} />
+ )
+ const defaultTick = defaultChart.element.querySelector<HTMLElement>('[data-attr="hog-chart-axis-tick-y"]')
+ const { chart: widenedChart } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} config={{ margins: { left: 200 } }} />
+ )
+ const widenedTick = widenedChart.element.querySelector<HTMLElement>(
+ '[data-attr="hog-chart-axis-tick-y"]'
+ )
+ expect(defaultTick).not.toBeNull()
+ expect(widenedTick).not.toBeNull()
+ // Left-side tick position is `right: box.width - box.plotLeft + gap` — widening the left
+ // margin increases `plotLeft`, which decreases this `right` offset.
+ expect(parseFloat(widenedTick!.style.right)).toBeLessThan(parseFloat(defaultTick!.style.right))
+ })
+ })
+
it('forwards children alongside built-in overlays', () => {
const { container } = renderHogChart(
<TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME}>
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index a63cd3dcbee5..f00478a29d70 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -6,6 +6,7 @@ import type {
BarChartConfig,
BarFillStyle,
ChartLegendConfig,
+ ChartMargins,
ChartTheme,
DateRangeZoomData,
PointClickData,
@@ -50,6 +51,13 @@ export interface TimeSeriesBarChartConfig {
divergingStack?: boolean
/** Bar fill treatment — `flat` (default), `gradient`, or `gloss`. */
fillStyle?: BarFillStyle
+ /** Inner gap between bars as a fraction of the band slot (0–1). See {@link BarsConfig.bandPadding}. */
+ bandPadding?: number
+ /** Px floor on a bar's thickness along the value axis, so a tiny non-zero value stays visible.
+ * See {@link BarsConfig.minBarSize}. */
+ minBarSize?: number
+ /** Per-side overrides on the computed chart margins — see {@link ChartConfig.margins}. */
+ margins?: Partial<ChartMargins>
/** Ease the hover highlight in over this many ms (`true` = default duration). Omit to snap. */
animateHover?: boolean | number
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
@@ -101,6 +109,9 @@ export function TimeSeriesBarChart<Meta = unknown>({
tooltip: tooltipConfig,
divergingStack,
fillStyle,
+ bandPadding,
+ minBarSize,
+ margins,
animateHover,
legend,
trendLines,
@@ -125,6 +136,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
const trendSeries = useTrendLineSeries(visibleSeries, trendLines)
const barChartConfig: BarChartConfig = {
+ margins,
yScaleType: primaryYAxis?.scale,
xTickFormatter,
yTickFormatter,
@@ -146,6 +158,8 @@ export function TimeSeriesBarChart<Meta = unknown>({
divergingStack,
valueDomain,
fillStyle,
+ bandPadding,
+ minBarSize,
},
}
diff --git a/packages/quill/packages/charts/src/core/bar-layout.test.ts b/packages/quill/packages/charts/src/core/bar-layout.test.ts
index 9e9c744c726e..15a45c913fd1 100644
--- a/packages/quill/packages/charts/src/core/bar-layout.test.ts
+++ b/packages/quill/packages/charts/src/core/bar-layout.test.ts
@@ -296,6 +296,141 @@ describe('hog-charts bar-layout', () => {
expect(bars[2]?.dataIndex).toBe(2)
})
+ describe('computeSeriesBars — minBarSize', () => {
+ // Volume sparklines floor tiny buckets so "one error happened here" stays visible next to a
+ // spike. Guards the ways that goes wrong: flooring empty buckets into phantom bars, flooring
+ // a bar that is already tall enough, and — since `height` is `Math.abs`, blind to direction —
+ // flooring toward the wrong edge (a bar that hangs off the plot instead of growing from its
+ // baseline). Covers both `grouped` and `stacked` call sites, and both value signs.
+ // `edge` picks which computed pixel to compare against `expected`: the bar's top (`y`),
+ // bottom (`y + height`), right (`x + width`), or its `height` alone.
+ const IS_HORIZONTAL = { vertical: false, horizontal: true } as const
+ it.each([
+ {
+ name: 'stacked vertical positive: tiny value floors up from the baseline',
+ layout: 'stacked' as const,
+ axisOrientation: 'vertical' as const,
+ value: 1,
+ valueDomain: [0, 1000] as [number, number],
+ // baseline (value 0) sits at plotHeight (100); floored cap grows 6px above it — the
+ // bar's top edge (smaller y) is the cap here.
+ edge: 'top' as const,
+ expected: 94,
+ },
+ {
+ name: 'stacked vertical: zero value stays empty (not floored)',
+ layout: 'stacked' as const,
+ axisOrientation: 'vertical' as const,
+ value: 0,
+ valueDomain: [0, 1000] as [number, number],
+ edge: 'height' as const,
+ expected: 0,
+ },
+ {
+ name: 'stacked vertical: value above the floor is left exact',
+ layout: 'stacked' as const,
+ axisOrientation: 'vertical' as const,
+ value: 1000,
+ valueDomain: [0, 1000] as [number, number],
+ edge: 'top' as const,
+ expected: 0,
+ },
+ {
+ name: 'grouped vertical positive: tiny value floors up from the baseline',
+ layout: 'grouped' as const,
+ axisOrientation: 'vertical' as const,
+ value: 1,
+ valueDomain: [0, 1000] as [number, number],
+ edge: 'top' as const,
+ expected: 94,
+ },
+ {
+ name: 'grouped vertical negative: tiny value floors down from the baseline (symmetric domain)',
+ layout: 'grouped' as const,
+ axisOrientation: 'vertical' as const,
+ value: -1,
+ valueDomain: [-1000, 1000] as [number, number],
+ // baseline (value 0) sits at plotHeight / 2 (50) on a symmetric domain; the floored cap
+ // grows 6px below it — the bar's *bottom* edge (larger y) is the cap here, so asserting
+ // the top alone (which stays pinned to the baseline) would pass even if it floored upward.
+ edge: 'bottom' as const,
+ expected: 56,
+ },
+ {
+ name: 'grouped horizontal positive: tiny value floors right from the baseline',
+ layout: 'grouped' as const,
+ axisOrientation: 'horizontal' as const,
+ value: 1,
+ valueDomain: [0, 1000] as [number, number],
+ // baseline (value 0) sits at x=0; floored cap grows 6px right of it.
+ edge: 'right' as const,
+ expected: 6,
+ },
+ ])('$name', ({ layout, axisOrientation, value, valueDomain, edge, expected }) => {
+ const labels = ['a']
+ const s = makeSeries({ key: 's', data: [value] })
+ const scales = createBarScales([s], labels, PIXEL_TEST_DIMENSIONS, {
+ barLayout: layout,
+ axisOrientation,
+ minBarSize: 6,
+ // Pin the domain so the floor, not the auto-scaled axis, is what the assertion reads.
+ valueDomain,
+ })
+ // `stackedBand` must be omitted for `grouped` and supplied for `stacked`; a lookup keyed
+ // by layout keeps that out of the test body as data rather than control flow.
+ const stackedBandForLayout = {
+ stacked: () => computeStackData([s], labels).get('s'),
+ grouped: () => undefined,
+ }
+ const bars = computeSeriesBars({
+ series: s,
+ labels,
+ scales,
+ layout,
+ isHorizontal: IS_HORIZONTAL[axisOrientation],
+ stackedBand: stackedBandForLayout[layout](),
+ isTopOfStack: true,
+ })
+ const bar = bars[0]!
+ const actual = { top: bar.y, bottom: bar.y + bar.height, right: bar.x + bar.width, height: bar.height }[
+ edge
+ ]
+ expect(actual).toBeCloseTo(expected, 5)
+ })
+
+ // An interior segment's floored rect is invisible — the segment above starts where the
+ // unfloored stack ends and paints over it — but would still win `resolveBarsAtCursor`'s
+ // first-rect-wins hit test, so a hover or click in the overlap reported the wrong series.
+ it('floors only the outermost segment of a multi-series stack', () => {
+ const labels = ['a']
+ const lower = makeSeries({ key: 'lower', data: [1] })
+ const upper = makeSeries({ key: 'upper', data: [1] })
+ const scales = createBarScales([lower, upper], labels, PIXEL_TEST_DIMENSIONS, {
+ barLayout: 'stacked',
+ minBarSize: 10,
+ valueDomain: [0, 1000],
+ })
+ const stacks = computeStackData([lower, upper], labels)
+ const shared = { labels, scales, layout: 'stacked' as const, isHorizontal: false }
+ const lowerBars = computeSeriesBars({
+ ...shared,
+ series: lower,
+ stackedBand: stacks.get('lower'),
+ isTopOfStack: false,
+ })
+ const upperBars = computeSeriesBars({
+ ...shared,
+ series: upper,
+ stackedBand: stacks.get('upper'),
+ isTopOfStack: true,
+ })
+ // 1 unit is 0.1px on this domain, so both segments start far under the 10px floor.
+ expect(lowerBars[0]?.height).toBeCloseTo(0.1, 5)
+ // The top segment still floors: its bottom sits at 99.9, so its cap lands 10px above.
+ expect(upperBars[0]?.y).toBeCloseTo(89.9, 5)
+ })
+ })
+
describe('computeSeriesBars — exact pixel positions', () => {
interface PixelCase {
name: string
diff --git a/packages/quill/packages/charts/src/core/bar-layout.ts b/packages/quill/packages/charts/src/core/bar-layout.ts
index 6069c719a3f3..4f9b72bdc4cd 100644
--- a/packages/quill/packages/charts/src/core/bar-layout.ts
+++ b/packages/quill/packages/charts/src/core/bar-layout.ts
@@ -278,6 +278,26 @@ export function buildBarLayers({
return layers
}
+/** Push a bar's value-axis edge out to `minBarSize` px from its baseline-side edge when the bar
+ * would otherwise be thinner, so a tiny non-zero value still reads as a bar. Zero-valued bars keep
+ * their exact (empty) extent. The direction to grow is taken from the segment's own geometry
+ * (`valuePixel` vs `basePixel`), not from `raw`'s sign — a stacked/percent layout clamps negative
+ * data to a zero-extent segment (`raw !== 0` but `valuePixel === basePixel`), and a diverging
+ * stack's negative segment has `valuePixel > basePixel`, both of which disagree with `raw`'s sign.
+ * The `raw === 0` guard still keys off the value, not the geometry: on the grouped path a clamped
+ * baseline (e.g. a fixed `valueDomain` excluding 0) can make a zero-valued bar geometrically
+ * non-empty, and that must stay unfloored. */
+function floorValuePixel(valuePixel: number, basePixel: number, raw: number, minBarSize: number | undefined): number {
+ const direction = Math.sign(valuePixel - basePixel)
+ if (!minBarSize || minBarSize <= 0 || raw === 0 || direction === 0) {
+ return valuePixel
+ }
+ if (Math.abs(valuePixel - basePixel) >= minBarSize) {
+ return valuePixel
+ }
+ return basePixel + direction * minBarSize
+}
+
export interface ComputeBarAtIndexOptions {
series: Series
label: string
@@ -341,17 +361,37 @@ export function computeBarAtIndex({
// 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 cap = floorValuePixel(valuePixel, baseline, raw, scales.minBarSize)
+ return makeBarRect(isHorizontal, slot.x, slot.width, baseline, cap, corners, 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 rawTopPixel = valueScale(stackedBand!.top[dataIndex])
const bottomPixel = valueScale(stackedBand!.bottom[dataIndex])
- if (!isFinite(topPixel) || !isFinite(bottomPixel)) {
+ if (!isFinite(rawTopPixel) || !isFinite(bottomPixel)) {
return null
}
+ // Only the outermost segment is floored. Flooring an interior one oversizes its rect without
+ // moving the segment above it, so the extension is invisible — immediately overpainted — yet
+ // still wins hit-testing, since `resolveBarsAtCursor` takes the first rect containing the cursor:
+ // the tooltip and click would resolve to a series that isn't drawn there.
+ //
+ // Floored against this segment's own bottom, not the axis baseline, so a floored segment grows
+ // out of where it actually starts in the stack. Only a pixel the floor itself pushed out is
+ // clamped back into the value scale's range (mirrors the grouped branch's baseline clamp above)
+ // — an unfloored `rawTopPixel` outside the range is legitimate (e.g. a `valueDomain` narrower
+ // than the stack total) and hit-testing above the plot still needs to resolve to it, so clamping
+ // unconditionally would break that.
+ const flooredTopPixel = floorValuePixel(rawTopPixel, bottomPixel, raw, isTopOfStack ? scales.minBarSize : undefined)
+ let topPixel = flooredTopPixel
+ if (flooredTopPixel !== rawTopPixel) {
+ const [valueRangeA, valueRangeB] = valueScale.range()
+ const valueRangeMin = Math.min(valueRangeA, valueRangeB)
+ const valueRangeMax = Math.max(valueRangeA, valueRangeB)
+ topPixel = Math.min(Math.max(flooredTopPixel, valueRangeMin), valueRangeMax)
+ }
// For stacked/percent the bar's "positive direction" depends on which pixel is further from baseline,
// which differs by orientation: horizontal = larger x-pixel, vertical = smaller y-pixel (axis is inverted).
const isPositive = isHorizontal ? topPixel >= bottomPixel : topPixel <= bottomPixel
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts
index 3a253113edff..8736e2f8372d 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts
@@ -26,6 +26,22 @@ describe('useChartMargins', () => {
expect(render({ hideXAxis: true }).bottom).toBe(8)
})
+ describe('override', () => {
+ it('applies the sides it sets', () => {
+ expect(render({ override: { top: 30, left: 24 } })).toMatchObject({ top: 30, left: 24 })
+ })
+
+ it('leaves a side alone when its override is undefined', () => {
+ const withUndefined = render({ override: { top: undefined, left: 24 } })
+ expect(withUndefined.top).toBe(DEFAULT_MARGINS.top)
+ expect(withUndefined.left).toBe(24)
+ })
+
+ it('honors an explicit zero rather than treating it as unset', () => {
+ expect(render({ override: { top: 0, left: 0 } })).toMatchObject({ top: 0, left: 0 })
+ })
+ })
+
it('keeps default bottom margin otherwise', () => {
expect(render().bottom).toBe(DEFAULT_MARGINS.bottom)
})
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
index fdfc24fa6ab9..7a8148160377 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
@@ -53,6 +53,29 @@ interface UseChartMarginsOptions {
yAxisHidden?: Record<string, boolean>
}
+/** Apply per-side overrides, skipping sides left `undefined`. A plain spread would write the
+ * `undefined` through and clobber the computed margin, which turns the whole plot geometry into
+ * `NaN` and renders a blank chart — so a caller building an override object conditionally
+ * (`{ top: reserveOrUndefined }`) gets "leave this side alone" rather than a silent wipeout. */
+export function applyMarginOverride(computed: ChartMargins, override: Partial<ChartMargins>): ChartMargins
+export function applyMarginOverride(
+ computed: Partial<ChartMargins>,
+ override: Partial<ChartMargins>
+): Partial<ChartMargins>
+export function applyMarginOverride(
+ computed: Partial<ChartMargins>,
+ override: Partial<ChartMargins>
+): Partial<ChartMargins> {
+ const result = { ...computed }
+ for (const side of ['top', 'right', 'bottom', 'left'] as const) {
+ const value = override[side]
+ if (value !== undefined) {
+ result[side] = value
+ }
+ }
+ return result
+}
+
function widestCategoryLabelWidth(
labels: string[],
xTickFormatter: ((value: string, index: number) => string | null) | undefined,
@@ -232,7 +255,12 @@ export function useChartMargins({
const rightLabelReserve = (gutterReserves?.right ?? 0) + titleReserve.right
const right = Math.max(rightFloor, rightLabelReserve, xLabelHalfWidth + X_LABEL_EDGE_PADDING)
const computed: ChartMargins = { top: DEFAULT_MARGINS.top, right, bottom, left }
- return override ? { ...computed, ...override } : computed
+ 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
}, [
hideXAxis,
hideYAxis,
@@ -242,6 +270,9 @@ export function useChartMargins({
xLabelHalfWidth,
normalizedXAxisLabel,
titleReserve,
- override,
+ override?.top,
+ override?.right,
+ override?.bottom,
+ override?.left,
])
}
diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.ts
index 64a7707a794d..e80e9e173308 100644
--- a/packages/quill/packages/charts/src/core/scales.ts
+++ b/packages/quill/packages/charts/src/core/scales.ts
@@ -563,6 +563,13 @@ export interface BarScaleSet {
* more than one axis id across the visible series (`showMultipleYAxes`). `value` is
* the primary (left) axis scale. */
yAxes?: Record<string, { scale: D3YScale; position: 'left' | 'right' }>
+ /** Px floor on bar thickness along the value axis — see {@link BarsConfig.minBarSize}. A layout
+ * parameter rather than a scale, but carried here because every path that resolves a bar *rect*
+ * (static draw, hover overlay, click routing) already reads the committed scale set, so the
+ * floor can't drift between them. Tooltip/value-label anchoring (`buildTooltipContext`) is a
+ * separate path that positions off the unfloored value, not the drawn rect — a floored bucket's
+ * anchor can land inside the bar it labels. */
+ minBarSize?: number
}
/** Band-axis slot of one series's bar within a grouped band: `{ x, width }` along the band axis.
@@ -596,6 +603,8 @@ export function createBarScales(
fitToHeight?: boolean
/** Minimum px per row — only consulted to compute the `fitToHeight` row cap. */
minBandSize?: number
+ /** Px floor on bar thickness along the value axis — see {@link BarsConfig.minBarSize}. */
+ minBarSize?: number
/** Fixed `[min, max]` or `{ include }` extra values the value axis must cover. */
valueDomain?: ValueDomain
/** Px reserved past the bars at the value-axis data end(s) — see {@link BarsConfig.valuePadding}. */
@@ -614,6 +623,7 @@ export function createBarScales(
maxBandRange,
fitToHeight,
minBandSize,
+ minBarSize,
valueDomain,
valuePadding = 0,
axes,
@@ -691,7 +701,7 @@ export function createBarScales(
yAxes[axisId] = { scale, position }
})
const primary = yAxes[DEFAULT_Y_AXIS_ID] ?? yAxes[positions[0].axisId]
- return { band, value: primary.scale, group, yAxes }
+ return { band, value: primary.scale, group, yAxes, minBarSize }
}
return {
@@ -707,6 +717,7 @@ export function createBarScales(
valuePadding
),
group,
+ minBarSize,
}
}
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 13cd992ca673..44dc3b9c7fc5 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -412,6 +412,15 @@ export interface BarsConfig {
/** Inner gap between bars as a fraction of the band slot (0–1). Outer padding is half this
* value, so `step = range / N`. Defaults to `DEFAULT_BAND_PADDING` in `scales.ts`. */
bandPadding?: number
+ /** Floor (px) on a bar's thickness along the value axis, so a present-but-tiny value stays
+ * visible instead of collapsing to a sub-pixel sliver — e.g. a single error in a volume bucket
+ * whose neighbours are in the thousands. Zero-valued bars are never floored: the point is to
+ * keep small data readable, not to draw a bar where there is no data. On a stacked chart only
+ * the outermost segment is floored: flooring an interior one would oversize a rect that the
+ * segment above immediately overpaints, while still capturing the hover and clicks meant for
+ * that segment. So a multi-series (breakdown) stack floors only its top segment — this is aimed
+ * at single-series volume charts and grouped bars. Defaults to 0 (exact heights). */
+ minBarSize?: number
/** Horizontal bar charts only — minimum px per row. When many rows would otherwise crush into
* an unreadable strip, the chart expands its container height so each row has at least this
* much vertical space (label height + breathing room). Defaults to `24`. Pass `0` to opt out. */