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): axis baselines, bar track hover control, label offset (#62148)

Sam Pennington75a9d4c6ccd5
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index 062250f5a980..e24761dfad44 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -71,13 +71,14 @@ function BarChartInner<Meta = unknown>({
const {
yScaleType = 'linear',
showGrid = false,
+ showAxisLines = false,
barLayout = 'stacked',
axisOrientation = 'vertical',
xTickFormatter,
} = config ?? {}
const {
cornerRadius: barCornerRadius = 0,
- track: barTrack = false,
+ track: trackConfig = false,
shadow: barShadow,
divergingStack = false,
maxBandRange,
@@ -89,6 +90,8 @@ function BarChartInner<Meta = unknown>({
fillStyle: barFillStyle = 'flat',
} = config?.bars ?? {}
const isHorizontal = axisOrientation === 'horizontal'
+ const barTrack = trackConfig !== false
+ const barTrackHover = trackConfig === true || (typeof trackConfig === 'object' && trackConfig.hover !== false)
const resolvedMinBandSize = minBandSize ?? (isHorizontal ? HORIZONTAL_MIN_BAND_SIZE_DEFAULT : 0)
const wrapperMinHeight = useMemo(
@@ -245,6 +248,7 @@ function BarChartInner<Meta = unknown>({
barLayout,
isHorizontal,
showGrid,
+ showAxisLines,
xTickFormatter,
stackedData,
topStackedKeyByAxis,
@@ -256,6 +260,7 @@ function BarChartInner<Meta = unknown>({
}),
[
showGrid,
+ showAxisLines,
stackedData,
barLayout,
isHorizontal,
@@ -286,7 +291,7 @@ function BarChartInner<Meta = unknown>({
stackedData,
topStackedKeyByAxis,
roundStackEnds,
- barTrack,
+ barTrackHover,
})
if (!resolved) {
lastHoverKeyRef.current = null
@@ -303,7 +308,16 @@ function BarChartInner<Meta = unknown>({
drawBarHoverItems(ctx, d3Scales, resolved, { alpha, barCornerRadius, barTrack, isHorizontal })
return true
},
- [stackedData, barLayout, isHorizontal, topStackedKeyByAxis, roundStackEnds, barCornerRadius, barTrack]
+ [
+ stackedData,
+ barLayout,
+ isHorizontal,
+ topStackedKeyByAxis,
+ roundStackEnds,
+ barCornerRadius,
+ barTrack,
+ barTrackHover,
+ ]
)
// Show each series's own segment value (resolveValue) but anchor the tooltip/value labels
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 9be55ffab819..8e12e562adc1 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
@@ -6,6 +6,7 @@ import {
type BarRect,
type BarShadow,
clipToRoundedRects,
+ drawAxes,
drawBarHighlight,
drawBars,
drawBarTracks,
@@ -74,6 +75,7 @@ export interface DrawBarChartStaticArgs {
barLayout: BarLayout
isHorizontal: boolean
showGrid: boolean
+ showAxisLines: boolean
xTickFormatter: BarChartConfig['xTickFormatter']
stackedData: Map<string, StackedBand> | undefined
topStackedKeyByAxis: Map<string, string>
@@ -93,6 +95,7 @@ export function drawBarChartStatic(
barLayout,
isHorizontal,
showGrid,
+ showAxisLines,
xTickFormatter,
stackedData,
topStackedKeyByAxis,
@@ -122,6 +125,8 @@ export function drawBarChartStatic(
orientation: isHorizontal ? 'horizontal' : 'vertical',
categoryTicks: computeGridTicks(d3Scales, drawLabels, isHorizontal, xTickFormatter),
})
+ } else if (showAxisLines) {
+ drawAxes(baseDrawCtx, { axisColor: theme.gridColor })
}
const seriesBars = coloredSeries
diff --git a/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-bar-hover.ts b/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-bar-hover.ts
index f998dea27876..fc7e1f022fb3 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-bar-hover.ts
+++ b/packages/quill/packages/charts/src/charts/BarChart/utils/resolve-bar-hover.ts
@@ -33,7 +33,7 @@ export interface ResolveBarHoverArgs {
stackedData: Map<string, StackedBand> | undefined
topStackedKeyByAxis: Map<string, string>
roundStackEnds: boolean
- barTrack: boolean
+ barTrackHover: boolean
}
/** Resolve which bars (or tracks) the hovered band should highlight, plus the pill clip and a
@@ -43,7 +43,14 @@ export interface ResolveBarHoverArgs {
export function resolveBarHoverItems(
{ series: coloredSeries, labels: drawLabels, hoverIndex, hoverPosition }: ChartDrawArgs,
d3Scales: BarScaleSet,
- { barLayout, isHorizontal, stackedData, topStackedKeyByAxis, roundStackEnds, barTrack }: ResolveBarHoverArgs
+ {
+ barLayout,
+ isHorizontal,
+ stackedData,
+ topStackedKeyByAxis,
+ roundStackEnds,
+ barTrackHover,
+ }: ResolveBarHoverArgs
): ResolvedBarHover | null {
const hoveredLabel = drawLabels[hoverIndex]
const items: BarHoverItem[] = []
@@ -89,7 +96,7 @@ export function resolveBarHoverItems(
continue
}
const isTrackHighlight =
- barTrack === true &&
+ barTrackHover &&
barLayout === 'grouped' &&
hoverPosition != null &&
cursorOutsideBarFillExtent(bar, hoverPosition, isHorizontal)
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index d57d978d1038..1f3531c8d3d0 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -1,6 +1,6 @@
import React, { useCallback, useMemo } from 'react'
-import { drawArea, drawGrid, drawHighlightPoint, drawLine, drawPoints } from '../../core/canvas-renderer'
+import { drawArea, drawAxes, drawGrid, drawHighlightPoint, drawLine, drawPoints } from '../../core/canvas-renderer'
import type { DrawContext } from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
@@ -68,7 +68,13 @@ function LineChartInner<Meta = unknown>({
dataAttr,
children,
}: LineChartProps<Meta>): React.ReactElement {
- const { yScaleType = 'linear', percentStackView = false, showGrid = false, valueDomain } = config ?? {}
+ const {
+ yScaleType = 'linear',
+ percentStackView = false,
+ showGrid = false,
+ showAxisLines = false,
+ valueDomain,
+ } = config ?? {}
const hasMultipleFilledSeries = useMemo(() => {
const filledSeries = series.filter((s) => s.fill && !s.fill.lowerData)
@@ -169,6 +175,8 @@ function LineChartInner<Meta = unknown>({
if (showGrid) {
drawGrid(baseDrawCtx, { gridColor: theme.gridColor })
+ } else if (showAxisLines) {
+ drawAxes(baseDrawCtx, { axisColor: theme.gridColor })
}
// Clip data drawing to the plot area so an overlay series with values outside
@@ -207,7 +215,7 @@ function LineChartInner<Meta = unknown>({
ctx.restore()
},
- [showGrid, stackedData]
+ [showGrid, showAxisLines, stackedData]
)
const drawHover = useCallback(
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index 1140042de850..d74cb1749e35 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -38,6 +38,8 @@ export interface TimeSeriesBarChartConfig {
barCornerRadius?: number
/** Show a vertical crosshair line that follows the cursor. */
showCrosshair?: boolean
+ /** Draw L-shaped axis baselines without grid lines (ignored when `yAxis.showGrid` is true). */
+ showAxisLines?: boolean
/** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
tooltip?: TooltipConfig
/** Stacked layout only — stack negatives below the zero baseline (d3.stackOffsetDiverging). */
@@ -82,6 +84,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
axisOrientation,
barCornerRadius,
showCrosshair,
+ showAxisLines,
tooltip: tooltipConfig,
divergingStack,
fillStyle,
@@ -122,6 +125,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
xAxisLabel: xAxis?.label,
yAxisLabel: yAxis?.label,
showGrid: yAxis?.showGrid,
+ showAxisLines,
barLayout,
axisOrientation,
showCrosshair,
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 76320ea9c869..913e9f80d9e1 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -46,6 +46,8 @@ export interface TimeSeriesLineChartConfig {
percentStackView?: boolean
/** Show a vertical crosshair line that follows the cursor. */
showCrosshair?: boolean
+ /** Draw L-shaped axis baselines without grid lines (ignored when `yAxis.showGrid` is true). */
+ showAxisLines?: boolean
/** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
tooltip?: TooltipConfig
}
@@ -86,6 +88,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
comparisonOf,
percentStackView,
showCrosshair,
+ showAxisLines,
tooltip: tooltipConfig,
} = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
@@ -119,6 +122,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
xAxisLabel: xAxis?.label,
yAxisLabel: yAxis?.label,
showGrid: yAxis?.showGrid,
+ showAxisLines,
percentStackView,
showCrosshair,
tooltip: tooltipConfig,
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 e342bb9b5ecd..46a98f524424 100644
--- a/packages/quill/packages/charts/src/core/bar-layout.test.ts
+++ b/packages/quill/packages/charts/src/core/bar-layout.test.ts
@@ -107,21 +107,22 @@ describe('hog-charts bar-layout', () => {
describe('computeSeriesBars — stacked', () => {
it('uses the band top/bottom values for stack height', () => {
+ // Asserts on the bottom-of-stack segment, whose baseline edge is exact (no seam overlap).
const labels = ['a', 'b']
const a = makeSeries({ key: 'a', data: [10, 20] })
const b = makeSeries({ key: 'b', data: [5, 15] })
const scales = createBarScales([a, b], labels, dimensions, { barLayout: 'stacked' })
- const stackB = computeStackData([a, b], labels).get('b')!
+ const stackA = computeStackData([a, b], labels).get('a')!
const bars = layoutOf({
- series: b,
+ series: a,
labels,
scales,
layout: 'stacked',
- stackedBand: stackB,
- isTopOfStack: true,
+ stackedBand: stackA,
+ isTopOfStack: false,
})
expect(bars).toHaveLength(2)
- const expectedHeight = Math.abs(scales.value(stackB.top[0]) - scales.value(stackB.bottom[0]))
+ const expectedHeight = Math.abs(scales.value(stackA.top[0]) - scales.value(stackA.bottom[0]))
expect(bars[0]!.height).toBeCloseTo(expectedHeight, 5)
})
@@ -192,6 +193,29 @@ describe('hog-charts bar-layout', () => {
expect(fillerBars[1]?.corners).toEqual({ topRight: true, bottomRight: true })
})
+ it('overlaps an interior segment 0.5px into its lower neighbour, keeping baseline and cap exact', () => {
+ const labels = ['L1']
+ const a = makeSeries({ key: 'a', data: [50] })
+ const b = makeSeries({ key: 'b', data: [50] })
+ const stacks = computeStackData([a, b], labels)
+ const stackedSeries = [a, b].map((s) => ({ ...s, data: stacks.get(s.key)!.top }))
+ const scales = createBarScales([a, b], labels, PIXEL_TEST_DIMENSIONS, {
+ barLayout: 'stacked',
+ bandPadding: 0,
+ groupPadding: 0,
+ 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]!
+ // 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.
+ expect(upper.y + upper.height).toBeCloseTo(lower.y + 0.5, 5)
+ // Cap (away-from-baseline) edge stays exact.
+ expect(upper.y).toBeCloseTo(0, 5)
+ })
+
it('returns nulls when stackedBand is omitted for non-grouped layouts', () => {
const s = makeSeries({ key: 's', data: [10] })
const scales = createBarScales([s], ['a'], dimensions, { barLayout: 'stacked' })
@@ -276,12 +300,13 @@ describe('hog-charts bar-layout', () => {
{
key: 'b',
isTopOfStack: true,
+ // Interior segment: baseline edge extended 0.5px into the lower neighbour.
bars: [
{
x: 0,
y: 50,
width: 100,
- height: 25,
+ height: 25.5,
corners: { topLeft: true, topRight: true },
dataIndex: 0,
},
@@ -289,7 +314,7 @@ describe('hog-charts bar-layout', () => {
x: 100,
y: 0,
width: 100,
- height: 50,
+ height: 50.5,
corners: { topLeft: true, topRight: true },
dataIndex: 1,
},
@@ -371,11 +396,12 @@ describe('hog-charts bar-layout', () => {
{
key: 'b',
isTopOfStack: true,
+ // Interior segment: baseline edge extended 0.5px into the lower neighbour.
bars: [
{
- x: 100,
+ x: 99.5,
y: 0,
- width: 100,
+ width: 100.5,
height: 100,
corners: { topRight: true, bottomRight: true },
dataIndex: 0,
diff --git a/packages/quill/packages/charts/src/core/bar-layout.ts b/packages/quill/packages/charts/src/core/bar-layout.ts
index 0490fad37843..722806ff703a 100644
--- a/packages/quill/packages/charts/src/core/bar-layout.ts
+++ b/packages/quill/packages/charts/src/core/bar-layout.ts
@@ -10,6 +10,9 @@ export interface BarChartPrivate {
export type SeriesBarLayout = (BarRect | null)[]
+// Sub-pixel overlap between adjacent stacked segments, to hide anti-aliased seams at shared edges.
+const STACK_SEGMENT_OVERLAP_PX = 0.5
+
/** Cap is the side away from the value-axis baseline; pass `shouldRoundCap: false` for stacked
* layers below the topmost. `shouldRoundBaseline` rounds the side *towards* the baseline — used
* for the bottom-of-stack layer so a funnel-style bar reads as one rounded pill on both ends. */
@@ -179,7 +182,16 @@ export function computeBarAtIndex({
// which differs by orientation: horizontal = larger x-pixel, vertical = smaller y-pixel (axis is inverted).
const isPositive = isHorizontal ? topPixel >= bottomPixel : topPixel <= bottomPixel
const corners = cornersFor(isHorizontal, isPositive, shouldRoundCap, shouldRoundBaseline)
- return makeBarRect(isHorizontal, bandStart, bandWidth, topPixel, bottomPixel, corners, dataIndex)
+ // Extend an interior segment a sub-pixel toward the baseline so it overlaps its lower neighbour,
+ // hiding the faint anti-aliased seam where two adjacent fills meet on a fractional device pixel.
+ // 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 overlappedBottom = sitsOnBaseline
+ ? bottomPixel
+ : bottomPixel + STACK_SEGMENT_OVERLAP_PX * Math.sign(bottomPixel - topPixel)
+ return makeBarRect(isHorizontal, bandStart, bandWidth, topPixel, overlappedBottom, corners, dataIndex)
}
/** The track rect behind a bar — the bar's band slot stretched across the whole value
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index 77174317fd24..fd9fbc00146b 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -301,6 +301,32 @@ export function drawPoints(drawCtx: DrawContext, series: ResolvedSeries, yValues
}
}
+export interface DrawAxesOptions {
+ axisColor?: string
+}
+
+/** Draws just the L-shaped axis baselines — the left value axis and the bottom category axis —
+ * without any interior grid lines. For charts that want axis framing but a clean, grid-free plot. */
+export function drawAxes(drawCtx: DrawContext, options: DrawAxesOptions = {}): void {
+ const { ctx, dimensions } = drawCtx
+ ctx.strokeStyle = options.axisColor ?? 'rgba(0, 0, 0, 0.15)'
+ ctx.lineWidth = 1
+ ctx.setLineDash([])
+ // +0.5 / -0.5 pixel snapping keeps the 1px strokes crisp and inside the plot rect (see drawGrid).
+ const axisX = Math.round(dimensions.plotLeft) + 0.5
+ const axisY = Math.round(dimensions.plotTop + dimensions.plotHeight) - 0.5
+ // Route both strokes through the shared, snapped corner (axisX, axisY) so the L meets cleanly
+ // even when plotLeft/plotHeight are fractional.
+ ctx.beginPath()
+ ctx.moveTo(axisX, dimensions.plotTop)
+ ctx.lineTo(axisX, axisY)
+ ctx.stroke()
+ ctx.beginPath()
+ ctx.moveTo(axisX, axisY)
+ ctx.lineTo(dimensions.plotLeft + dimensions.plotWidth, axisY)
+ ctx.stroke()
+}
+
export interface DrawGridOptions {
gridColor?: string
orientation?: 'vertical' | 'horizontal'
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
index ed7105cc9fd6..db73c7bf71d8 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
@@ -13,6 +13,9 @@ const COLLAPSED_AXIS_MARGIN = 8
const MIN_LEFT_MARGIN = 20
const MIN_RIGHT_MARGIN_DUAL_AXIS = 48
const Y_LABEL_RIGHT_PADDING = 12
+// Gutter left of the y-axis labels so the widest label doesn't sit flush at the plot's left edge
+// and clip against the chart wrapper's `overflow: hidden`.
+const Y_LABEL_LEFT_GUTTER = 6
const X_LABEL_EDGE_PADDING = 4
export const X_AXIS_TITLE_MARGIN = 22
const Y_AXIS_TITLE_MARGIN = 24
@@ -132,7 +135,7 @@ export function useChartMargins({
? COLLAPSED_AXIS_MARGIN
: Math.max(
MIN_LEFT_MARGIN,
- Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING,
+ Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING + Y_LABEL_LEFT_GUTTER,
xLabelHalfWidth + X_LABEL_EDGE_PADDING
) + (normalizedYAxisLabel ? Y_AXIS_TITLE_MARGIN : 0)
const rightFloor = hasMultipleAxes && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index ddacf9c98405..b9f678b56bb0 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -187,6 +187,9 @@ export interface ChartConfig {
/** Show horizontal grid lines at y-axis tick positions. */
showGrid?: boolean
+ /** Draw only the L-shaped axis baselines (left + bottom) without interior grid lines. Ignored
+ * when `showGrid` is true, since the grid already frames the plot. */
+ showAxisLines?: boolean
/** Tooltip behaviour. Defaults to enabled with no pinning and `follow-data` placement. */
tooltip?: TooltipConfig
/** Show a vertical crosshair line that follows the cursor. */
@@ -244,8 +247,10 @@ export interface BarsConfig {
/** Draw a faint hatched track behind each bar, spanning the full plot height — for
* funnel-style charts where every bar is a share of a whole. Only honored when
* `barLayout: 'grouped'`; ignored for stacked/percent (the "share of a whole"
- * semantics don't apply when bars share a band). Defaults to `false`. */
- track?: boolean
+ * semantics don't apply when bars share a band). Defaults to `false`. `true` also
+ * highlights the track region on hover; pass `{ hover: false }` to draw the track
+ * but leave it inert (no highlight when the cursor is over the empty remainder). */
+ track?: boolean | { hover?: boolean }
/** Drop shadow under each bar so it reads as layered over a `track`. */
shadow?: boolean | { color: string; blur: number; offsetX?: number; offsetY?: number }
/** Bar fill treatment. `flat` (default) is a solid color. `gradient` is a smooth diagonal
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
index 91fa44f78899..4035eb4960f6 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
@@ -404,4 +404,45 @@ describe('ValueLabels', () => {
.sort()
).toEqual(['20%', '40%', '60%', '80%'])
})
+
+ describe('offset', () => {
+ it('nudges a vertical above-label up by the offset', () => {
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [50] }]
+ const { container } = renderInChart(makeContext(series, { labels: ['Mon'] }), <ValueLabels offset={6} />)
+ const divs = labelDivs(container)
+ expect(divs).toHaveLength(1)
+ expect(divs[0].style.transform).toBe('translate(-50%, -100%) translate(0px, -6px)')
+ })
+
+ it('nudges a horizontal label outward from the bar tip by the offset', () => {
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [1] }]
+ const ctx = makeContext(series, {
+ axisOrientation: 'horizontal',
+ labels: ['Mon'],
+ scales: { x: () => 200, y: () => 400, yTicks: () => [0, 1] },
+ })
+ const divs = labelDivs(renderInChart(ctx, <ValueLabels offset={6} />).container)
+ expect(divs).toHaveLength(1)
+ expect(divs[0].style.transform).toBe('translateY(-50%) translate(6px, 0px)')
+ })
+
+ it('ignores offset for centered percent-mode labels', () => {
+ const series: ResolvedSeries[] = [
+ { key: 'a', label: 'A', color: '#f00', data: [20, 60] },
+ { key: 'b', label: 'B', color: '#0f0', data: [80, 40] },
+ ]
+ const percentScales: ChartScales = { x: xScale, y: (v: number) => 368 - v * 352, yTicks: () => [0, 0.5, 1] }
+ const positionByKey: Record<string, number[]> = { a: [0.2, 0.6], b: [1.0, 1.0] }
+ const resolvePositionValue: ResolveValueFn = (s, i) => positionByKey[s.key]?.[i] ?? 0
+ const ctx = makeContext(series, {
+ isPercent: true,
+ labels: ['Mon', 'Tue'],
+ scales: percentScales,
+ resolvePositionValue,
+ })
+ const divs = labelDivs(renderInChart(ctx, <ValueLabels offset={6} />).container)
+ expect(divs.length).toBeGreaterThan(0)
+ divs.forEach((d) => expect(d.style.transform).toBe('translate(-50%, -50%)'))
+ })
+ })
})
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
index 407c1f064934..af75abab4feb 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
@@ -36,13 +36,16 @@ export interface ValueLabelsProps {
valueFormatter?: ValueLabelFormatter
minGap?: number
mode?: ValueLabelsMode
+ /** Gap in px between the bar tip and the label, applied along the value axis in the outward
+ * direction (right/above the tip, or inward for labels flipped inside a clipped bar). Ignored
+ * for centered (`percent`) labels. Defaults to 0 — the label's edge sits on the bar tip. */
+ offset?: number
}
const LABEL_FONT =
'600 12px -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif'
const LABEL_HEIGHT = 22
const LABEL_PADDING_X = 4
-const LABEL_PADDING_Y = 2
const LABEL_BORDER = 2
const LABEL_HORIZONTAL_CHROME = (LABEL_PADDING_X + LABEL_BORDER) * 2
const STACK_TOTAL_KEY = '__stack_total__'
@@ -402,11 +405,18 @@ function applyCollisionAvoidance(candidates: Candidate[], minGap: number, isHori
const LABEL_STYLE_BASE: React.CSSProperties = {
position: 'absolute',
+ // Fixed, even border-box height so `translateY(-50%)` lands on a whole pixel (no half-pixel
+ // bias) and the text is flex-centered rather than relying on line-height to centre it.
+ boxSizing: 'border-box',
+ height: LABEL_HEIGHT,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
color: 'white',
fontSize: 12,
fontWeight: 600,
- lineHeight: 1.2,
- padding: `${LABEL_PADDING_Y}px ${LABEL_PADDING_X}px`,
+ lineHeight: 1,
+ padding: `0 ${LABEL_PADDING_X}px`,
borderRadius: 4,
borderWidth: LABEL_BORDER,
borderStyle: 'solid',
@@ -415,7 +425,7 @@ const LABEL_STYLE_BASE: React.CSSProperties = {
transition: 'transform 150ms ease-out',
}
-function transformFor(c: Candidate, isHorizontal: boolean, hovered: boolean): string {
+function transformFor(c: Candidate, isHorizontal: boolean, hovered: boolean, offset: number): string {
// Lift direction depends on which side of the value-axis the label sits on.
let liftX = 0
let liftY = 0
@@ -428,6 +438,15 @@ function transformFor(c: Candidate, isHorizontal: boolean, hovered: boolean): st
liftY = c.above ? -HOVER_LIFT_PX : HOVER_LIFT_PX
}
}
+ // Nudge the label off the bar tip, away from the baseline (or inward when flipped inside a
+ // clipped bar so the gap stays on the bar side). Centered labels sit on the segment, no offset.
+ if (offset && !c.centerAnchor) {
+ if (isHorizontal) {
+ liftX += c.above ? offset : -offset
+ } else {
+ liftY += c.above ? -offset : offset
+ }
+ }
const lift = liftX === 0 && liftY === 0 ? '' : ` translate(${liftX}px, ${liftY}px)`
if (c.centerAnchor) {
return `translate(-50%, -50%)${lift}`
@@ -442,6 +461,7 @@ export function ValueLabels({
valueFormatter,
minGap = 4,
mode = 'per-segment',
+ offset = 0,
}: ValueLabelsProps): React.ReactElement | null {
const { series, scales, labels, theme, resolvePositionValue, axis, dimensions } = useChartLayout()
const { hoverIndex } = useChartHover()
@@ -513,7 +533,7 @@ export function ValueLabels({
borderColor,
left: Math.round(c.x),
top: Math.round(c.y),
- transform: transformFor(c, isHorizontal, isHovered),
+ transform: transformFor(c, isHorizontal, isHovered, offset),
willChange: isHovered ? 'transform' : undefined,
}}
>