: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
refactor(quill-charts): render a y-axis title per axis at its gutter (#65093)
Sam Pennington3e3c22961fca
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d50ddfa0aac1..e63ae2708690 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -909,13 +909,13 @@ snapshots:components-hogcharts-timeserieslinechart--drag-to-zoom--light:hash: v1.k794b7964.7d8de1c664f78dad36682304cd25c746266b6fb509d28bcaf2d8ae629a808284.eGlPABfqYjC1-H2VGiv5lJxfPOXP5U2fpK2cr7CtOT4components-hogcharts-timeserieslinechart--dual-y-axis--dark:- hash: v1.k794b7964.9dd0eaaa2cc7cb1f24435e4ef698026fdff68203f5f47458aae13f44d1f5a728.q1wTd45_ueu_x_Zse6xADTOqGZ08WtEMo0EVf1th-Ws+ hash: v1.k794b7964.08f3d6c5cfb18f6016608aa4dbb7cd6fe9e47edebb0f0348a7efb3ac9b260069.P2j41Bw733-VMbNmMBsHVdIkG289MsmHhk_m0tU7BWocomponents-hogcharts-timeserieslinechart--dual-y-axis--light:- hash: v1.k794b7964.74c876ccaa5fec4e36be5caab089532d26162d4cc8e5d0462331cbfb9b945b07.P2nBmV3pHVf81hjDjOYyrU5VnlwdRy-VAn19v7huY2A+ hash: v1.k794b7964.1f138ad789223e20e6ce5a44a606eef88a656cc6e6f1a9b97509d41097924487.ahlyjBbCBI_xNK_wpzuGHu7ggQpeg9TEWbuK2JfankMcomponents-hogcharts-timeserieslinechart--dual-y-axis-mixed-scales--dark:- hash: v1.k794b7964.29818ddbe1b02235c664d60287f532df226476a1397e5fd338462b91cb8b1a43.Gb-KIUMh9HExDL0NOX4gpVcDQKhglUXmBLo_CKKV4Ik+ hash: v1.k794b7964.f707dca453892b302d4fb7d9de170e8fc06724d15b279058e7abb8ca2da86223.njpHnoZg1z2SZ9s-p-V14hb6U_GmOGvjJYjEqsAHVwgcomponents-hogcharts-timeserieslinechart--dual-y-axis-mixed-scales--light:- hash: v1.k794b7964.3fe1803ae3e039ead859da938fdef88300ab6ff08254757da777556a499636ff.Ne7zpBUPko3GyNTT5tmSZqQeKABJyVdObd1Sz2V_Cj0+ hash: v1.k794b7964.beaba679099c68a2741f10fd75af0ce911c82fbb7bd6facd4991fabf21d0f70d.PCyv0DEoo5ZDgud3iDg7VCZlyy1-3P7KVM6YIuqGkdwcomponents-hogcharts-timeserieslinechart--moving-average--dark:hash: v1.k794b7964.e332e9beb6b72bee51ab22b8078273883dabe8cd97163f6005a44367378fa8f7.H_JLql_NFDi4zX-Gn0svc0N_NewsyAhqaII4UGIXykgcomponents-hogcharts-timeserieslinechart--moving-average--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex a11804db7e0b..7ffb4ecc99d6 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -78,7 +78,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped'`) and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.-- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. `TimeSeriesBarChart`/`ComboChart` already render per-`yAxisId` axes but share one tick formatter across gutters.+- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`ComboChart` already render per-`yAxisId` axes but share one tick formatter across gutters.- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.## Testingdiff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsxindex 92a40afa195a..8daa8c4cb7db 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx@@ -241,22 +241,31 @@ describe('TimeSeriesLineChart', () => {expect(Math.max(...chart.yRightTicks().map(num))).toBeLessThanOrEqual(1)})- it('renders the right-axis title from the right entry label', () => {+ it('renders a title per axis, each from its own entry label', () => {+ const threeAxisSeries: Series[] = [+ { key: 'rev', label: 'Revenue', data: [1000, 1500, 1200] },+ { key: 'signups', label: 'Signups', data: [50, 80, 65], yAxisId: 'right' },+ { key: 'conv', label: 'Conversion', data: [0.01, 0.02, 0.015], yAxisId: 'right2' },+ ]const { container, chart } = renderHogChart(<TimeSeriesLineChart- series={LEFT_RIGHT_SERIES}+ series={threeAxisSeries}labels={LABELS}theme={THEME}config={{yAxis: [{ id: 'left', label: 'Revenue' },- { id: 'right', position: 'right', label: 'Conversion' },+ { id: 'right', position: 'right', label: 'Signups' },+ { id: 'right2', position: 'right', label: 'Conversion' },],}}/>)+ const rightTitles = Array.from(+ container.querySelectorAll<SVGTextElement>('[data-attr="hog-chart-axis-title-yr"]')+ ).map((el) => el.textContent)expect(chart.yAxisLabel()).toBe('Revenue')- expect(container.querySelector('[data-attr="hog-chart-axis-title-yr"]')?.textContent).toBe('Conversion')+ expect(rightTitles).toEqual(['Signups', 'Conversion'])})it('reserves right margin so right-axis tick labels are not clipped', () => {diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsxindex c65664088256..bacea09aef4d 100644--- a/packages/quill/packages/charts/src/core/Chart.tsx+++ b/packages/quill/packages/charts/src/core/Chart.tsx@@ -17,6 +17,7 @@ import { useLatest } from './hooks/useLatest'import { useResolvedYFormatter } from './hooks/useResolvedYFormatters'import { useStableResolveValue } from './hooks/useStableResolveValue'import { useYAxisMaps } from './hooks/useYAxisMaps'+import { computeYAxisGutters, type Gutter } from './y-axis-gutters'import type {ChartConfig,ChartDrawArgs,@@ -127,13 +128,10 @@ export function Chart<Meta = unknown>({yAxes,} = config ?? {}- // Per-axis tick formatters, sides, and right-axis title for multi-axis charts. Each gutter- // formats against its own axis config; absent here, an axis auto-formats against its ticks.- const {- formatters: yAxisFormatters,- positions: yAxisPositions,- labelRight: yAxisLabelRight,- } = useYAxisMaps(yAxes)+ const { formatters: yAxisFormatters, positions: yAxisPositions, titles: yAxisTitles } = useYAxisMaps(+ yAxes,+ yAxisLabel+ )const hoverAnimationMs = resolveHoverAnimationMs(animateHover)const interactionAxis: 'x' | 'y' = axisOrientation === 'horizontal' ? 'y' : 'x'const {@@ -168,7 +166,6 @@ export function Chart<Meta = unknown>({hideXAxis,hideYAxis,xAxisLabel,- yAxisLabel,xTickFormatter,yTickFormatter,axisOrientation,@@ -177,7 +174,7 @@ export function Chart<Meta = unknown>({maxCategoryLabelWidth,yAxisFormatters,yAxisPositions,- yAxisLabelRight,+ yAxisTitles,})const { canvasRef, overlayCanvasRef, wrapperRef, dimensions, ctx, overlayCtx } = useChartCanvas({ margins })@@ -264,6 +261,21 @@ export function Chart<Meta = unknown>({)const axisColor = theme.axisColor ?? DEFAULT_AXIS_COLOR+ // Computed once and shared with AxisLabels and AxisTitles via context so they can't drift.+ const yGutters = useMemo<Gutter[]>(+ () =>+ !scales || hideYAxis || axisOrientation === 'horizontal'+ ? []+ : computeYAxisGutters(scales, {+ yTicks: scales.yTicks(),+ yTickFormatter: resolvedYFormatter,+ userYTickFormatter: yTickFormatter,+ yAxisFormatters,+ titles: yAxisTitles,+ }),+ [scales, hideYAxis, axisOrientation, resolvedYFormatter, yTickFormatter, yAxisFormatters, yAxisTitles]+ )+const layoutValue = useMemo<ChartLayoutContextValue | null>(() => {if (!scales || !dimensions) {return null@@ -277,8 +289,9 @@ export function Chart<Meta = unknown>({resolvePositionValue: stablePositionValue,canvasBounds,axis: axisValue,+ yGutters,}- }, [scales, dimensions, labels, coloredSeries, theme, stablePositionValue, canvasBounds, axisValue])+ }, [scales, dimensions, labels, coloredSeries, theme, stablePositionValue, canvasBounds, axisValue, yGutters])const hoverValue = useMemo<ChartHoverContextValue>(() => ({ hoverIndex }), [hoverIndex])@@ -300,8 +313,6 @@ export function Chart<Meta = unknown>({<AxisLabelsxTickFormatter={xTickFormatter}yTickFormatter={resolvedYFormatter}- userYTickFormatter={yTickFormatter}- yAxisFormatters={yAxisFormatters}hideXAxis={hideXAxis}hideYAxis={hideYAxis}axisColor={axisColor}@@ -312,9 +323,9 @@ export function Chart<Meta = unknown>({<AxisTitlesxAxisLabel={xAxisLabel}yAxisLabel={yAxisLabel}- yAxisLabelRight={yAxisLabelRight}hideXAxis={hideXAxis}hideYAxis={hideYAxis}+ orientation={axisOrientation}axisColor={axisColor}/>diff --git a/packages/quill/packages/charts/src/core/RadialChart.tsx b/packages/quill/packages/charts/src/core/RadialChart.tsxindex 55caaa17c376..91c7d13c5474 100644--- a/packages/quill/packages/charts/src/core/RadialChart.tsx+++ b/packages/quill/packages/charts/src/core/RadialChart.tsx@@ -144,6 +144,7 @@ export function RadialChart<Meta = unknown>({resolvePositionValue: defaultResolveValue,canvasBounds,axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },+ yGutters: [],}}, [scales, dimensions, coloredSeries, theme, canvasBounds])diff --git a/packages/quill/packages/charts/src/core/chart-context.test.tsx b/packages/quill/packages/charts/src/core/chart-context.test.tsxindex 37372527a1db..5a304900d767 100644--- a/packages/quill/packages/charts/src/core/chart-context.test.tsx+++ b/packages/quill/packages/charts/src/core/chart-context.test.tsx@@ -16,6 +16,7 @@ const LAYOUT: ChartLayoutContextValue = {resolvePositionValue: (s, i) => s.data[i] ?? 0,canvasBounds: () => null,axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },+ yGutters: [],}describe('chart-context split', () => {diff --git a/packages/quill/packages/charts/src/core/chart-context.ts b/packages/quill/packages/charts/src/core/chart-context.tsindex 34ad5f1acb77..8f255f4fb10e 100644--- a/packages/quill/packages/charts/src/core/chart-context.ts+++ b/packages/quill/packages/charts/src/core/chart-context.ts@@ -1,6 +1,7 @@import { createContext, useContext } from 'react'import type { ChartDimensions, ChartScales, ChartTheme, ResolvedSeries, ResolveValueFn } from './types'+import type { Gutter } from './y-axis-gutters'/** Axis-related state exposed to overlays. */export interface ChartAxisContextValue {@@ -39,6 +40,9 @@ export interface ChartLayoutContextValue<Meta = unknown> {canvasBounds: () => DOMRect | null/** Axis-related state (orientation, x-axis formatter, value-scale flags). */axis: ChartAxisContextValue+ /** Stacked value-axis gutters shared by `AxisLabels` and `AxisTitles`. Empty for horizontal /+ * hidden y-axis charts. */+ yGutters: Gutter[]}/** Hover state isolated from layout so mousemoves don't invalidate every overlay.diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.tsindex 9ca500b89f02..da53555b75ba 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts@@ -54,14 +54,26 @@ describe('useChartMargins', () => {expect(empty.left).toBeGreaterThanOrEqual(fourCharLabelReserve)})- it('adds left space for a y-axis title', () => {- const withoutTitle = render()- const withTitle = render({ yAxisLabel: 'Unique users' })+ it('reserves the left title band for a horizontal chart category-axis title', () => {+ const withoutTitle = render({ axisOrientation: 'horizontal' })+ const withTitle = render({ axisOrientation: 'horizontal', yAxisTitles: { left: 'Series' } })expect(withTitle.left).toBeGreaterThan(withoutTitle.left)})- it('does not add left space for a whitespace-only y-axis title', () => {- expect(render({ yAxisLabel: ' ' }).left).toBe(render().left)+ it('reserves a title band per titled axis stacked on the same side', () => {+ const threeAxis: Series[] = [+ { key: 'a', label: 'A', data: [1, 2, 3] },+ { key: 'b', label: 'B', data: [4, 5, 6], yAxisId: 'right' },+ { key: 'c', label: 'C', data: [7, 8, 9], yAxisId: 'right2' },+ ]+ const positions = { left: 'left', right: 'right', right2: 'right' } as const+ const oneTitle = render({ series: threeAxis, yAxisPositions: positions, yAxisTitles: { right: 'One' } })+ const twoTitles = render({+ series: threeAxis,+ yAxisPositions: positions,+ yAxisTitles: { right: 'One', right2: 'Two' },+ })+ expect(twoTitles.right).toBeGreaterThan(oneTitle.right)})it('grows the right margin to at least 48 when multiple y-axes are present', () => {diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.tsindex 81236f825dce..02d1cf2b206b 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts@@ -21,7 +21,7 @@ const Y_LABEL_LEFT_GUTTER = 6export const GUTTER_GAP = 12const X_LABEL_EDGE_PADDING = 4export const X_AXIS_TITLE_MARGIN = 22-const Y_AXIS_TITLE_MARGIN = 24+export const Y_AXIS_TITLE_MARGIN = 24interface UseChartMarginsOptions {series: Series[]@@ -29,7 +29,6 @@ interface UseChartMarginsOptions {hideXAxis: booleanhideYAxis: booleanxAxisLabel?: string- yAxisLabel?: stringxTickFormatter?: (value: string, index: number) => string | nullyTickFormatter?: (value: number) => stringaxisOrientation?: 'vertical' | 'horizontal'@@ -49,8 +48,7 @@ interface UseChartMarginsOptions {/** Per-axis sides keyed by axis id, overriding the alternating-side default. Keeps the margin* reservation in step with the scales' config-driven positions. Multi-axis charts only. */yAxisPositions?: Record<string, 'left' | 'right'>- /** Right-side y-axis title — reserves extra right margin so it doesn't clip. */- yAxisLabelRight?: string+ yAxisTitles?: Record<string, string>}function widestCategoryLabelWidth(@@ -93,7 +91,6 @@ export function useChartMargins({hideXAxis,hideYAxis,xAxisLabel,- yAxisLabel,xTickFormatter,yTickFormatter,axisOrientation = 'vertical',@@ -102,13 +99,11 @@ export function useChartMargins({maxCategoryLabelWidth = 0,yAxisFormatters,yAxisPositions,- yAxisLabelRight,+ yAxisTitles,}: UseChartMarginsOptions): ChartMargins {const isHorizontal = axisOrientation === 'horizontal'const valueSeries = valueRangeSeries ?? seriesconst normalizedXAxisLabel = normalizeAxisLabel(xAxisLabel)- const normalizedYAxisLabel = normalizeAxisLabel(yAxisLabel)- const normalizedYAxisLabelRight = normalizeAxisLabel(yAxisLabelRight)const hasMultipleAxes = useMemo(() => {const axisIds = new Set(@@ -117,6 +112,30 @@ export function useChartMargins({return axisIds.size > 1}, [series])+ // One rotated-title band per titled axis, on its side. Horizontal charts (category axis on the+ // left) and single-value-axis charts only ever title the default left axis.+ const titleReserve = useMemo<{ left: number; right: number }>(() => {+ if (hideYAxis || !yAxisTitles) {+ return { left: 0, right: 0 }+ }+ if (isHorizontal || !hasMultipleAxes) {+ return { left: yAxisTitles[DEFAULT_Y_AXIS_ID] ? Y_AXIS_TITLE_MARGIN : 0, right: 0 }+ }+ let left = 0+ let right = 0+ for (const { axisId, position } of orderedAxisPositions(valueSeries)) {+ if (!yAxisTitles[axisId]) {+ continue+ }+ if ((yAxisPositions?.[axisId] ?? position) === 'left') {+ left += Y_AXIS_TITLE_MARGIN+ } else {+ right += Y_AXIS_TITLE_MARGIN+ }+ }+ return { left, right }+ }, [hideYAxis, isHorizontal, hasMultipleAxes, valueSeries, yAxisPositions, yAxisTitles])+const yLabelWidth = useMemo<number>(() => {if (hideYAxis) {return 0@@ -186,9 +205,9 @@ export function useChartMargins({MIN_LEFT_MARGIN,leftLabelReserve + Y_LABEL_LEFT_GUTTER,xLabelHalfWidth + X_LABEL_EDGE_PADDING- ) + (normalizedYAxisLabel ? Y_AXIS_TITLE_MARGIN : 0)+ ) + titleReserve.leftconst rightFloor = hasMultipleAxes && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right- const rightLabelReserve = (gutterReserves?.right ?? 0) + (normalizedYAxisLabelRight ? Y_AXIS_TITLE_MARGIN : 0)+ const rightLabelReserve = (gutterReserves?.right ?? 0) + titleReserve.rightconst 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@@ -200,8 +219,7 @@ export function useChartMargins({yLabelWidth,xLabelHalfWidth,normalizedXAxisLabel,- normalizedYAxisLabel,- normalizedYAxisLabelRight,+ titleReserve,override,])}diff --git a/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.ts b/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.tsindex fd8d0b40eece..d1714da261a7 100644--- a/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.ts+++ b/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.ts@@ -1,5 +1,7 @@import { useMemo } from 'react'+import { normalizeAxisLabel } from '../../utils/axis-labels'+import { DEFAULT_Y_AXIS_ID } from '../types'import type { YAxis } from '../types'export interface YAxisMaps {@@ -7,29 +9,39 @@ export interface YAxisMaps {formatters?: Record<string, (value: number) => string>/** Per-axis side keyed by axis id. */positions?: Record<string, 'left' | 'right'>- /** Title of the right-side axis, if any. */- labelRight?: string+ /** Per-axis titles keyed by axis id; single-axis charts fall back to the scalar `yAxisLabel`. */+ titles: Record<string, string>}-/** Derive the per-axis lookup maps the base chart's margins, labels, and titles need from the- * resolved axes. All fields are absent for single-axis charts (`yAxes` omitted). */-export function useYAxisMaps(yAxes: YAxis[] | undefined): YAxisMaps {+/** Per-axis tick formatters, sides, and titles keyed by axis id (formatters/sides are absent for+ * single-axis charts). */+export function useYAxisMaps(yAxes: YAxis[] | undefined, yAxisLabel?: string): YAxisMaps {return useMemo(() => {if (!yAxes) {- return {}+ const label = normalizeAxisLabel(yAxisLabel)+ const titles: Record<string, string> = {}+ if (label) {+ titles[DEFAULT_Y_AXIS_ID] = label+ }+ return { titles }}const formatters: Record<string, (value: number) => string> = {}const positions: Record<string, 'left' | 'right'> = {}+ const titles: Record<string, string> = {}for (const axis of yAxes) {if (axis.tickFormatter) {formatters[axis.id] = axis.tickFormatter}positions[axis.id] = axis.position+ const label = normalizeAxisLabel(axis.label)+ if (label) {+ titles[axis.id] = label+ }}return {formatters: Object.keys(formatters).length > 0 ? formatters : undefined,positions,- labelRight: yAxes.find((axis) => axis.position === 'right')?.label,+ titles,}- }, [yAxes])+ }, [yAxes, yAxisLabel])}diff --git a/packages/quill/packages/charts/src/core/y-axis-gutters.test.ts b/packages/quill/packages/charts/src/core/y-axis-gutters.test.tsnew file mode 100644index 000000000000..74cebd539260--- /dev/null+++ b/packages/quill/packages/charts/src/core/y-axis-gutters.test.ts@@ -0,0 +1,45 @@+import { GUTTER_GAP, Y_AXIS_TITLE_MARGIN } from './hooks/useChartMargins'+import type { ChartScales, YAxisScale } from './types'+import { computeYAxisGutters } from './y-axis-gutters'++jest.mock('../utils/text-measure', () => ({ measureLabelWidth: (text: string) => text.length * 10 }))++const identity = (value: number): number => value++function scales(yAxes?: Record<string, YAxisScale>): ChartScales {+ return { x: () => 0, y: identity, yTicks: () => [1, 2, 3], yAxes }+}++const axis = (position: 'left' | 'right'): YAxisScale => ({ scale: identity, ticks: () => [0], position })++const formatters = { left: () => 'X', right: () => 'XX', right2: () => 'XXX' }++describe('computeYAxisGutters', () => {+ it('returns a single left gutter for the single-axis fallback', () => {+ const gutters = computeYAxisGutters(scales(), { yTicks: [1, 2, 3] })+ expect(gutters).toHaveLength(1)+ expect(gutters[0]).toMatchObject({ axisId: 'left', side: 'left', offset: 0 })+ })++ it('stacks same-side gutters outward, each offset by the inner gutters width plus the gap', () => {+ const gutters = computeYAxisGutters(scales({ left: axis('left'), right: axis('right'), right2: axis('right') }), {+ yTicks: [],+ yAxisFormatters: formatters,+ })+ const right = gutters.find((g) => g.axisId === 'right')+ const right2 = gutters.find((g) => g.axisId === 'right2')+ expect(right).toMatchObject({ offset: 0, width: 20 })+ expect(right2?.offset).toBe(20 + GUTTER_GAP)+ })++ it('reserves a title band that pushes the next same-side gutter out', () => {+ const gutters = computeYAxisGutters(scales({ left: axis('left'), right: axis('right'), right2: axis('right') }), {+ yTicks: [],+ yAxisFormatters: formatters,+ titles: { right: 'Inner title' },+ })+ const right2 = gutters.find((g) => g.axisId === 'right2')+ expect(right2?.offset).toBe(20 + GUTTER_GAP + Y_AXIS_TITLE_MARGIN)+ expect(gutters.find((g) => g.axisId === 'right')?.title).toBe('Inner title')+ })+})diff --git a/packages/quill/packages/charts/src/core/y-axis-gutters.ts b/packages/quill/packages/charts/src/core/y-axis-gutters.tsnew file mode 100644index 000000000000..f6977ba50510--- /dev/null+++ b/packages/quill/packages/charts/src/core/y-axis-gutters.ts@@ -0,0 +1,90 @@+import { measureLabelWidth } from '../utils/text-measure'+import { GUTTER_GAP, Y_AXIS_TITLE_MARGIN } from './hooks/useChartMargins'+import { autoFormatterFor } from './scales'+import { DEFAULT_Y_AXIS_ID } from './types'+import type { ChartScales } from './types'++/** One stacked value-axis gutter. `offset` is its outward pixel distance from the plot edge; the+ * next gutter out clears this one's `width` + {@link GUTTER_GAP}, plus a title band when titled. */+export interface Gutter {+ axisId: string+ key: string+ side: 'left' | 'right'+ offset: number+ width: number+ title?: string+ ticks: number[]+ scale: (value: number) => number+ formatter: (value: number) => string+}++export interface YAxisGutterOptions {+ /** `scales.yTicks()` — used for the single-axis path. */+ yTicks: number[]+ yTickFormatter?: (value: number) => string+ /** Like `yTickFormatter` but only the multi-axis path consults it; the single-axis path already+ * resolves the user formatter into `yTickFormatter`. */+ userYTickFormatter?: (value: number) => string+ yAxisFormatters?: Record<string, (value: number) => string>+ titles?: Record<string, string>+}++/** Gap from the plot edge to a gutter's tick labels — shared by AxisLabels and AxisTitles. */+export const TICK_GAP = 8++function widestTickWidth(ticks: number[], formatter: (value: number) => string): number {+ return ticks.reduce((widest, tick) => Math.max(widest, measureLabelWidth(formatter(tick))), 0)+}++/** Resolve the stacked value-axis gutters, outermost-last per side — one per axis when `scales.yAxes`+ * is present (`showMultipleYAxes`), else a single left gutter. Shared by `AxisLabels` (ticks) and+ * `AxisTitles` (titles) so the two can't drift. */+export function computeYAxisGutters(+ scales: ChartScales,+ { yTicks, yTickFormatter, userYTickFormatter, yAxisFormatters, titles }: YAxisGutterOptions+): Gutter[] {+ if (!scales.yAxes) {+ const formatter = yTickFormatter ?? autoFormatterFor(yTicks)+ return [+ {+ axisId: DEFAULT_Y_AXIS_ID,+ key: 'y-left',+ side: 'left',+ offset: 0,+ width: widestTickWidth(yTicks, formatter),+ title: titles?.[DEFAULT_Y_AXIS_ID],+ ticks: yTicks,+ scale: scales.y,+ formatter,+ },+ ]+ }+ let leftCum = 0+ let rightCum = 0+ const gutters: Gutter[] = []+ for (const [axisId, axis] of Object.entries(scales.yAxes)) {+ const ticks = axis.ticks()+ const formatter = yAxisFormatters?.[axisId] ?? userYTickFormatter ?? autoFormatterFor(ticks)+ const offset = axis.position === 'left' ? leftCum : rightCum+ const width = widestTickWidth(ticks, formatter)+ const title = titles?.[axisId]+ gutters.push({+ axisId,+ key: `y-${axisId}`,+ side: axis.position,+ offset,+ width,+ title,+ ticks,+ scale: axis.scale,+ formatter,+ })+ const step = width + GUTTER_GAP + (title ? Y_AXIS_TITLE_MARGIN : 0)+ if (axis.position === 'left') {+ leftCum += step+ } else {+ rightCum += step+ }+ }+ return gutters+}diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex f5f9e4e5d0a3..237d68a45a83 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -78,6 +78,7 @@ export type { RadialSlicePayload } from './core/hooks/useRadialInteraction'// Chart context (for custom overlay children)export { useChart, useChartHover, useChartLayout } from './core/chart-context'export type { BaseChartContext, ChartHoverContextValue, ChartLayoutContextValue } from './core/chart-context'+export type { Gutter } from './core/y-axis-gutters'// Core typesexport type {diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx b/packages/quill/packages/charts/src/overlays/AxisLabels.tsxindex 56f0c62afa50..c7d5b42f0212 100644--- a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx@@ -1,19 +1,12 @@import React, { useMemo } from 'react'import { useChartLayout } from '../core/chart-context'-import { GUTTER_GAP } from '../core/hooks/useChartMargins'-import { autoFormatterFor } from '../core/scales'-import { AXIS_LABEL_FONT, getTextMeasureCtx, measureLabelWidth, truncateToWidth } from '../utils/text-measure'+import { TICK_GAP } from '../core/y-axis-gutters'+import { AXIS_LABEL_FONT, getTextMeasureCtx, truncateToWidth } from '../utils/text-measure'interface AxisLabelsProps {xTickFormatter?: (value: string, index: number) => string | nullyTickFormatter?: (value: number) => string- /** The *unresolved* user y-tick formatter (config). When set, every stacked axis uses it; when- * unset, each axis auto-formats against its own ticks. Only consulted for the multi-axis path. */- userYTickFormatter?: (value: number) => string- /** Per-axis tick formatters keyed by axis id. A gutter prefers its own formatter, then- * `userYTickFormatter`, then auto-formats against its ticks. Only consulted for the multi-axis path. */- yAxisFormatters?: Record<string, (value: number) => string>hideXAxis?: booleanhideYAxis?: booleanaxisColor?: string@@ -135,18 +128,6 @@ const TICK_STYLE_BASE: React.CSSProperties = {whiteSpace: 'nowrap',}-const TICK_GAP = 8--/** One stacked value-axis gutter: its ticks, scale, side, and outward pixel offset from the plot edge. */-interface Gutter {- key: string- side: 'left' | 'right'- offset: number- ticks: number[]- scale: (v: number) => number- formatter: (v: number) => string-}-interface ChartBox {width: numberplotLeft: number@@ -232,8 +213,6 @@ function XTickLabel({export const AxisLabels = React.memo(function AxisLabels({xTickFormatter,yTickFormatter,- userYTickFormatter,- yAxisFormatters,hideXAxis,hideYAxis,axisColor = 'rgba(0, 0, 0, 0.5)',@@ -241,50 +220,9 @@ export const AxisLabels = React.memo(function AxisLabels({labelToCoord,maxCategoryLabelWidth = 0,}: AxisLabelsProps): React.ReactElement | null {- const { scales, dimensions, labels } = useChartLayout()+ const { scales, dimensions, labels, yGutters } = useChartLayout()const yTicks = scales.yTicks()- // Vertical value-axis gutters, stacked outward per side. With per-axis scales (`scales.yAxes`,- // i.e. `showMultipleYAxes`) we render one gutter per axis — each labelled with its own ticks and- // offset by the cumulative width of the inner gutters. Without, a single left gutter from the- // shared scale (`scales.y` / `scales.yTicks`). Each axis auto-formats against its own ticks- // unless the caller supplied an explicit formatter, in which case every axis shares it.- const yGutters = useMemo(() => {- if (hideYAxis || orientation === 'horizontal') {- return []- }- if (!scales.yAxes) {- return [- {- key: 'y-left',- side: 'left' as const,- offset: 0,- ticks: yTicks,- scale: scales.y,- formatter: yTickFormatter ?? autoFormatterFor(yTicks),- },- ] satisfies Gutter[]- }- const widthOf = (ticks: number[], formatter: (v: number) => string): number =>- ticks.reduce((widest, t) => Math.max(widest, measureLabelWidth(formatter(t))), 0)- let leftCum = 0- let rightCum = 0- const gutters: Gutter[] = []- Object.entries(scales.yAxes).forEach(([axisId, axis]) => {- const ticks = axis.ticks()- const formatter = yAxisFormatters?.[axisId] ?? userYTickFormatter ?? autoFormatterFor(ticks)- const offset = axis.position === 'left' ? leftCum : rightCum- gutters.push({ key: `y-${axisId}`, side: axis.position, offset, ticks, scale: axis.scale, formatter })- const width = widthOf(ticks, formatter) + GUTTER_GAP- if (axis.position === 'left') {- leftCum += width- } else {- rightCum += width- }- })- return gutters- }, [hideYAxis, orientation, scales.yAxes, scales.y, yTicks, yTickFormatter, userYTickFormatter, yAxisFormatters])-const visibleXLabels = useMemo(() =>hideXAxis || orientation === 'horizontal'diff --git a/packages/quill/packages/charts/src/overlays/AxisTitles.tsx b/packages/quill/packages/charts/src/overlays/AxisTitles.tsxindex 44f47f47541e..3ea55a58c047 100644--- a/packages/quill/packages/charts/src/overlays/AxisTitles.tsx+++ b/packages/quill/packages/charts/src/overlays/AxisTitles.tsx@@ -1,16 +1,18 @@import React from 'react'import { useChartLayout } from '../core/chart-context'+import { Y_AXIS_TITLE_MARGIN } from '../core/hooks/useChartMargins'+import { TICK_GAP } from '../core/y-axis-gutters'import { normalizeAxisLabel } from '../utils/axis-labels'-import { AXIS_LABEL_FONT, measureLabelWidth } from '../utils/text-measure'+import { AXIS_LABEL_FONT, truncateToWidth } from '../utils/text-measure'export interface AxisTitlesProps {xAxisLabel?: string+ /** Category-axis title for horizontal charts only; vertical titles come per-gutter. */yAxisLabel?: string- /** Title for the right-side y-axis on a dual-axis chart. */- yAxisLabelRight?: stringhideXAxis?: booleanhideYAxis?: boolean+ orientation?: 'vertical' | 'horizontal'axisColor: string}@@ -34,72 +36,74 @@ const SVG_STYLE: React.CSSProperties = {const X_AXIS_TITLE_BASELINE_OFFSET = 6const Y_AXIS_TITLE_X = 12const TITLE_EDGE_PADDING = 8-const ELLIPSIS = '\u2026'-function measureAxisTitleWidth(label: string): number {- const measured = measureLabelWidth(label, AXIS_TITLE_FONT)- const fallback = label.length * 7- return measured > 0 ? measured : fallback-}--function truncateAxisTitle(label: string, maxWidth: number): string {- if (maxWidth <= 0 || measureAxisTitleWidth(label) <= maxWidth) {- return label- }-- const ellipsisWidth = measureAxisTitleWidth(ELLIPSIS)- if (ellipsisWidth >= maxWidth) {- return ELLIPSIS- }-- let low = 0- let high = label.length- while (low < high) {- const mid = Math.ceil((low + high) / 2)- const candidate = `${label.slice(0, mid).trimEnd()}${ELLIPSIS}`- if (measureAxisTitleWidth(candidate) <= maxWidth) {- low = mid- } else {- high = mid - 1- }- }+const truncateAxisTitle = (label: string, maxWidth: number): string => truncateToWidth(label, maxWidth, AXIS_TITLE_FONT)- return `${label.slice(0, low).trimEnd()}${ELLIPSIS}`+interface YTitle {+ key: string+ x: number+ rotation: -90 | 90+ dataAttr: string+ label: string}export function AxisTitles({xAxisLabel,yAxisLabel,- yAxisLabelRight,hideXAxis,hideYAxis,+ orientation = 'vertical',axisColor,}: AxisTitlesProps): React.ReactElement | null {- const { dimensions } = useChartLayout()+ const { dimensions, yGutters } = useChartLayout()const fullXAxisLabel = normalizeAxisLabel(xAxisLabel)- const fullYAxisLabel = normalizeAxisLabel(yAxisLabel)- const fullYAxisLabelRight = normalizeAxisLabel(yAxisLabelRight)const showXAxisTitle = !hideXAxis && !!fullXAxisLabel- const showYAxisTitle = !hideYAxis && !!fullYAxisLabel- const showYAxisTitleRight = !hideYAxis && !!fullYAxisLabelRight- if (!showXAxisTitle && !showYAxisTitle && !showYAxisTitleRight) {+ // Horizontal charts have a category y-axis with no gutter — render its single title at the left+ // edge. Vertical charts title each value gutter on its own side.+ const yTitles: YTitle[] = []+ if (orientation === 'horizontal') {+ const fullYAxisLabel = normalizeAxisLabel(yAxisLabel)+ if (!hideYAxis && fullYAxisLabel) {+ yTitles.push({+ key: 'y-cat',+ x: Y_AXIS_TITLE_X,+ rotation: -90,+ dataAttr: 'hog-chart-axis-title-y',+ label: fullYAxisLabel,+ })+ }+ } else {+ for (const { key, side, offset, width, title } of yGutters) {+ if (!title) {+ continue+ }+ // Sit in the title band just outside this gutter's tick labels (which end at+ // `TICK_GAP + offset + width` from the plot edge), centered in the band.+ const outward = TICK_GAP + offset + width + Y_AXIS_TITLE_MARGIN / 2+ const x =+ side === 'left' ? dimensions.plotLeft - outward : dimensions.plotLeft + dimensions.plotWidth + outward+ yTitles.push({+ key,+ x,+ rotation: side === 'left' ? -90 : 90,+ dataAttr: side === 'left' ? 'hog-chart-axis-title-y' : 'hog-chart-axis-title-yr',+ label: title,+ })+ }+ }++ if (!showXAxisTitle && yTitles.length === 0) {return null}const xCenter = dimensions.plotLeft + dimensions.plotWidth / 2const xBaseline = dimensions.height - X_AXIS_TITLE_BASELINE_OFFSETconst yCenter = dimensions.plotTop + dimensions.plotHeight / 2- const rightTitleX = dimensions.width - Y_AXIS_TITLE_X+ const maxYTitleWidth = Math.max(0, dimensions.plotHeight - TITLE_EDGE_PADDING * 2)const xTitle = fullXAxisLabel? truncateAxisTitle(fullXAxisLabel, Math.max(0, dimensions.plotWidth - TITLE_EDGE_PADDING * 2)): undefined- const yTitle = fullYAxisLabel- ? truncateAxisTitle(fullYAxisLabel, Math.max(0, dimensions.plotHeight - TITLE_EDGE_PADDING * 2))- : undefined- const yTitleRight = fullYAxisLabelRight- ? truncateAxisTitle(fullYAxisLabelRight, Math.max(0, dimensions.plotHeight - TITLE_EDGE_PADDING * 2))- : undefinedreturn (<svg aria-hidden="true" style={SVG_STYLE}>@@ -116,36 +120,22 @@ export function AxisTitles({{xTitle}</text>)}- {showYAxisTitle && yTitle && (- <text- data-attr="hog-chart-axis-title-y"- data-full-label={fullYAxisLabel}- x={Y_AXIS_TITLE_X}- y={yCenter}- fill={axisColor}- textAnchor="middle"- dominantBaseline="middle"- transform={`rotate(-90 ${Y_AXIS_TITLE_X} ${yCenter})`}- style={AXIS_TITLE_STYLE}- >- {yTitle}- </text>- )}- {showYAxisTitleRight && yTitleRight && (+ {yTitles.map(({ key, x, rotation, dataAttr, label }) => (<text- data-attr="hog-chart-axis-title-yr"- data-full-label={fullYAxisLabelRight}- x={rightTitleX}+ key={key}+ data-attr={dataAttr}+ data-full-label={label}+ x={x}y={yCenter}fill={axisColor}textAnchor="middle"dominantBaseline="middle"- transform={`rotate(90 ${rightTitleX} ${yCenter})`}+ transform={`rotate(${rotation} ${x} ${yCenter})`}style={AXIS_TITLE_STYLE}>- {yTitleRight}+ {truncateAxisTitle(label, maxYTitleWidth)}</text>- )}+ ))}</svg>)}diff --git a/packages/quill/packages/charts/src/testing/overlay.tsx b/packages/quill/packages/charts/src/testing/overlay.tsxindex b15518df7575..6418825b9e86 100644--- a/packages/quill/packages/charts/src/testing/overlay.tsx+++ b/packages/quill/packages/charts/src/testing/overlay.tsx@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'import { ChartHoverContext, ChartLayoutContext } from '../core/chart-context'import type { BaseChartContext, ChartLayoutContextValue } from '../core/chart-context'import type { ChartScales, ChartTheme, ResolvedSeries, ResolveValueFn } from '../core/types'+import type { Gutter } from '../core/y-axis-gutters'import { dimensions as DEFAULT_DIMENSIONS } from './jsdom'const DEFAULT_THEME: ChartTheme = { colors: ['#000'], backgroundColor: '#ffffff' }@@ -20,6 +21,7 @@ export interface OverlayContextOverrides {isPercent?: booleanhoverIndex?: numberxTickFormatter?: (value: string, index: number) => string | null+ yGutters?: Gutter[]}/** Build a fully-populated overlay context with sensible defaults. Required:@@ -39,6 +41,7 @@ export function makeOverlayContext(scales: ChartScales, overrides: OverlayContexisPercent: overrides.isPercent ?? false,},hoverIndex: overrides.hoverIndex ?? -1,+ yGutters: overrides.yGutters ?? [],}}