: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
feat(sql insights): render right y-axis series via quill-charts (#64901)
Sam Pennington285770aadeab
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.tsindex 4974018e6b3f..924900e3dd2e 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts@@ -79,9 +79,9 @@ describe('sqlLineGraphAdapter', () => {expect(canRenderSqlLineGraph(baseProps({ visualizationType, yData }))).toBe(true)})- it('falls back when any series targets the right y-axis', () => {- const yData = [ySeries('a', [1], { display: { yAxisPosition: 'right' } })]- expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(false)+ it('renders right y-axis series natively rather than falling back', () => {+ const yData = [ySeries('a', [1]), ySeries('b', [2], { display: { yAxisPosition: 'right' } })]+ expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(true)})})@@ -360,6 +360,15 @@ describe('sqlLineGraphAdapter', () => {expect([bar.type, line.type, area.type]).toEqual(['bar', 'line', 'area'])})+ it.each<[string, AxisSeries<number | null>['settings'], string | undefined]>([+ ['right when the series targets the right axis', { display: { yAxisPosition: 'right' } }, 'right'],+ ['unset when the series targets the left axis', { display: { yAxisPosition: 'left' } }, undefined],+ ['unset when no axis is specified', {}, undefined],+ ])('assigns yAxisId %s', (_name, settings, expected) => {+ const [series] = buildSeries([ySeries('a', [1], settings)], ChartDisplayType.ActionsLineGraph)+ expect(series.yAxisId).toBe(expected)+ })+it('threads each series settings through meta for the tooltip', () => {const usd: AxisSeries<number | null>['settings'] = { formatting: { prefix: '$' } }const [withSettings, plain] = buildSeries(@@ -500,6 +509,25 @@ describe('sqlLineGraphAdapter', () => {expect(config.yAxis).toMatchObject({ scale: 'linear', showGrid: true })})+ it('keeps a single-object yAxis when no series targets the right axis', () => {+ const ySeriesData = [ySeries('a', [1, 2]), ySeries('b', [3, 4])]+ const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC', ySeriesData })+ expect(Array.isArray(config.yAxis)).toBe(false)+ })++ it('emits a per-axis array honoring each column settings when a series targets the right axis', () => {+ const ySeriesData = [ySeries('a', [1, 2]), ySeries('b', [3, 4], { display: { yAxisPosition: 'right' } })]+ const chartSettings: ChartSettings = {+ leftYAxisSettings: { label: 'Left', scale: 'logarithmic' },+ rightYAxisSettings: { label: 'Right', showGridLines: false },+ }+ const config = buildLineChartConfig({ xData: dateXData, chartSettings, timezone: 'UTC', ySeriesData })+ expect(config.yAxis).toEqual([+ { id: 'left', position: 'left', label: 'Left', scale: 'log', showGrid: true, hide: false },+ { id: 'right', position: 'right', label: 'Right', scale: 'linear', showGrid: false, hide: false },+ ])+ })+it.each([['shows', true, true],['hides', false, false],@@ -605,5 +633,18 @@ describe('sqlLineGraphAdapter', () => {})expect('trendLines' in config).toBe(false)})++ it('honors leftYAxisSettings for the single y-axis', () => {+ const chartSettings: ChartSettings = {+ leftYAxisSettings: { label: 'Combo Left', scale: 'logarithmic', showGridLines: false },+ }+ const config = buildComboChartConfig({+ xData: dateXData,+ chartSettings,+ timezone: 'UTC',+ visualizationType: ChartDisplayType.ActionsBar,+ })+ expect(config.yAxis).toEqual({ label: 'Combo Left', scale: 'log', showGrid: false, hide: false })+ })})})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.tsindex 7d13657216a5..133a880cafe7 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts@@ -14,7 +14,7 @@ import {createXAxisTickCallback,} from '@posthog/quill-charts'-import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'+import { ChartSettings, GoalLine, YAxisSettings } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'@@ -97,9 +97,9 @@ export function buildTrendLineConfigs(ySeriesData: SqlLineYSeries[] | null | und}/**- * Plain line/area charts — including goal lines and trend lines — render here. Series that mix a bar- * with a line/area route to {@link canRenderSqlComboGraph}; right y-axis series aren't ported yet, so- * those fall back to the legacy chart.js path.+ * Plain line/area charts — including goal lines, trend lines, and right y-axis series — render here.+ * Series that mix a bar with a line/area route to {@link canRenderSqlComboGraph}; other mixes fall+ * back to the legacy chart.js path.*/export function canRenderSqlLineGraph(props: LineGraphProps): boolean {const { visualizationType, yData } = props@@ -113,11 +113,6 @@ export function canRenderSqlLineGraph(props: LineGraphProps): boolean {if (yData?.some((series) => series.settings?.display?.displayType === 'bar')) {return false}- // quill applies a single tick formatter/scale to both gutters, so a right axis can't honor its- // own settings yet — fall back to legacy rather than silently dropping those prefs.- if (yData?.some((series) => series.settings?.display?.yAxisPosition === 'right')) {- return false- }return true}@@ -237,6 +232,7 @@ export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDistype,// Only pin an explicit color; otherwise let quill assign palette colors by index....(color ? { color } : {}),+ ...(settings?.display?.yAxisPosition === 'right' ? { yAxisId: 'right' } : {}),// Area fill, but never on a bar — a bar-override on an area-graph chart resolves to// `type: 'bar'` yet `isAreaSeries` is still true for the whole area graph....(type !== 'bar' && isAreaSeries(visualizationType, settings)@@ -291,12 +287,12 @@ function buildXAxisConfig(xData: AxisSeries<string>, chartSettings: ChartSetting}function buildYAxisConfig(- chartSettings: ChartSettings,- { forceLinear = false }: { forceLinear?: boolean } = {}+ yAxis: YAxisSettings | undefined,+ { forceLinear = false, id, position }: { forceLinear?: boolean; id?: string; position?: 'left' | 'right' } = {}): YAxisConfig {- const yAxis = chartSettings.leftYAxisSettings-return {+ ...(id ? { id } : {}),+ ...(position ? { position } : {}),label: yAxis?.label,scale: !forceLinear && yAxis?.scale === 'logarithmic' ? 'log' : 'linear',showGrid: yAxis?.showGridLines ?? true,@@ -315,9 +311,19 @@ export function buildLineChartConfig({goalLines,ySeriesData,}: BuildConfigArgs): TimeSeriesLineChartConfig {+ const hasRightAxisSeries =+ ySeriesData?.some((series) => series.settings?.display?.yAxisPosition === 'right') ?? false+return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),- yAxis: buildYAxisConfig(chartSettings),+ // Emit a per-axis array only when a series actually targets the right axis — otherwise keep+ // the single-object form so single-axis charts render unchanged.+ yAxis: hasRightAxisSeries+ ? [+ buildYAxisConfig(chartSettings.leftYAxisSettings, { id: 'left', position: 'left' }),+ buildYAxisConfig(chartSettings.rightYAxisSettings, { id: 'right', position: 'right' }),+ ]+ : buildYAxisConfig(chartSettings.leftYAxisSettings),goalLines: schemaGoalLinesToConfigs(goalLines),trendLines: buildTrendLineConfigs(ySeriesData),legend: buildLegendConfig(chartSettings),@@ -336,7 +342,7 @@ export function buildBarChartConfig({return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),- yAxis: buildYAxisConfig(chartSettings, { forceLinear: barLayout === 'percent' }),+ yAxis: buildYAxisConfig(chartSettings.leftYAxisSettings, { forceLinear: barLayout === 'percent' }),goalLines: schemaGoalLinesToConfigs(goalLines),barLayout,legend: buildLegendConfig(chartSettings),@@ -354,7 +360,7 @@ export function buildComboChartConfig({}: BuildBarConfigArgs): TimeSeriesComboChartConfig {return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),- yAxis: buildYAxisConfig(chartSettings),+ yAxis: buildYAxisConfig(chartSettings.leftYAxisSettings),goalLines: schemaGoalLinesToConfigs(goalLines),barLayout: comboBarLayoutForDisplay(visualizationType),legend: buildLegendConfig(chartSettings),diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsxindex ad2ac2272445..85ee54709e6a 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx@@ -79,7 +79,7 @@ function LineChartInner<Meta = unknown>({showGrid = false,showAxisLines = false,valueDomain,- yAxes: yAxisRenderConfigs,+ yAxes,} = config ?? {}const { visibleSeries, legendProps } = useChartLegend(series, theme, config?.legend)@@ -128,12 +128,12 @@ function LineChartInner<Meta = unknown>({scaleType: yScaleType,percentStack: percentStackView,valueDomain,- axes: yAxisRenderConfigs,+ axes: yAxes,})const yTickCount = yTickCountForHeight(dimensions.plotHeight)- const yAxes = d3Scales.yAxes ? toYAxisScales(d3Scales.yAxes, yTickCount) : undefined+ const yAxisScales = d3Scales.yAxes ? toYAxisScales(d3Scales.yAxes, yTickCount) : undefined// Stash raw d3 scales in the private slot so drawStatic can read them without// a side-channel ref — every render gets a self-contained ChartScales object,@@ -147,11 +147,11 @@ function LineChartInner<Meta = unknown>({x: (label: string) => d3Scales.x(label),y: (value: number) => d3Scales.y(value),yTicks: () => d3Scales.y.ticks?.(yTickCount) ?? [],- yAxes,+ yAxes: yAxisScales,_private: lineChartPrivate,}},- [yScaleType, percentStackView, stackedData, valueDomain, yAxisRenderConfigs]+ [yScaleType, percentStackView, stackedData, valueDomain, yAxes])const drawStatic = useCallback(diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsxindex d0959484d2fd..821c420d52cb 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx@@ -2,7 +2,6 @@ import React, { useMemo } from 'react'import { ChartLegend } from '../../components/Legend/ChartLegend'import { useChartLegend } from '../../components/Legend/useChartLegend'-import { DEFAULT_Y_AXIS_ID } from '../../core/types'import type {ChartLegendConfig,ChartTheme,@@ -12,13 +11,15 @@ import type {Series,TooltipConfig,TooltipContext,- YAxisRenderConfig,+ YAxis,} from '../../core/types'import { ReferenceLines } from '../../overlays/ReferenceLine'import { ValueLabels } from '../../overlays/ValueLabels'import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'import {- resolveYTickFormatter,+ buildYAxes,+ normalizeYAxisList,+ primaryYAxisConfig,useXTickFormatter,useYTickFormatter,type XAxisConfig,@@ -39,26 +40,6 @@ import {export type { ConfidenceIntervalConfig, MovingAverageConfig, TrendLineConfig }-interface NormalizedYAxis {- id: string- position: 'left' | 'right'- config: YAxisConfig-}--/** Normalize the `yAxis` config into a per-axis list. A single object (or omitted) is the primary- * left axis; an array assigns ids/positions, defaulting the first entry to the primary left axis- * and subsequent entries to the right. */-function normalizeYAxisList(yAxis: YAxisConfig | YAxisConfig[] | undefined): NormalizedYAxis[] {- if (!Array.isArray(yAxis)) {- return yAxis ? [{ id: DEFAULT_Y_AXIS_ID, position: 'left', config: yAxis }] : []- }- return yAxis.map((config, index) => ({- id: config.id ?? (index === 0 ? DEFAULT_Y_AXIS_ID : `axis-${index}`),- position: config.position ?? (index === 0 ? 'left' : 'right'),- config,- }))-}-export interface TimeSeriesLineChartConfig {xAxis?: XAxisConfig/** Single object = one y-axis (today's behavior). Array = one entry per axis for dual y-axis@@ -130,24 +111,13 @@ export function TimeSeriesLineChart<Meta = unknown>({const axisList = useMemo(() => normalizeYAxisList(yAxis), [yAxis])// Scalar y-config describes the primary (left) axis — drives single-axis rendering, the default// value-label formatter, and the left gutter when a right-axis series is present.- const primaryYAxis = useMemo<YAxisConfig | undefined>(- () => (axisList.find((a) => a.id === DEFAULT_Y_AXIS_ID) ?? axisList[0])?.config,- [axisList]+ const primaryYAxis = useMemo<YAxisConfig | undefined>(() => primaryYAxisConfig(axisList), [axisList])+ // Per-axis configs only when the caller passed an array — a single object keeps the existing+ // single-axis path untouched (no `yAxes` on the LineChart config).+ const yAxes = useMemo<YAxis[] | undefined>(+ () => (Array.isArray(yAxis) ? buildYAxes(axisList) : undefined),+ [yAxis, axisList])- // Per-axis render configs only when the caller passed an array — a single object keeps the- // existing single-axis path untouched (no `yAxes` on the LineChart config).- const yAxesRenderConfig = useMemo<YAxisRenderConfig[] | undefined>(() => {- if (!Array.isArray(yAxis)) {- return undefined- }- return axisList.map(({ id, position, config }) => ({- id,- position,- scaleType: config.scale,- tickFormatter: resolveYTickFormatter(config),- label: config.label,- }))- }, [yAxis, axisList])const xTickFormatter = useXTickFormatter(xAxis, labels)const yTickFormatter = useYTickFormatter(primaryYAxis)@@ -189,7 +159,7 @@ export function TimeSeriesLineChart<Meta = unknown>({showCrosshair,tooltip: tooltipConfig,valueDomain,- yAxes: yAxesRenderConfig,+ yAxes,}return (diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsxindex 2e7aaa346b32..c65664088256 100644--- a/packages/quill/packages/charts/src/core/Chart.tsx+++ b/packages/quill/packages/charts/src/core/Chart.tsx@@ -16,6 +16,7 @@ import { useChartMargins } from './hooks/useChartMargins'import { useLatest } from './hooks/useLatest'import { useResolvedYFormatter } from './hooks/useResolvedYFormatters'import { useStableResolveValue } from './hooks/useStableResolveValue'+import { useYAxisMaps } from './hooks/useYAxisMaps'import type {ChartConfig,ChartDrawArgs,@@ -128,32 +129,11 @@ export function Chart<Meta = unknown>({// 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 yAxisFormatters = useMemo<Record<string, (value: number) => string> | undefined>(() => {- if (!yAxes) {- return undefined- }- const map: Record<string, (value: number) => string> = {}- for (const axis of yAxes) {- if (axis.tickFormatter) {- map[axis.id] = axis.tickFormatter- }- }- return Object.keys(map).length > 0 ? map : undefined- }, [yAxes])- const yAxisPositions = useMemo<Record<string, 'left' | 'right'> | undefined>(() => {- if (!yAxes) {- return undefined- }- const map: Record<string, 'left' | 'right'> = {}- for (const axis of yAxes) {- map[axis.id] = axis.position- }- return map- }, [yAxes])- const yAxisLabelRight = useMemo<string | undefined>(- () => yAxes?.find((axis) => axis.position === 'right')?.label,- [yAxes]- )+ const {+ formatters: yAxisFormatters,+ positions: yAxisPositions,+ labelRight: yAxisLabelRight,+ } = useYAxisMaps(yAxes)const hoverAnimationMs = resolveHoverAnimationMs(animateHover)const interactionAxis: 'x' | 'y' = axisOrientation === 'horizontal' ? 'y' : 'x'const {diff --git a/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.ts b/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.tsnew file mode 100644index 000000000000..fd8d0b40eece--- /dev/null+++ b/packages/quill/packages/charts/src/core/hooks/useYAxisMaps.ts@@ -0,0 +1,35 @@+import { useMemo } from 'react'++import type { YAxis } from '../types'++export interface YAxisMaps {+ /** Per-axis tick formatters keyed by axis id — only axes that define one. Absent when no axis does. */+ 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+}++/** 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 {+ return useMemo(() => {+ if (!yAxes) {+ return {}+ }+ const formatters: Record<string, (value: number) => string> = {}+ const positions: Record<string, 'left' | 'right'> = {}+ for (const axis of yAxes) {+ if (axis.tickFormatter) {+ formatters[axis.id] = axis.tickFormatter+ }+ positions[axis.id] = axis.position+ }+ return {+ formatters: Object.keys(formatters).length > 0 ? formatters : undefined,+ positions,+ labelRight: yAxes.find((axis) => axis.position === 'right')?.label,+ }+ }, [yAxes])+}diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 37aaaaf73b77..1cd657033c27 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -238,13 +238,13 @@ export interface ChartConfig {* {@link Series.yAxisId}. When set, each axis formats ticks, labels, and scales independently;* the scalar `yScaleType`/`yTickFormatter`/`yAxisLabel` then describe the primary (left) axis.* Omit for single-axis charts. */- yAxes?: YAxisRenderConfig[]+ yAxes?: YAxis[]}-/** Per-axis render config for a multi-axis (dual y-axis) chart. One entry per distinct+/** A resolved y-axis for a multi-axis (dual y-axis) chart. One entry per distinct* {@link Series.yAxisId}; series resolve to their axis by id. Drives each axis's scale type,* tick formatting, side, and label independently. */-export interface YAxisRenderConfig {+export interface YAxis {/** Axis id — matches {@link Series.yAxisId}. The default-axis id is {@link DEFAULT_Y_AXIS_ID}. */id: string/** Which side this axis renders on. */diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex b945638db32a..f5f9e4e5d0a3 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -103,7 +103,7 @@ export type {TooltipConfig,TooltipContext,ValueDomain,- YAxisRenderConfig,+ YAxis,YAxisScale,} from './core/types'export { DEFAULT_Y_AXIS_ID } from './core/types'diff --git a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts b/packages/quill/packages/charts/src/utils/use-axis-formatters.tsindex 241be30a888c..15783252abd9 100644--- a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts+++ b/packages/quill/packages/charts/src/utils/use-axis-formatters.ts@@ -1,5 +1,6 @@import { useMemo } from 'react'+import { DEFAULT_Y_AXIS_ID, type YAxis } from '../core/types'import { createXAxisTickCallback, type TimeInterval } from './dates'import { buildYTickFormatter, type YFormatterConfig } from './y-formatters'@@ -82,6 +83,44 @@ export function resolveYTickFormatter(yAxis: YAxisConfig | undefined): ((value:})}+interface NormalizedYAxis {+ id: string+ position: 'left' | 'right'+ config: YAxisConfig+}++/** Normalize the user `yAxis` config into a per-axis list. A single object (or omitted) is the+ * primary left axis; an array assigns ids/positions, defaulting the first entry to the primary+ * left axis and subsequent entries to the right. */+export function normalizeYAxisList(yAxis: YAxisConfig | YAxisConfig[] | undefined): NormalizedYAxis[] {+ if (!Array.isArray(yAxis)) {+ return yAxis ? [{ id: DEFAULT_Y_AXIS_ID, position: 'left', config: yAxis }] : []+ }+ return yAxis.map((config, index) => ({+ id: config.id ?? (index === 0 ? DEFAULT_Y_AXIS_ID : `axis-${index}`),+ position: config.position ?? (index === 0 ? 'left' : 'right'),+ config,+ }))+}++/** Resolve a normalized axis list into the {@link YAxis}es the base chart consumes —+ * each axis's id, side, scale, label, and resolved tick formatter. */+export function buildYAxes(axisList: NormalizedYAxis[]): YAxis[] {+ return axisList.map(({ id, position, config }) => ({+ id,+ position,+ scaleType: config.scale,+ tickFormatter: resolveYTickFormatter(config),+ label: config.label,+ }))+}++/** Resolve the primary (left) axis from a normalized list — the entry whose id is the default+ * axis id, falling back to the first entry. Drives the base chart's scalar y-config. */+export function primaryYAxisConfig(axisList: NormalizedYAxis[]): YAxisConfig | undefined {+ return (axisList.find((a) => a.id === DEFAULT_Y_AXIS_ID) ?? axisList[0])?.config+}+export function useYTickFormatter(yAxis: YAxisConfig | undefined): ((value: number) => string) | undefined {// Read the formatter-relevant fields here (not the whole object) so the memo stays stable across// unrelated config-identity changes — the same field set forms the dependency array.