: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(insights): add a y-axis range option to trends charts (#81106)
Daniel Parker095986852dea
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex daa2126f497b..e68869f4a596 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1072,6 +1072,10 @@ snapshots:hash: v1.k794b7964.43f6eb1474d256161abbb5a6a9fb4fcdc9106b3a2929c8b3a16b6ff76ba1fad9.FBPe_INNlLA1E-419fyRDywJsBSgXBgInE2a1Jg17vAcomponents-hogcharts-timeserieslinechart--y-axis-formats--light:hash: v1.k794b7964.f069019d468fdbe30e6dadec5747c4103ef9d696404463c433c5c6d333f786b3.5--sMNDuGxAUTA_gdKqQbE8KKnkjsOGubKKrg59-0s0+ components-hogcharts-timeserieslinechart--y-axis-range--dark:+ hash: v1.k794b7964.74fa4998f18f347555b68b7d5b70cbcbd58d362d405c48cb4efd4eb14df2c0d6.aoLPhLRwS1e43mJx-spfRqtspjEVrIGfwqWby9cY18Y+ components-hogcharts-timeserieslinechart--y-axis-range--light:+ hash: v1.k794b7964.625e033c4e33d90b83a2226ac1a7cb4a21001ad1ea9e0f1bb1a92b65c9b82fc9.PN7p1HkN-58lB8tal-t-_Xnuogrm20kdQ11-S_5L8gIcomponents-hogcharts-trendlineoverlay--single-series-with-trend--dark:hash: v1.k794b7964.516a16ffe07ab9611351c87621a551c2be271b06e36362c9451dea8dc4b5eacb.5Sxpr5u-k77d0oS64FGemW7JP-NlFmNqVrK6_frmZNkcomponents-hogcharts-trendlineoverlay--single-series-with-trend--light:@@ -6433,9 +6437,9 @@ snapshots:scenes-app-inbox-scene--empty-with-many-scouts--light:hash: v1.k794b7964.4757fdc3e6603cc7752cffdf45421aa24d8551754e9b5cca04569ed5c9577a26.k0mDZb6DY2eTMFjNrG2mi_0Dbhcrho9A4MhjjH5KlCMscenes-app-inbox-scene--inbox--dark:- hash: v1.k794b7964.7ade0c95519de555691da00b03aaa9aeea1ba0c32762354222d23676099ea0da.OmzLebXW_1EJ-lRFDeh7flQ6cl3OqskJfVarjDu4FQc+ hash: v1.k794b7964.6938f54b10a00b66cd90158043512d6b056ac3bf97e291fa5961529af56ba084.noXScllvtHLNl8e7c7bKckMTjf-O9lC0OuvKdUKVT7oscenes-app-inbox-scene--inbox--light:- hash: v1.k794b7964.cd4a9d438b8342df350fcc8de14e27707c460e73d08772f90fec51dcb346858d.pXZHp6MatJwXk0M_5UL2njnpvO02KcZWmTtPqoeaj6E+ hash: v1.k794b7964.21ae4235f9bc3c8f39fc33259edc39f53e06baaeb37f679f3badd771b986b86a.AoPLxHhT6028ylYpVRlXQUVgqm6ckEBiLWWwCovU7DQscenes-app-inbox-scene--installing-self-driving--dark:hash: v1.k794b7964.d2c648fd6ea8079c6746f4b5e979cac53dbd928dd06990c3bac2031eeaba12be.rCs94UBn0krUWBSp28BM_f7Jo4Smc85JTXR_iWzDjoYscenes-app-inbox-scene--installing-self-driving--light:diff --git a/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsxindex 3de5a75b8039..0569cb104b40 100644--- a/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx+++ b/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx@@ -34,6 +34,7 @@ import { ShowTrendLinesFilter } from 'scenes/insights/EditorFilters/ShowTrendLinimport { SliceNamesFilter } from 'scenes/insights/EditorFilters/SliceNamesFilter'import { StackBreakdownFilter } from 'scenes/insights/EditorFilters/StackBreakdownFilter'import { ValueOnSeriesFilter } from 'scenes/insights/EditorFilters/ValueOnSeriesFilter'+import { YAxisRangeFilter } from 'scenes/insights/EditorFilters/YAxisRangeFilter'import { RetentionCohortLabelStartIndexPicker } from 'scenes/insights/filters/RetentionCohortLabelStartIndexPicker'import { RetentionDashboardDisplayPicker } from 'scenes/insights/filters/RetentionDashboardDisplayPicker'import { insightLogic } from 'scenes/insights/insightLogic'@@ -45,30 +46,7 @@ import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'import { isTrendsQuery } from '~/queries/utils'import { ChartDisplayType } from '~/types'-export const LINE_DISPLAYS = [- ChartDisplayType.ActionsLineGraph,- ChartDisplayType.ActionsLineGraphCumulative,- ChartDisplayType.ActionsAreaGraph,-] as const-export const BAR_DISPLAYS = [- ChartDisplayType.ActionsBar,- ChartDisplayType.ActionsUnstackedBar,- ChartDisplayType.ActionsBarValue,-] as const--export function displayMatches(- display: ChartDisplayType | null | undefined,- displays: readonly ChartDisplayType[]-): boolean {- return !!display && displays.includes(display)-}--export function isDefaultTrendsLineDisplay(- display: ChartDisplayType | null | undefined,- querySource: Parameters<typeof isTrendsQuery>[0]-): boolean {- return !display && isTrendsQuery(querySource)-}+import { displayMatches, isDefaultTrendsLineDisplay, LINE_DISPLAYS } from './displayTypes'function useLineGraphState(): { isLineGraph: boolean; isLinearScale: boolean } {const { insightProps } = useValues(insightLogic)@@ -259,6 +237,7 @@ export const DisplayOptions = {ResultCustomizationBy: { label: () => <ResultCustomizationByPicker /> },Unit: { label: () => <UnitPicker /> },Scale: { label: () => <ScalePicker /> },+ YAxisRange: { label: () => <YAxisRangeFilter /> },LineStyle: { label: () => <LineStylePicker /> },ConfidenceInterval: { label: () => <ConfidenceInterval /> },ConfidenceLevel: { label: () => <ConfidenceLevelInput /> },diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsxindex 11c594305bd0..c8ccfe789837 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx@@ -129,6 +129,7 @@ describe('InsightDisplayConfig', () => {'Color customization by','Y-axis unit','Y-axis scale',+ 'Y-axis range','Line style','Statistical analysis','Axis labels',@@ -167,6 +168,7 @@ describe('InsightDisplayConfig', () => {'Display','Y-axis unit','Y-axis scale',+ 'Y-axis range','Line style','Statistical analysis','Axis labels',diff --git a/frontend/src/queries/nodes/InsightViz/displayTypes.ts b/frontend/src/queries/nodes/InsightViz/displayTypes.tsnew file mode 100644index 000000000000..3d4f49f52c80--- /dev/null+++ b/frontend/src/queries/nodes/InsightViz/displayTypes.ts@@ -0,0 +1,29 @@+import { isTrendsQuery } from '~/queries/utils'+import { ChartDisplayType } from '~/types'++// Their own module so an option component can read these groupings without importing the+// DisplayOptions registry that renders it.+export const LINE_DISPLAYS = [+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsLineGraphCumulative,+ ChartDisplayType.ActionsAreaGraph,+] as const+export const BAR_DISPLAYS = [+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsBarValue,+] as const++export function displayMatches(+ display: ChartDisplayType | null | undefined,+ displays: readonly ChartDisplayType[]+): boolean {+ return !!display && displays.includes(display)+}++export function isDefaultTrendsLineDisplay(+ display: ChartDisplayType | null | undefined,+ querySource: Parameters<typeof isTrendsQuery>[0]+): boolean {+ return !display && isTrendsQuery(querySource)+}diff --git a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsxindex cb8451fdb3fb..a0bf6e8e260c 100644--- a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx+++ b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx@@ -14,14 +14,8 @@ import type { TrendsFilter } from '~/queries/schema/schema-general'import { hasBreakdownFilter } from '~/queries/utils'import { ChartDisplayType } from '~/types'-import {- BAR_DISPLAYS,- displayMatches,- DisplayOptions,- isDefaultTrendsLineDisplay,- LINE_DISPLAYS,- SectionHeader,-} from './DisplayOptions'+import { DisplayOptions, SectionHeader } from './DisplayOptions'+import { BAR_DISPLAYS, displayMatches, isDefaultTrendsLineDisplay, LINE_DISPLAYS } from './displayTypes'// The "Options" menu in the insight editor's display config bar. `count` is the number of non-default// active options, badged on the Options button.@@ -98,6 +92,9 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numbconst showDisplaySection =(isTrends && !isCalendarHeatmap) || isRetention || isTrendsFunnel || isStickiness || isLifecycleconst showYAxisScale = !hideContinuousChartOptions && isTrends && !isCalendarHeatmap+ // Bars encode magnitude as length from zero, so a bounded baseline misreads them: 10 vs 11+ // would draw as 1 vs 2.+ const showYAxisRangeConfig = showYAxisScale && isLineDisplay// Only the quill line charts (trends/stickiness line and area, retention and funnel-trends// graphs) draw curves, so they're the only ones with curvature to straighten. Retention and// funnel trends default to their line graph when display is unset.@@ -206,6 +203,11 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numbitems.push({ title: 'Y-axis scale', items: [DisplayOptions.Scale] })}+ // Kept under the scale section, so the log scale that disables the range sits one row above.+ if (showYAxisRangeConfig) {+ items.push({ title: 'Y-axis range', items: [DisplayOptions.YAxisRange] })+ }+if (showLineStyleConfig) {items.push({ title: 'Line style', items: [DisplayOptions.LineStyle] })}@@ -256,6 +258,9 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb: 0) +((hasLegend || showFunnelLegendConfig) && showLegend ? 1 : 0) +(!!yAxisScaleType && yAxisScaleType !== 'linear' ? 1 : 0) ++ (showYAxisRangeConfig && trendsFilter?.yAxisStartAtZero === false ? 1 : 0) ++ (showYAxisRangeConfig && typeof trendsFilter?.yAxisMin === 'number' ? 1 : 0) ++ (showYAxisRangeConfig && typeof trendsFilter?.yAxisMax === 'number' ? 1 : 0) +(showLineStyleConfig && (insightFilter as TrendsFilter | undefined)?.chartStyle?.curve === 'linear' ? 1 : 0) +(showAxisLabelsConfig && normalizeAxisLabel(trendsFilter?.xAxisLabel) ? 1 : 0) +(showAxisLabelsConfig && normalizeAxisLabel(trendsFilter?.yAxisLabel) ? 1 : 0) +diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 6e2571d25af2..5a99233f6e0b 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -52226,9 +52226,22 @@"description": "Custom label rendered alongside the Y axis.","type": "string"},+ "yAxisMax": {+ "description": "Pins the top of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, and when `yAxisMin` is not below it.",+ "type": "number"+ },+ "yAxisMin": {+ "description": "Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`.",+ "type": "number"+ },"yAxisScaleType": {"enum": ["log10", "linear"],"type": "string"+ },+ "yAxisStartAtZero": {+ "default": true,+ "description": "Y-axis baseline. When false the axis floats to the data range instead of starting at zero. Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while showing percentages.",+ "type": "boolean"}},"type": "object"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex ebab652d66e2..4b5c97eb08be 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1588,6 +1588,17 @@ export type TrendsFilter = {* @default false */stackBreakdownValues?: booleanyAxisScaleType?: TrendsFilterLegacy['y_axis_scale_type']+ /** Y-axis baseline. When false the axis floats to the data range instead of starting at zero.+ * Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while+ * showing percentages.+ * @default true */+ yAxisStartAtZero?: boolean+ /** Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as+ * `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`. */+ yAxisMin?: number+ /** Pins the top of the y-axis; unset means automatic. Ignored in the same cases as+ * `yAxisStartAtZero`, and when `yAxisMin` is not below it. */+ yAxisMax?: number/** @default false */showMultipleYAxes?: TrendsFilterLegacy['show_multiple_y_axes']hiddenLegendIndexes?: integer[]@@ -1669,6 +1680,9 @@ export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>(['showPercentStackView','stackBreakdownValues','yAxisScaleType',+ 'yAxisStartAtZero',+ 'yAxisMin',+ 'yAxisMax','hiddenLegendIndexes','excludeBoxPlotOutliers','hideWeekends',diff --git a/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsx b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsxnew file mode 100644index 000000000000..2a805c7c66a6--- /dev/null+++ b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsx@@ -0,0 +1,109 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'+import { BindLogic, Provider } from 'kea'++import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { useMocks } from '~/mocks/jest'+import { NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { BaseMathType, ChartDisplayType, InsightShortId } from '~/types'++import { YAxisRangeFilter } from './YAxisRangeFilter'++const insightProps = { dashboardItemId: '123' as InsightShortId }++function makeQuery(trendsFilter: TrendsFilter, display = ChartDisplayType.ActionsLineGraph): TrendsQuery {+ return {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],+ trendsFilter: { display, ...trendsFilter },+ }+}++describe('YAxisRangeFilter', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/insights/trend': [],+ '/api/environments/:team_id/insights/': { results: [{}] },+ },+ })+ initKeaTests()+ featureFlagLogic().mount()+ })++ afterEach(() => cleanup())++ function setup(trendsFilter: TrendsFilter, display?: ChartDisplayType): HTMLElement {+ insightLogic(insightProps).mount()+ insightDataLogic(insightProps).mount()+ const vizDataLogic = insightVizDataLogic(insightProps)+ vizDataLogic.mount()+ vizDataLogic.actions.updateQuerySource(makeQuery(trendsFilter, display))++ return render(+ <Provider>+ <BindLogic logic={insightLogic} props={insightProps}>+ <YAxisRangeFilter />+ </BindLogic>+ </Provider>+ ).container+ }++ const control = (container: HTMLElement, attr: string): HTMLElement =>+ container.querySelector<HTMLElement>(`[data-attr="${attr}"]`)!++ const committedFilter = (): TrendsFilter =>+ (insightVizDataLogic(insightProps).values.querySource as TrendsQuery).trendsFilter ?? {}++ // "Begin at zero" and the minimum both set the axis floor, so exactly one is live at a time.+ // Wire the reason to the wrong control and the toggle is unusable, since it is on by default.+ // Every row carries a display, including `undefined`: jest passes a `done` callback in place of+ // an argument a shorter row doesn't supply, and the case then times out waiting on it.+ it.each<[string, TrendsFilter, { toggle: boolean; min: boolean; max: boolean }, ChartDisplayType | undefined]>([+ ['begin at zero is on by default', {}, { toggle: false, min: true, max: false }, undefined],+ ['begin at zero is off', { yAxisStartAtZero: false }, { toggle: false, min: false, max: false }, undefined],+ ['a logarithmic scale', { yAxisScaleType: 'log10' }, { toggle: true, min: true, max: true }, undefined],+ [+ 'percentages are shown',+ { showPercentStackView: true },+ { toggle: true, min: true, max: true },+ // Percent stacking is offered on bar, area and pie only, so an area graph is the one+ // display where it and the range controls are both reachable.+ ChartDisplayType.ActionsAreaGraph,+ ],+ ])('disables the right controls when %s', (_name, trendsFilter, expected, display) => {+ const container = setup(trendsFilter, display)+ expect(control(container, 'trends-y-axis-start-at-zero')).toHaveProperty('disabled', expected.toggle)+ expect(control(container, 'trends-y-axis-min-input')).toHaveProperty('disabled', expected.min)+ expect(control(container, 'trends-y-axis-max-input')).toHaveProperty('disabled', expected.max)+ })++ // An emptied number input reports NaN. Committing that leaves a bound the chart ignores but the+ // Options badge still counts, so the user sees an option they cannot clear, and it reaches the+ // saved insight as null. `toBeUndefined` separates that from the bound simply not clearing.+ it('commits undefined rather than NaN when a bound is cleared', async () => {+ const container = setup({ yAxisStartAtZero: false, yAxisMin: 40 })+ const input = control(container, 'trends-y-axis-min-input')++ fireEvent.change(input, { target: { value: '' } })+ fireEvent.blur(input)++ await waitFor(() => expect(committedFilter().yAxisMin).toBeUndefined())+ })++ // The chart falls back to its automatic range on an inverted pair, so the message explains a+ // real effect. While the minimum is disabled there is no such effect to explain.+ it.each<[string, TrendsFilter, boolean]>([+ ['the minimum applies', { yAxisStartAtZero: false, yAxisMin: 80, yAxisMax: 10 }, true],+ ['begin at zero holds the minimum back', { yAxisMin: 80, yAxisMax: 10 }, false],+ ])('shows the inverted-range message only while %s', (_name, trendsFilter, shown) => {+ const container = setup(trendsFilter)+ expect(container.textContent?.includes('Maximum must be greater than minimum')).toBe(shown)+ })+})diff --git a/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsx b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsxnew file mode 100644index 000000000000..e7d6327bace6--- /dev/null+++ b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsx@@ -0,0 +1,99 @@+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { LemonInput, LemonLabel, LemonSwitch } from '@posthog/lemon-ui'++import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { insightLogic } from '../insightLogic'++export function YAxisRangeFilter(): JSX.Element {+ const { insightProps } = useValues(insightLogic)+ const { trendsFilter, yAxisScaleType, showPercentStackView } = useValues(insightVizDataLogic(insightProps))+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))++ const [minDraft, setMinDraft] = useState(trendsFilter?.yAxisMin)+ const [maxDraft, setMaxDraft] = useState(trendsFilter?.yAxisMax)++ useEffect(() => {+ setMinDraft(trendsFilter?.yAxisMin)+ }, [trendsFilter?.yAxisMin])++ useEffect(() => {+ setMaxDraft(trendsFilter?.yAxisMax)+ }, [trendsFilter?.yAxisMax])++ const rangeDisabledReason =+ yAxisScaleType === 'log10'+ ? 'Not available on a logarithmic scale'+ : showPercentStackView+ ? 'Not available while showing percentages'+ : undefined+ // Disabled rather than cleared, so the typed value applies again when the toggle goes off.+ const beginsAtZero = trendsFilter?.yAxisStartAtZero !== false+ const minDisabledReason =+ rangeDisabledReason ?? (beginsAtZero ? 'Turn off "Begin at zero" to set a minimum' : undefined)++ // An inverted pair sends the chart back to its automatic range, which otherwise just looks like+ // the controls not responding. Nothing to warn about while the minimum is disabled.+ const invalidRange =+ !beginsAtZero &&+ typeof trendsFilter?.yAxisMin === 'number' &&+ typeof trendsFilter?.yAxisMax === 'number' &&+ trendsFilter.yAxisMin >= trendsFilter.yAxisMax++ // Commit on blur, not on change: a number input reads as empty mid-entry, so every keystroke+ // would clear the bound. An emptied input reports NaN, which must become `undefined` because+ // the chart ignores NaN while the Options badge still counts it, leaving no way to clear it.+ const asBound = (value: number | undefined): number | undefined =>+ typeof value === 'number' && isFinite(value) ? value : undefined+ const commitMin = (): void => updateInsightFilter({ yAxisMin: asBound(minDraft) })+ const commitMax = (): void => updateInsightFilter({ yAxisMax: asBound(maxDraft) })++ return (+ <div className="p-1 px-2 flex flex-col gap-2 w-64">+ <LemonSwitch+ className="flex-1 w-full"+ label="Begin at zero"+ tooltip="When off, the axis starts just below your lowest value instead of at zero, so small changes are easier to see."+ data-attr="trends-y-axis-start-at-zero"+ checked={beginsAtZero}+ disabledReason={rangeDisabledReason}+ onChange={(checked) => updateInsightFilter({ yAxisStartAtZero: checked ? undefined : false })}+ />+ <div className="flex flex-col gap-1">+ <LemonLabel>Minimum</LemonLabel>+ <LemonInput+ type="number"+ size="small"+ data-attr="trends-y-axis-min-input"+ value={minDraft}+ placeholder="Auto"+ disabledReason={minDisabledReason}+ onChange={setMinDraft}+ onBlur={commitMin}+ onPressEnter={commitMin}+ />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Maximum</LemonLabel>+ <LemonInput+ type="number"+ size="small"+ data-attr="trends-y-axis-max-input"+ value={maxDraft}+ placeholder="Auto"+ disabledReason={rangeDisabledReason}+ onChange={setMaxDraft}+ onBlur={commitMax}+ onPressEnter={commitMax}+ />+ </div>+ {invalidRange ? (+ <span className="text-xs text-danger">Maximum must be greater than minimum.</span>+ ) : (+ <span className="text-xs text-secondary">Leave blank for an automatic bound.</span>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.tsindex 786b4fc013d5..64701702bb35 100644--- a/frontend/src/scenes/insights/utils/queryUtils.ts+++ b/frontend/src/scenes/insights/utils/queryUtils.ts@@ -303,6 +303,9 @@ export const cleanInsightQuery = (query: InsightQueryNode, opts?: CompareQueryOpshowMean: undefined,meanRetentionCalculation: undefined,yAxisScaleType: undefined,+ yAxisStartAtZero: undefined,+ yAxisMin: undefined,+ yAxisMax: undefined,hiddenLegendIndexes: undefined,hiddenLegendBreakdowns: undefined,resultCustomizations: undefined,diff --git a/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsx b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsxindex 46b91c54d28e..ace3aab33574 100644--- a/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsx+++ b/frontend/src/scenes/surveys/components/question-visualizations/MultipleChoiceBarChart.tsx@@ -71,7 +71,7 @@ export function MultipleChoiceBarChart({barCornerRadius: 3,bars: {minBandSize: 32,- valueDomain: [0, 100],+ valueDomain: { min: 0, max: 100 },},tooltip: { placement: 'cursor' },}),diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex b8c6d638c1f4..b53fd2e93d02 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -98,10 +98,11 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.- `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' | 'percent'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.-- `TimeSeriesBarChart` also takes `config.valueDomain` (same `ValueDomain` semantics as `BarChartConfig.bars.valueDomain`): a fixed `[min, max]` skips `d3.nice()` and wins over the goal-line stretch — pin `[0, dataMax]` so the tallest bar reaches the plot top on an axis-less volume chart, where nice-rounded headroom is invisible waste; `{ include }` merges with the goal-line stretch (`mergeValueDomains` in `utils/goal-lines.ts`).+- `TimeSeriesBarChart` also takes `config.valueDomain` (same `ValueDomain` semantics as `BarChartConfig.bars.valueDomain`): setting both `min` and `max` skips `d3.nice()` and wins over the goal-line stretch — pin `{ min: 0, max: dataMax }` so the tallest bar reaches the plot top on an axis-less volume chart, where nice-rounded headroom is invisible waste; `include` merges with the goal-line stretch (`mergeValueDomains` in `utils/goal-lines.ts`).- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix`/`suffix`. Numeric and percentage ticks default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (say latency in seconds over 0–0.012) doesn't render every tick as `0.01`; `decimalPlaces` pins the precision instead.- Fixed x-axis tick rotation: set `xAxis.tickLabelRotation` on a time-series chart (`-45` tilts labels left). Values are clamped to `-90..90`; omit it to keep horizontal labels and existing collision behavior.- 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.+- y-axis min/max: `yAxis.min` / `yAxis.max` pin either end of the primary value axis on `TimeSeriesLineChart` (`config.valueDomain: { min, max }` on the lower-level `LineChart` — the same option that carries `include`, since a capped axis still has to stretch to reach an off-scale goal line; `mergeValueDomains` combines them field by field). How many ends are set decides the behavior: **both** pins the axis (skips `nice()`, discards `include`, overrides percent layout), **one** clamps that end and leaves the other automatic. A single clamp composes with auto-scaling — it runs after `include` folding, the zero-baseline clamp and `nice()`, so only the extreme label is the raw bound while interior ticks stay round — and is ignored under a percent layout, where the domain is already 0..1. On a log scale a non-positive bound is dropped. A non-finite bound counts as unset, so `{ min: 0, max: Math.max(...[]) }` floors at zero rather than collapsing. An inverted `min >= max` pair falls back to the automatic domain rather than swapping. Overlays positioned off the value scale hide themselves outside the bounded window rather than painting over the chrome: a goal line drops out, and so does the value label of a clipped point (a point sitting exactly on the bound keeps its label). Bar and combo charts deliberately ignore `min`/`max`, even though they take the same `yAxis` config: a bar encodes magnitude as length from zero, so a bounded baseline misreads it — 10 vs 11 would draw as 1 vs 2. Pin `valueDomain` there instead, which rescales the bars rather than truncating them.- 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. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). 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`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/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. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the raw x and y pixel spans (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. `ScatterChart` exposes it as its own `onAreaSelect`, inverting the pixel spans through its continuous scales — the label range is meaningless there, since it snaps to whichever points sit near the drag edges. Each edge is clamped to its axis first, so a drag that overshoots the plot (routine when brushing into a corner) reports the rectangle the user saw rather than an extrapolated one. Takes precedence over `onDateRangeZoom` when both are set.diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsxindex 781a42b57801..e86e16623800 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx@@ -78,7 +78,7 @@ export const WithBarTrackCeiling: Story = {barLayout: 'grouped',showGrid: true,barCornerRadius: 6,- bars: { track: true, valueDomain: [0, 100] },+ bars: { track: true, valueDomain: { min: 0, max: 100 } },}return (<Stage>@@ -104,7 +104,7 @@ export const StackedWithTrackCeiling: Story = {axisOrientation: 'horizontal',showGrid: true,barCornerRadius: 6,- bars: { valueDomain: [0, 100] },+ bars: { valueDomain: { min: 0, max: 100 } },}return (<Stage height={120}>diff --git a/packages/quill/packages/charts/src/charts/BarChart/utils/bars-under-cursor.test.ts b/packages/quill/packages/charts/src/charts/BarChart/utils/bars-under-cursor.test.tsindex 439f983827f8..7611a9661e41 100644--- a/packages/quill/packages/charts/src/charts/BarChart/utils/bars-under-cursor.test.ts+++ b/packages/quill/packages/charts/src/charts/BarChart/utils/bars-under-cursor.test.ts@@ -256,7 +256,7 @@ describe('cursorInInertTrackGap', () => {const stackedScales = createBarScales(stack, labels, dimensions, {barLayout: 'stacked',axisOrientation: 'horizontal',- valueDomain: [0, 100],+ valueDomain: { min: 0, max: 100 },})return cursorInInertTrackGap({series: stack,diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsxindex e4318d6d01b0..e0db03d418fd 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx@@ -256,7 +256,7 @@ function PinnedValueDomainCell({ title, pinned }: { title: string; pinned: booleconfig={{yAxis: { hide: true },minBarSize: 2,- valueDomain: pinned ? [0, 246] : undefined,+ valueDomain: pinned ? { min: 0, max: 246 } : undefined,}}/></Stage>@@ -271,7 +271,7 @@ export const PinnedValueDomain: Story = {// eslint-disable-next-line react/forbid-dom-props<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, auto)', gap: 24 }}><PinnedValueDomainCell title="default (niced headroom)" pinned={false} />- <PinnedValueDomainCell title="valueDomain: [0, dataMax]" pinned />+ <PinnedValueDomainCell title="valueDomain: { min: 0, max: dataMax }" pinned /></div>),}diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsxindex d7ad69047a02..c16d3147d19e 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx@@ -291,7 +291,7 @@ describe('TimeSeriesBarChart', () => {series={SPIKY_SERIES}labels={LABELS}theme={THEME}- config={{ valueDomain: [0, 246] }}+ config={{ valueDomain: { min: 0, max: 246 } }}/>).chartexpect(maxTick(pinned)).toBeLessThanOrEqual(246)@@ -303,7 +303,7 @@ describe('TimeSeriesBarChart', () => {series={SPIKY_SERIES}labels={LABELS}theme={THEME}- config={{ valueDomain: [0, 246], goalLines: [{ value: 1000, label: 'Target' }] }}+ config={{ valueDomain: { min: 0, max: 246 }, goalLines: [{ value: 1000, label: 'Target' }] }}/>)expect(maxTick(chart)).toBeLessThanOrEqual(246)diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsxindex 4990ceec4c03..96862859d665 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx@@ -235,6 +235,23 @@ export const StartAtZero: Story = {),}+/** `min` / `max` pin either end of the axis. Either may be omitted to keep the automatic bound, so+ * a lone `min` reads as "only show me above this". */+export const YAxisRange: Story = {+ render: () => (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, auto)', gap: 24 }}>+ <YFormatCell title="automatic" series={OFFSET_SERIES} config={{ suffix: ' ms' }} />+ <YFormatCell title="min: 800" series={OFFSET_SERIES} config={{ suffix: ' ms', min: 800 }} />+ <YFormatCell+ title="min: 800, max: 1000"+ series={OFFSET_SERIES}+ config={{ suffix: ' ms', min: 800, max: 1000 }}+ />+ </div>+ ),+}+const DERIVED_SERIES: Series[] = [{ key: 'visits', label: 'Visits', data: [20, 35, 28, 60, 45, 70, 52] },{ key: 'signups', label: 'Sign-ups', data: [4, 8, 6, 14, 11, 19, 13] },diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsxindex e16c5071b268..5107cacd7c34 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx@@ -186,6 +186,48 @@ describe('TimeSeriesLineChart', () => {// A log axis can't include 0 regardless; this just guards against a crash / NaN domain.expect(lowestTick(chart)).toBeGreaterThan(0)})++ // The clamp itself is unit-tested on the scale; what only a render catches is+ // `config.yAxis.min/max` never reaching the scale builder.+ it.each([+ ['floors the axis at yAxis.min', { min: 40 }, 40, Math.min],+ ['caps the axis at yAxis.max', { max: 80 }, 80, Math.max],+ ])('%s', (_name, bounds, expected, pick) => {+ const { chart } = renderHogChart(+ <TimeSeriesLineChart series={OFFSET_SERIES} labels={LABELS} theme={THEME} config={{ yAxis: bounds }} />+ )+ const ticks = chart.yTicks().map((t) => parseFloat(t.replace(/[^0-9.eE+-]/g, '')))+ expect(pick(...ticks)).toBe(expected)+ })++ // Same rule as the goal line below. The bound truncates the drawn line, but a label is+ // DOM-positioned, so without a guard a clipped point still prints its number over the+ // title and legend. A point exactly on the bound keeps its label.+ it('hides a value label for a point above the bounded window', () => {+ const { chart } = renderHogChart(+ <TimeSeriesLineChart+ series={OFFSET_SERIES}+ labels={LABELS}+ theme={THEME}+ config={{ yAxis: { max: 60 }, valueLabels: true }}+ />+ )+ expect(chart.valueLabels().map((l) => l.text)).toEqual(['50', '60'])+ })++ // A goal line pushed outside a bounded window must drop out, not paint over the axis gutter.+ it('hides a goal line that falls outside the bounded window', () => {+ const { chart } = renderHogChart(+ <TimeSeriesLineChart+ series={OFFSET_SERIES}+ labels={LABELS}+ theme={THEME}+ config={{ yAxis: { max: 80 }, goalLines: [{ value: 500, label: 'Target' }] }}+ />+ )+ expect(chart.referenceLines()).toHaveLength(0)+ expect(chart.yTicks().length).toBeGreaterThan(0)+ })})describe('config.yAxis array (dual y-axis)', () => {diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsxindex 5e272c5de96d..854d111d8cd5 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx@@ -1,4 +1,4 @@-import React from 'react'+import React, { useMemo } from 'react'import { ChartLegend } from '../../components/Legend/ChartLegend'import type {@@ -14,7 +14,7 @@ import type {} from '../../core/types'import { ReferenceLines } from '../../overlays/ReferenceLine'import { ValueLabels } from '../../overlays/ValueLabels'-import type { GoalLineConfig } from '../../utils/goal-lines'+import { mergeValueDomains, type GoalLineConfig } from '../../utils/goal-lines'import { useTimeSeriesTooltipConfig, type XAxisConfig, type YAxisConfig } from '../../utils/use-axis-formatters'import { LineChart } from '../LineChart/LineChart'import {@@ -23,7 +23,7 @@ import {type MovingAverageConfig,type TrendLineConfig,} from '../utils/use-derived-series'-import { useGoalLines, useTimeSeries } from '../utils/use-time-series'+import { useGoalLines, useTimeSeries, useValueBounds } from '../utils/use-time-series'import type { ValueLabelsConfig } from '../utils/use-value-labels'export type { ConfidenceIntervalConfig, MovingAverageConfig, TrendLineConfig }@@ -130,7 +130,10 @@ export function TimeSeriesLineChart<Meta = unknown>({})// Goal lines scale against the drawn (post-derived) series, unlike bar/combo.- const { referenceLines, valueDomain } = useGoalLines(goalLines, finalSeries)+ const { referenceLines, valueDomain: goalLineDomain } = useGoalLines(goalLines, finalSeries)+ const boundsDomain = useValueBounds(primaryYAxis)+ // A capped axis still has to stretch to reach an off-scale goal line.+ const valueDomain = useMemo(() => mergeValueDomains(goalLineDomain, boundsDomain), [goalLineDomain, boundsDomain])// `startAtZero === false` floats the primary axis to its data range; the default (undefined/true)// keeps the baseline clamped to 0. A log scale has no zero baseline to clamp, so it's a no-op there.diff --git a/packages/quill/packages/charts/src/charts/utils/use-time-series.ts b/packages/quill/packages/charts/src/charts/utils/use-time-series.tsindex 103777595e97..6c9b01097b2c 100644--- a/packages/quill/packages/charts/src/charts/utils/use-time-series.ts+++ b/packages/quill/packages/charts/src/charts/utils/use-time-series.ts@@ -83,6 +83,15 @@ export function useTimeSeries<Meta>(}}+/** The primary axis's `min`/`max` as a {@link ValueDomain}, memoized so a chart with no bounds set+ * doesn't churn its scales. Merge it with the goal-line domain rather than passing it alone, or a+ * chart carrying both a cap and an off-scale goal line keeps only one of them. */+export function useValueBounds(axis: YAxisConfig | undefined): ValueDomain | undefined {+ const min = typeof axis?.min === 'number' && isFinite(axis.min) ? axis.min : undefined+ const max = typeof axis?.max === 'number' && isFinite(axis.max) ? axis.max : undefined+ return useMemo(() => (min === undefined && max === undefined ? undefined : { min, max }), [min, max])+}+/** Goal lines resolved against the series they should scale with — the drawn (post-derived)* series for the line chart, the hook's `chartSeries` for bar/combo. `valueDomain` extends the value* axis to cover goal lines outside the data range, so an off-scale goal still renders on-plot;diff --git a/packages/quill/packages/charts/src/core/bar-layout.test.ts b/packages/quill/packages/charts/src/core/bar-layout.test.tsindex 15a45c913fd1..7cfaf3675a01 100644--- a/packages/quill/packages/charts/src/core/bar-layout.test.ts+++ b/packages/quill/packages/charts/src/core/bar-layout.test.ts@@ -114,7 +114,7 @@ describe('hog-charts bar-layout', () => {const s = makeSeries({ key: 's', data: [75] })const scales = createBarScales([s], ['a'], dimensions, {barLayout: 'grouped',- valueDomain: [50, 100],+ valueDomain: { min: 50, max: 100 },})const bar = layoutOf({ series: s, scales })[0]!const plotBottom = dimensions.plotTop + dimensions.plotHeight@@ -311,7 +311,7 @@ describe('hog-charts bar-layout', () => {layout: 'stacked' as const,axisOrientation: 'vertical' as const,value: 1,- valueDomain: [0, 1000] as [number, number],+ valueDomain: { min: 0, max: 1000 },// 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,@@ -322,7 +322,7 @@ describe('hog-charts bar-layout', () => {layout: 'stacked' as const,axisOrientation: 'vertical' as const,value: 0,- valueDomain: [0, 1000] as [number, number],+ valueDomain: { min: 0, max: 1000 },edge: 'height' as const,expected: 0,},@@ -331,7 +331,7 @@ describe('hog-charts bar-layout', () => {layout: 'stacked' as const,axisOrientation: 'vertical' as const,value: 1000,- valueDomain: [0, 1000] as [number, number],+ valueDomain: { min: 0, max: 1000 },edge: 'top' as const,expected: 0,},@@ -340,7 +340,7 @@ describe('hog-charts bar-layout', () => {layout: 'grouped' as const,axisOrientation: 'vertical' as const,value: 1,- valueDomain: [0, 1000] as [number, number],+ valueDomain: { min: 0, max: 1000 },edge: 'top' as const,expected: 94,},@@ -349,7 +349,7 @@ describe('hog-charts bar-layout', () => {layout: 'grouped' as const,axisOrientation: 'vertical' as const,value: -1,- valueDomain: [-1000, 1000] as [number, number],+ valueDomain: { min: -1000, max: 1000 },// 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.@@ -361,7 +361,7 @@ describe('hog-charts bar-layout', () => {layout: 'grouped' as const,axisOrientation: 'horizontal' as const,value: 1,- valueDomain: [0, 1000] as [number, number],+ valueDomain: { min: 0, max: 1000 },// baseline (value 0) sits at x=0; floored cap grows 6px right of it.edge: 'right' as const,expected: 6,@@ -408,7 +408,7 @@ describe('hog-charts bar-layout', () => {const scales = createBarScales([lower, upper], labels, PIXEL_TEST_DIMENSIONS, {barLayout: 'stacked',minBarSize: 10,- valueDomain: [0, 1000],+ valueDomain: { min: 0, max: 1000 },})const stacks = computeStackData([lower, upper], labels)const shared = { labels, scales, layout: 'stacked' as const, isHorizontal: false }diff --git a/packages/quill/packages/charts/src/core/bar-scales.test.ts b/packages/quill/packages/charts/src/core/bar-scales.test.tsindex 6e56604c5215..f22e79327025 100644--- a/packages/quill/packages/charts/src/core/bar-scales.test.ts+++ b/packages/quill/packages/charts/src/core/bar-scales.test.ts@@ -225,24 +225,27 @@ describe('hog-charts bar scales', () => {})})- describe('createBarScales — valueDomain [min, max] (fixed)', () => {+ describe('createBarScales — valueDomain with both ends pinned', () => {it.each([- ['pins the domain regardless of data and skips nice()', undefined, [0, 40] as [number, number]],- ['takes precedence over percent layout', 'percent' as const, [0, 200] as [number, number]],- ])('%s', (_name, barLayout, valueDomain) => {+ ['pins the domain regardless of data and skips nice()', undefined, 0, 40],+ ['takes precedence over percent layout', 'percent' as const, 0, 200],+ ])('%s', (_name, barLayout, min, max) => {const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]- const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, { barLayout, valueDomain })- expect(value.domain()).toEqual(valueDomain)+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, {+ barLayout,+ valueDomain: { min, max },+ })+ expect(value.domain()).toEqual([min, max])})// A non-finite or collapsed fixed domain maps every bar (and axis tick) to NaN, so the chart// paints nothing while x-only tooltips keep working — the same failure the line path guards// against via sanitizeFixedDomain. The bar value scale must stay well-formed too.it.each([- { name: 'NaN bounds', valueDomain: [NaN, NaN] as [number, number] },- { name: 'a NaN max (e.g. Math.max of empty data)', valueDomain: [0, NaN] as [number, number] },- { name: 'an infinite max', valueDomain: [0, Infinity] as [number, number] },- { name: 'collapsed bounds', valueDomain: [50, 50] as [number, number] },+ { name: 'NaN bounds', valueDomain: { min: NaN, max: NaN } },+ { name: 'a NaN max (e.g. Math.max of empty data)', valueDomain: { min: 0, max: NaN } },+ { name: 'an infinite max', valueDomain: { min: 0, max: Infinity } },+ { name: 'collapsed bounds', valueDomain: { min: 50, max: 50 } },])('keeps a finite, non-degenerate domain for $name', ({ valueDomain }) => {const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]const [min, max] = createBarScales(series, ['a', 'b', 'c'], dimensions, { valueDomain }).value.domain()diff --git a/packages/quill/packages/charts/src/core/scales.test.ts b/packages/quill/packages/charts/src/core/scales.test.tsindex 4dd1a6096a29..4f95cf4325dd 100644--- a/packages/quill/packages/charts/src/core/scales.test.ts+++ b/packages/quill/packages/charts/src/core/scales.test.ts@@ -1,5 +1,6 @@import { dimensions, makeSeries } from '../testing'import {+ applyValueBounds,autoFormatYTick,buildSegmentResolveValue,buildStackedPositionValue,@@ -235,26 +236,26 @@ describe('hog-charts scales', () => {})})- describe('createYScale — valueDomain [min, max] (fixed)', () => {+ describe('createYScale — valueDomain with both ends pinned', () => {it('pins the domain regardless of data and skips nice()', () => {const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]- const scale = createYScale(series, dimensions, { valueDomain: [0, 40] })+ const scale = createYScale(series, dimensions, { valueDomain: { min: 0, max: 40 } })expect(scale.domain()).toEqual([0, 40])})it('takes precedence over percent stack mode', () => {const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]- const scale = createYScale(series, dimensions, { percentStack: true, valueDomain: [0, 200] })+ const scale = createYScale(series, dimensions, { percentStack: true, valueDomain: { min: 0, max: 200 } })expect(scale.domain()).toEqual([0, 200])})// A non-finite or collapsed fixed domain maps every value (and axis tick) to NaN, so the// chart paints nothing while x-only tooltips keep working. The domain must stay well-formed.it.each([- { name: 'NaN bounds', valueDomain: [NaN, NaN] as [number, number] },- { name: 'a NaN max (e.g. Math.max of empty data)', valueDomain: [0, NaN] as [number, number] },- { name: 'an infinite max', valueDomain: [0, Infinity] as [number, number] },- { name: 'collapsed bounds', valueDomain: [50, 50] as [number, number] },+ { name: 'NaN bounds', valueDomain: { min: NaN, max: NaN } },+ { name: 'a NaN max (e.g. Math.max of empty data)', valueDomain: { min: 0, max: NaN } },+ { name: 'an infinite max', valueDomain: { min: 0, max: Infinity } },+ { name: 'collapsed bounds', valueDomain: { min: 50, max: 50 } },])('keeps a finite, non-degenerate domain for $name', ({ valueDomain }) => {const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]const [min, max] = createYScale(series, dimensions, { valueDomain }).domain()@@ -264,6 +265,91 @@ describe('hog-charts scales', () => {})})+ describe('applyValueBounds', () => {+ // Every chart's domain flows through this, so an unset-bounds path that shifts it would+ // silently re-scale every existing chart.+ it.each([+ ['undefined', undefined],+ ['an empty object', {}],+ ['a NaN min', { min: NaN }],+ ['an infinite max', { max: Infinity }],+ ['a non-numeric min from a stored query', { min: '5' as unknown as number }],+ ])('leaves the domain untouched for %s', (_name, bounds) => {+ expect(applyValueBounds([0, 10], bounds)).toEqual([0, 10])+ })++ // A single bound past the data would otherwise invert the domain, mapping every value to NaN.+ it.each([+ ['a min above the data', { min: 50 }, [50, 60]],+ ['a max below the data', { max: -20 }, [-30, -20]],+ ])('keeps an ascending domain for %s', (_name, bounds, expected) => {+ expect(applyValueBounds([0, 10], bounds)).toEqual(expected)+ })++ // Swapping the pair (what sanitizeFixedDomain does) would render an axis nobody asked for.+ it.each([+ ['inverted bounds', { min: 100, max: 10 }],+ ['collapsed bounds', { min: 5, max: 5 }],+ ])('falls back to the automatic domain for %s', (_name, bounds) => {+ expect(applyValueBounds([0, 10], bounds)).toEqual([0, 10])+ })++ // A log domain reaching 0 maps every value to ±Infinity, blanking the chart.+ it.each([+ ['zero', { min: 0 }],+ ['negative', { min: -5 }],+ ])('drops a %s bound on a log scale', (_name, bounds) => {+ expect(applyValueBounds([1, 100], bounds, { log: true })).toEqual([1, 100])+ })++ // Only the caller's bound is vetted for positivity, so on a log scale the end derived+ // opposite it can land at or below zero, which maps every value to NaN.+ it.each([+ ['a max below the data', { max: 5 }, [0.05, 5]],+ ['a min above the data', { min: 2000 }, [2000, 200000]],+ ])('derives a positive opposite end for %s on a log scale', (_name, bounds, expected) => {+ expect(applyValueBounds([10, 1000], bounds, { log: true })).toEqual(expected)+ })+ })++ describe('createYScale — valueBounds', () => {+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]++ // Bounds must clamp back over goal-line stretching, not be widened by it afterwards.+ it('applies bounds after goal-line { include } folding', () => {+ const scale = createYScale(series, dimensions, {+ valueDomain: { include: [500], max: 40 },+ })+ expect(scale.domain()[1]).toBe(40)+ })++ // Both set the axis floor and the explicit one wins, since the zero clamp is only a default.+ // A consumer wanting its own baseline control to win holds the bound back before this point,+ // as the trends adapter does.+ it('applies a min over the zero-baseline clamp', () => {+ const offset = [makeSeries({ key: 's1', data: [50, 60, 70] })]+ expect(createYScale(offset, dimensions).domain()[0]).toBe(0)+ expect(createYScale(offset, dimensions, { valueDomain: { min: 40 } }).domain()[0]).toBe(40)+ })++ // The empty-data domain is linear whatever scale type was asked for, so a non-positive bound+ // is safe here and must not be dropped as though this were a log scale.+ it('honors a non-positive bound on a log scale with no data', () => {+ const scale = createYScale([], dimensions, { scaleType: 'log', valueDomain: { min: -5 } })+ expect(scale.domain()).toEqual([-5, 1])+ })++ // A pin wins over percent layout because it asks for an exact window, while a single clamp+ // only adjusts a data-derived range that percent layout has already replaced with 0..1.+ it.each([+ ['a pin overrides percentStack', { min: 5, max: 8 }, [5, 8]],+ ['a partial clamp is ignored under percentStack', { max: 8 }, [0, 1]],+ ])('%s', (_name, valueDomain, expected) => {+ const scale = createYScale(series, dimensions, { percentStack: true, valueDomain })+ expect(scale.domain()).toEqual(expected)+ })+ })+describe('createYScale — log mode', () => {it('returns a log scale', () => {const series = [makeSeries({ key: 's1', data: [1, 10, 100] })]@@ -373,6 +459,16 @@ describe('hog-charts scales', () => {expect(left(1)).not.toBeCloseTo(right(1), 0)})+ // Applying them to every axis would crush a secondary one onto a domain chosen for the+ // primary axis's units.+ it('applies valueBounds to the primary axis only', () => {+ const small = makeSeries({ key: 'small', data: [0, 10], yAxisId: DEFAULT_Y_AXIS_ID })+ const large = makeSeries({ key: 'large', data: [0, 1000], yAxisId: 'y1' })+ const result = createScales([small, large], ['a', 'b'], dimensions, { valueDomain: { max: 5 } })+ expect(result.yAxes![DEFAULT_Y_AXIS_ID].scale.domain()[1]).toBe(5)+ expect(result.yAxes!.y1.scale.domain()[1]).toBe(1000)+ })+it.each([['DEFAULT_Y_AXIS_ID first', [DEFAULT_Y_AXIS_ID, 'y1']],['non-default first', ['y1', DEFAULT_Y_AXIS_ID]],diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex 3f9c3b5fba01..bf115e2a8331 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -73,19 +73,32 @@ export function seriesValueRange(series: Series[]): SeriesValueRange {return { min, max, minPositive, count }}-/** Split a {@link ValueDomain} into its two mutually-exclusive modes — a fixed `[min, max]`- * or the set of values an auto-scaled domain must `include`. */+/** Split a {@link ValueDomain} into a pinned `[min, max]` (both ends given) and the adjustments to+ * an auto-scaled domain (either end left open). An inverted pair is dropped rather than swapped;+ * see {@link ValueDomain}. */function resolveValueDomain(valueDomain: ValueDomain | undefined): {fixed?: readonly [number, number]include?: readonly number[]+ bounds?: ValueDomain} {if (!valueDomain) {return {}}- if ('include' in valueDomain) {- return { include: valueDomain.include }+ const { include } = valueDomain+ const min = usableBound(valueDomain.min)+ const max = usableBound(valueDomain.max)++ if (min !== undefined && max !== undefined) {+ // Both ends pinned, so `include` has nothing left to stretch.+ return min < max ? { fixed: [min, max] } : { include }}- return { fixed: valueDomain }+ return { include, bounds: { min, max } }+}++/** A non-finite bound counts as absent rather than honored, since these arrive from stored queries+ * and `Math.max`-style expressions, not just typed input. */+function usableBound(value: number | undefined): number | undefined {+ return typeof value === 'number' && isFinite(value) ? value : undefined}/** Fold extra values (e.g. goal-line targets) into a range so the axis covers them even when@@ -157,6 +170,52 @@ export function sanitizeFixedDomain([min, max]: readonly [number, number]): [numreturn min < max ? [min, max] : [max, min]}+/** Clamp an already-computed domain to the caller's {@link ValueDomain}, running last so it composes+ * with `include` folding, the zero-baseline clamp, and `nice()`. Deliberately does not re-`nice()`,+ * since rounding a typed bound would defeat the point of typing it. */+export function applyValueBounds(+ domain: readonly [number, number],+ bounds: ValueDomain | undefined,+ options: { log?: boolean } = {}+): [number, number] {+ // A log domain containing 0 maps every value to ±Infinity, so a non-positive bound is dropped.+ const usable = (v: number | undefined): number | undefined =>+ typeof v === 'number' && isFinite(v) && (!options.log || v > 0) ? v : undefined+ const min = usable(bounds?.min)+ const max = usable(bounds?.max)++ if (min === undefined && max === undefined) {+ return [domain[0], domain[1]]+ }+ if (min !== undefined && max !== undefined) {+ return min < max ? [min, max] : [domain[0], domain[1]]+ }++ const lo = min ?? domain[0]+ const hi = max ?? domain[1]+ if (lo < hi) {+ return [lo, hi]+ }+ // The bound sits past the whole data range (e.g. "min 50" on 0-10 data), so carry the original+ // extent over to the other end rather than collapsing the domain. A log axis carries the ratio+ // instead, since subtracting a span from a small positive bound lands at or below zero and+ // `usable` only vetted the caller's bound, not the end derived here.+ if (options.log) {+ const ratio = domain[0] > 0 && domain[1] > domain[0] ? domain[1] / domain[0] : 10+ return min !== undefined ? [lo, lo * ratio] : [hi / ratio, hi]+ }+ const span = domain[1] - domain[0] > 0 ? domain[1] - domain[0] : 1+ return min !== undefined ? [lo, lo + span] : [hi - span, hi]+}++/** Apply {@link ValueDomain} to a built d3 scale in place. */+function withValueBounds<S extends D3YScale>(scale: S, bounds: ValueDomain | undefined, log: boolean): S {+ if (!bounds || (bounds.min === undefined && bounds.max === undefined)) {+ return scale+ }+ return scale.domain(applyValueBounds(scale.domain() as [number, number], bounds, { log })) as S+}+/** Repair a degenerate (`min === max`) or non-finite value-scale extent so a linear domain can't* map every value to NaN: coerce non-finite bounds to 0, bracket zero, and guarantee a unit span.* Callers apply it only inside the degenerate/non-finite guard — bracketing a well-formed extent@@ -172,14 +231,14 @@ export function createYScale(options: {scaleType?: 'linear' | 'log'percentStack?: boolean- /** Fixed `[min, max]` or `{ include }` extra values the domain must cover. */+ /** A pinned `[min, max]`, or adjustments (`include` / `min` / `max`) to the auto domain. */valueDomain?: ValueDomain/** Float the axis to its data range instead of clamping the baseline to 0. See {@link buildValueScale}. */floatBaseline?: boolean} = {}): ScaleLinear<number, number> | ScaleLogarithmic<number, number> {const { scaleType = 'linear', percentStack = false, valueDomain, floatBaseline = false } = options- const { fixed, include } = resolveValueDomain(valueDomain)+ const { fixed, include, bounds } = resolveValueDomain(valueDomain)const tickCount = yTickCountForHeight(dimensions.plotHeight)if (fixed) {@@ -210,6 +269,7 @@ export function createYScale(scaleType,allowNegativeBaseline: hasExplicitNegativeGoal,floatBaseline,+ bounds,})}@@ -233,6 +293,8 @@ export function buildValueScale(options: {/** Skip the zero-baseline clamp entirely so the axis floats to its data range (a y-axis "start at* zero = off"). The default clamps a non-negative axis down to 0. Has no effect on a log scale. */floatBaseline?: boolean+ /** Partial user clamp. See {@link applyValueBounds}. */+ bounds?: ValueDomain}): D3YScale {const {range,@@ -242,15 +304,18 @@ export function buildValueScale(options: {primaryRange = range,allowNegativeBaseline = false,floatBaseline = false,+ bounds,} = options+ const isLog = scaleType === 'log'if (range.count === 0) {- return scaleLinear().domain([0, 1]).range(valueRange)+ // This domain is linear whatever `scaleType` asked for, so a non-positive bound is safe here.+ return withValueBounds(scaleLinear().domain([0, 1]).range(valueRange), bounds, false)}let { min, max } = range- if (scaleType === 'log') {+ if (isLog) {if (!isFinite(range.minPositive)) {// No positive values for a log scale (e.g. all-zero data). Fall back to linear, and// bracket a degenerate `min === max` domain so it doesn't collapse to NaN.@@ -261,9 +326,18 @@ export function buildValueScale(options: {logMin = lologMax = hi}- return scaleLinear().domain([logMin, logMax]).nice(tickCount).range(valueRange)+ // The scale fell back to linear, so a non-positive bound is no longer a hazard.+ return withValueBounds(+ scaleLinear().domain([logMin, logMax]).nice(tickCount).range(valueRange),+ bounds,+ false+ )}- return scaleLog().domain(niceLogDomain(range.minPositive, max)).range(valueRange).clamp(true)+ return withValueBounds(+ scaleLog().domain(niceLogDomain(range.minPositive, max)).range(valueRange).clamp(true),+ bounds,+ true+ )}if (!floatBaseline) {@@ -285,7 +359,7 @@ export function buildValueScale(options: {max = hi}- return scaleLinear().domain([min, max]).nice(tickCount).range(valueRange)+ return withValueBounds(scaleLinear().domain([min, max]).nice(tickCount).range(valueRange), bounds, false)}/** Map raw d3 per-axis scales into the public {@link YAxisScale} shape (value→pixel fn + tickdiff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 1c89f3d62c5f..b7168ba88cff 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -393,18 +393,28 @@ export interface TooltipConfig {sortedByValue?: boolean}-/** How the value axis domain is determined (y for vertical/line/area charts, x for horizontal- * bars). The two modes are mutually exclusive by construction — pick one. Omit the option- * entirely for the default: a data-derived range with `d3.nice()`. */-export type ValueDomain =- /** Pin both ends — skips the data-derived range and `d3.nice()` so independent charts that- * share this domain stay visually comparable (e.g. funnel steps). Takes precedence over- * `barLayout: 'percent'` / `percentStackView`. */- | readonly [number, number]- /** Keep data-derived auto-scaling, but stretch the domain to always cover these values- * (e.g. goal-line targets that sit outside the data). Folded into the range before- * `d3.nice()`. */- | { include: readonly number[] }+/** Value-axis domain control (y for vertical/line/area charts, x for horizontal bars). Omit for the+ * default: a data-derived range with `d3.nice()`.+ *+ * Setting **both** ends pins the domain, skipping `d3.nice()` and overriding percent layout, which+ * keeps independent charts visually comparable (e.g. funnel steps). Setting **one** clamps that end+ * and leaves the other automatic.+ *+ * A non-finite bound counts as unset, so `{ min: 0, max: Math.max(...[]) }` floors at zero instead+ * of collapsing. An inverted pair falls back to the automatic domain rather than being swapped,+ * because these arrive from saved queries, the API, and MCP, where a silent reinterpretation would+ * render an axis nobody asked for. */+export interface ValueDomain {+ /** Widen the domain to cover these values (e.g. off-scale goal lines). Folded in before+ * `d3.nice()`. Ignored once both `min` and `max` are set. */+ include?: readonly number[]+ /** Floor of the value axis, applied after `include` folding, the zero clamp and `d3.nice()`, and+ * used verbatim so a typed bound isn't rounded away. Ignored under a percent layout, and dropped+ * when non-positive on a log scale. */+ min?: number+ /** Ceiling of the value axis. See {@link ValueDomain.min}. */+ max?: number+}/** Bar appearance + band-layout details. Grouped under {@link BarChartConfig.bars} to keep the* config flat at the top level. `barLayout` stays top-level as the primary discriminator. */diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsxindex 54223c16d847..b673ba92e38f 100644--- a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx@@ -21,6 +21,10 @@ const X_POSITIONS: Record<string, number> = { Mon: 60, Tue: 220, Wed: 380, Thu:const xScale = (label: string): number | undefined => X_POSITIONS[label]// Left axis: 0 -> 368, 100 -> 16const yScale = (v: number): number => 368 - (v / 100) * 352+// The overlay drops anchors outside the plot, so a case carrying values beyond 0..100 needs a scale+// whose domain covers them or every label is dropped and the case stops testing what it was for.+const wideYScale = (v: number): number => 368 - (v / 10000) * 352+const signedYScale = (v: number): number => 192 - (v / 100) * 176function makeContext(series: ResolvedSeries[],@@ -59,7 +63,10 @@ describe('ValueLabels', () => {['custom formatter', (v) => `$${(v / 1000).toFixed(1)}k`, [1000, 2000], ['$1.0k', '$2.0k']],])('formats labels: %s', (_name, formatter, data, expected) => {const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data }]- const ctx = makeContext(series, { labels: ['Mon', 'Tue'] })+ const ctx = makeContext(series, {+ labels: ['Mon', 'Tue'],+ scales: { x: xScale, y: wideYScale, yTicks: () => [0, 5000, 10000] },+ })const { container } = renderInChart(ctx, <ValueLabels valueFormatter={formatter} />)const divs = labelDivs(container)expect(divs.map((d) => d.textContent)).toEqual(expected)@@ -90,7 +97,8 @@ describe('ValueLabels', () => {it('positions negative values below the point and positive values above', () => {const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [50, -50, 25, -25, 75] }]- const { container } = renderInChart(makeContext(series), <ValueLabels />)+ const ctx = makeContext(series, { scales: { x: xScale, y: signedYScale, yTicks: () => [-100, 0, 100] } })+ const { container } = renderInChart(ctx, <ValueLabels />)const divs = labelDivs(container)expect(divs).toHaveLength(5)// positive values (50, 25, 75) render above → transform translates up by full height@@ -118,13 +126,15 @@ describe('ValueLabels', () => {})it('horizontal: flips a right-clipping label inside the bar instead of expanding margins', () => {- // Place the value-coord 4px from the right wrapper edge so the label (>4px wide) would- // overflow when anchored on its leading edge; flip to anchor on its trailing edge instead.+ // A bar reaching the edge of a plot with almost no right margin: anchored on its leading+ // edge the label would overflow the wrapper's `overflow: hidden`, so it flips. The anchor+ // stays on the plot edge rather than past it, since beyond that a label is dropped.const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [1] }]const ctx = makeContext(series, {axisOrientation: 'horizontal',labels: ['Mon'],- scales: { x: () => 60, y: () => 796, yTicks: () => [0, 1] },+ dimensions: { ...DIMENSIONS, plotWidth: 744 },+ scales: { x: () => 200, y: () => 792, yTicks: () => [0, 1] },})const divs = labelDivs(renderInChart(ctx, <ValueLabels />).container)expect(divs).toHaveLength(1)@@ -358,7 +368,10 @@ describe('ValueLabels', () => {{ key: 'a', label: 'A', color: '#a00', data: [30, 25] },{ key: 'b', label: 'B', color: '#0a0', data: [-10, 75] },]- const ctx = makeContext(series, { labels: ['Mon', 'Tue'] })+ const ctx = makeContext(series, {+ labels: ['Mon', 'Tue'],+ scales: { x: xScale, y: signedYScale, yTicks: () => [-100, 0, 100] },+ })const { container } = renderInChart(ctx,<ValueLabels valueFormatter={(_v, _si, _di, c) => `${c.rawValue}|${c.bandValues.join(',')}`} />@@ -375,7 +388,10 @@ describe('ValueLabels', () => {{ key: 'a', label: 'A', color: '#a00', data: [30, 25] },{ key: 'b', label: 'B', color: '#0a0', data: [-10, 75] },]- const ctx = makeContext(series, { labels: ['Mon', 'Tue'] })+ const ctx = makeContext(series, {+ labels: ['Mon', 'Tue'],+ scales: { x: xScale, y: signedYScale, yTicks: () => [-100, 0, 100] },+ })const { container } = renderInChart(ctx,<ValueLabels valueFormatter={(_v, _si, _di, c) => `${c.rawValue}|${c.previousBandValues.join(',')}`} />diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.tsxindex 86f0e09c4091..fc931e13ff0b 100644--- a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx@@ -323,6 +323,17 @@ function rectsOverlap(a: Rect, b: Rect, gap: number): boolean {return a.left < b.right + gap && a.right + gap > b.left && a.top < b.bottom + gap && a.bottom + gap > b.top}+/** Whether a candidate's anchor sits inside the plot area along the value axis. A bounded or pinned+ * `valueDomain` truncates the drawn line or bar, but a label is DOM-positioned straight off the+ * scale, so without this an out-of-range point still prints its number over the title and legend.+ * Inclusive at both edges, so a value sitting exactly on the bound keeps its label. */+function withinPlotArea(c: Candidate, dimensions: ChartDimensions, isHorizontal: boolean): boolean {+ if (isHorizontal) {+ return c.x >= dimensions.plotLeft && c.x <= dimensions.plotLeft + dimensions.plotWidth+ }+ return c.y >= dimensions.plotTop && c.y <= dimensions.plotTop + dimensions.plotHeight+}+function fitsWithinWrapper(c: Candidate, above: boolean, dimensions: ChartDimensions, isHorizontal: boolean): boolean {if (isHorizontal) {const left = above ? c.x : c.x - c.width@@ -467,7 +478,7 @@ export function ValueLabels({isHorizontal,mode,isPercent,- }),+ }).filter((c) => withinPlotArea(c, dimensions, isHorizontal)),dimensions,isHorizontal),diff --git a/packages/quill/packages/charts/src/utils/goal-lines.test.ts b/packages/quill/packages/charts/src/utils/goal-lines.test.tsindex 0a0e92174d65..49ac1a575c2b 100644--- a/packages/quill/packages/charts/src/utils/goal-lines.test.ts+++ b/packages/quill/packages/charts/src/utils/goal-lines.test.ts@@ -88,10 +88,20 @@ describe('goal-lines', () => {})describe('mergeValueDomains', () => {+ // A pin beating the goal lines is settled at resolution, not here, so a pinned pair still+ // merges and keeps the `include` that resolution will discard.it.each([['returns the defined side when the other is undefined', undefined, { include: [5] }, { include: [5] }],- ['a fixed domain wins over an include set', [0, 10] as const, { include: [50] }, [0, 10]],['two include sets merge', { include: [5] }, { include: [50] }, { include: [5, 50] }],+ ['a bound and an include set both survive', { min: 40 }, { include: [500] }, { min: 40, include: [500] }],+ ['bounds merge field by field', { min: 40 }, { max: 90 }, { min: 40, max: 90 }],+ ['the left side wins a contested bound', { max: 60 }, { max: 90 }, { max: 60 }],+ [+ 'a pin keeps the include for the resolver to drop',+ { min: 0, max: 10 },+ { include: [50] },+ { min: 0, max: 10, include: [50] },+ ],] as const)('%s', (_, a, b, expected) => {expect(mergeValueDomains(a, b)).toEqual(expected)})diff --git a/packages/quill/packages/charts/src/utils/goal-lines.ts b/packages/quill/packages/charts/src/utils/goal-lines.tsindex 9a6ef4df78a4..f565d16cf1be 100644--- a/packages/quill/packages/charts/src/utils/goal-lines.ts+++ b/packages/quill/packages/charts/src/utils/goal-lines.ts@@ -57,18 +57,18 @@ export function goalLineValueDomain(referenceLines: readonly ReferenceLineProps[return values.length > 0 ? { include: values } : undefined}-/** Combine a consumer-set {@link ValueDomain} with the goal-line stretch. A fixed `[min, max]`- * wins outright — the consumer pinned the axis, so nothing may stretch it — while two `include`- * sets merge, so an explicit include and off-scale goal lines both widen the auto domain. */+/** Combine a consumer-set {@link ValueDomain} with the goal-line stretch, field by field, so a+ * capped axis still stretches to reach an off-scale goal line. `a` wins a contested bound. A+ * consumer pinning both ends still overrides the goal lines, but that is settled when the domain+ * resolves and drops `include`, not here. */export function mergeValueDomains(a: ValueDomain | undefined, b: ValueDomain | undefined): ValueDomain | undefined {if (!a || !b) {return a ?? b}- if (!('include' in a)) {- return a+ const include = [...(a.include ?? []), ...(b.include ?? [])]+ return {+ include: include.length > 0 ? include : undefined,+ min: a.min ?? b.min,+ max: a.max ?? b.max,}- if (!('include' in b)) {- return b- }- return { include: [...a.include, ...b.include] }}diff --git a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts b/packages/quill/packages/charts/src/utils/use-axis-formatters.tsindex eedd9d5fc9c2..8d8773fe9634 100644--- a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts+++ b/packages/quill/packages/charts/src/utils/use-axis-formatters.ts@@ -37,6 +37,13 @@ export interface YAxisConfig extends YFormatterConfig {* on a log scale; honored per axis in the array (multi-axis) form, except axes carrying bar* series, which always draw from 0. */startAtZero?: boolean+ /** Pins the low end of the axis, overriding both the data-derived bound and `startAtZero`. Omit+ * for an automatic bound. Primary axis only; ignored under a percent layout, and dropped when+ * non-positive on a log scale. Read by the line charts only: this config is shared, but bar and+ * combo charts ignore it, since a bar encodes magnitude as length from zero. */+ min?: number+ /** Pins the high end of the axis. Omit for an automatic bound. See {@link YAxisConfig.min}. */+ max?: number}export function useXTickFormatter(diff --git a/posthog/schema.py b/posthog/schema.pyindex 71f1ff357746..3d089f08163e 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -8044,7 +8044,30 @@ class TrendsFilter(BaseModel):)xAxisLabel: str | None = Field(default=None, description="Custom label rendered under the X axis.")yAxisLabel: str | None = Field(default=None, description="Custom label rendered alongside the Y axis.")+ yAxisMax: float | None = Field(+ default=None,+ description=(+ "Pins the top of the y-axis; unset means automatic. Ignored in the same"+ " cases as `yAxisStartAtZero`, and when `yAxisMin` is not below it."+ ),+ )+ yAxisMin: float | None = Field(+ default=None,+ description=(+ "Pins the bottom of the y-axis; unset means automatic. Ignored in the same"+ " cases as `yAxisStartAtZero`, while it is on, and when not below"+ " `yAxisMax`."+ ),+ )yAxisScaleType: YAxisScaleType | None = YAxisScaleType.LINEAR+ yAxisStartAtZero: bool | None = Field(+ default=True,+ description=(+ "Y-axis baseline. When false the axis floats to the data range instead of"+ " starting at zero. Ignored on bar displays (bars always draw from zero),"+ " on a logarithmic scale, and while showing percentages."+ ),+ )class TrendsQueryResponse(BaseModel):diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.pyindex 772f4ce06cfd..9829af66a686 100644--- a/posthog/schema_helpers.py+++ b/posthog/schema_helpers.py@@ -100,6 +100,9 @@ def to_dict(query: BaseModel) -> dict:"showMean","meanRetentionCalculation","yAxisScaleType",+ "yAxisStartAtZero",+ "yAxisMin",+ "yAxisMax","hiddenLegendIndexes","hiddenLegendBreakdowns","resultCustomizations",diff --git a/posthog/test/test_schema_helpers.py b/posthog/test/test_schema_helpers.pyindex b091bd757938..3a9d658aad8a 100644--- a/posthog/test/test_schema_helpers.py+++ b/posthog/test/test_schema_helpers.py@@ -91,8 +91,18 @@ class TestSchemaHelpers(TestCase):self.assertEqual(result_dict, {"kind": "TrendsQuery", "series": [{"name": "$pageview"}]})- def test_serializes_insight_filter_without_frontend_only_props(self):- query = TrendsQuery(**{**base_trends, "trendsFilter": {"showLegend": True}})+ @parameterized.expand(+ [+ ({"showLegend": True},),+ # The y-axis range only changes how the results are drawn. Leaving it in the cache key+ # would refire the ClickHouse query on every axis tweak.+ ({"yAxisStartAtZero": False},),+ ({"yAxisMin": 50},),+ ({"yAxisMax": 70},),+ ]+ )+ def test_serializes_insight_filter_without_frontend_only_props(self, trends_filter):+ query = TrendsQuery(**{**base_trends, "trendsFilter": trends_filter})result_dict = to_dict(query)diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 75dd393417da..070d50d97d53 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2547,7 +2547,13 @@ export interface TrendsFilterApi {xAxisLabel?: string | null/** Custom label rendered alongside the Y axis. */yAxisLabel?: string | null+ /** Pins the top of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, and when `yAxisMin` is not below it. */+ yAxisMax?: number | null+ /** Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`. */+ yAxisMin?: number | nullyAxisScaleType?: YAxisScaleTypeApi | null+ /** Y-axis baseline. When false the axis floats to the data range instead of starting at zero. Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while showing percentages. */+ yAxisStartAtZero?: boolean | null}export interface TrendsQueryApi {diff --git a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsxindex acafe54e3c03..eb9ccc6831ff 100644--- a/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx+++ b/products/error_tracking/frontend/components/VolumeSparkline/VolumeSparkline.tsx@@ -116,7 +116,7 @@ export function VolumeSparkline({barCornerRadius: LAYOUTS[layout].barCornerRadius,bandPadding: LAYOUTS[layout].bandPadding,margins: resolveMargins(layout, eventLabelReserve),- valueDomain: [0, maxValue],+ valueDomain: { min: 0, max: maxValue },xAxis: { hide: xAxis !== 'full', tickFormatter },yAxis: { hide: true },showAxisLines: { x: showAxis, y: false },diff --git a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsxindex 7347eb766b92..66cec29848de 100644--- a/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ToolErrorRateChart.tsx@@ -63,7 +63,7 @@ export function ToolErrorRateChart({tooltip: { placement: 'cursor' },margins: { top: 4, right: 20, bottom: 22 },barCornerRadius: 4,- bars: { minBandSize: 30, valueDomain: [0, axisMax] },+ bars: { minBandSize: 30, valueDomain: { min: 0, max: axisMax } },}}, [sorted])const byTool = useMemo(() => new Map(sorted.map((r) => [r.tool, r])), [sorted])diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex d8bc97451060..599f7a266268 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1786,7 +1786,13 @@ export interface TrendsFilterApi {xAxisLabel?: string | null/** Custom label rendered alongside the Y axis. */yAxisLabel?: string | null+ /** Pins the top of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, and when `yAxisMin` is not below it. */+ yAxisMax?: number | null+ /** Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`. */+ yAxisMin?: number | nullyAxisScaleType?: YAxisScaleTypeApi | null+ /** Y-axis baseline. When false the axis floats to the data range instead of starting at zero. Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while showing percentages. */+ yAxisStartAtZero?: boolean | null}export interface TrendsQueryApi {diff --git a/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.ts b/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.tsindex 0472eb99967d..ab10334d1d3b 100644--- a/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.ts+++ b/products/product_analytics/frontend/insights/funnels/shared/funnelBarHorizontalShared.ts@@ -1,4 +1,4 @@-import type { Series } from '@posthog/quill-charts'+import type { Series, ValueDomain } from '@posthog/quill-charts'// Dependency-neutral primitives for the horizontal funnel bars, shared by the web container// (funnelBarHorizontalTransforms.ts) and the MCP UI app. Deliberately free of `~/`, `lib/`, and@@ -11,7 +11,7 @@ export const FUNNEL_BAR_HORIZONTAL_FILLER_KEY = 'funnel-bar-horizontal-filler'/** Every step's bar is its own single-band chart, so they only line up if they share this* value domain (passed to BarChart as `bars.valueDomain`). Segment data are basis-step* percentages, so the axis is `0–100`. */-export const FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN: [number, number] = [0, 100]+export const FUNNEL_BAR_HORIZONTAL_VALUE_DOMAIN: ValueDomain = { min: 0, max: 100 }export const RATE_TO_PERCENT = 100diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex 3c0f552fc420..8487d278790d 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -104,6 +104,8 @@ export interface BuildTrendsBarTimeSeriesConfigOpts {export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesConfigOpts): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {+ // No range extras: bar length encodes magnitude from zero, so a bound carried over from another+ // display type is dropped rather than silently truncating bars with no control left to clear it.const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, opts.isPercentStackView, opts.baseCurrency, {yAxisScaleType: opts.yAxisScaleType,showGrid: true,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 70713f3b5263..3f651bcd39e5 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -284,6 +284,9 @@ export function TrendsLineChart({allDays: currentPeriodResult?.days ?? [],xAxisLabel: trendsFilter?.xAxisLabel,yAxisLabel: trendsFilter?.yAxisLabel,+ yAxisStartAtZero: trendsFilter?.yAxisStartAtZero,+ yAxisMin: trendsFilter?.yAxisMin,+ yAxisMax: trendsFilter?.yAxisMax,goalLines,incompletenessOffsetFromEnd,getHidden: getTrendsHidden,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.tsindex 5d363542fc95..e9f28b8b3e53 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts@@ -473,6 +473,16 @@ describe('trendsChartTransforms', () => {expect((config.yAxis as YAxisConfig)?.label).toBe('Unique users')})+ it('forwards the y-axis range onto the axis config', () => {+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ yAxisStartAtZero: false,+ yAxisMin: 40,+ yAxisMax: 80,+ })+ expect(config.yAxis).toMatchObject({ startAtZero: false, min: 40, max: 80 })+ })+it('derives yAxis from buildTrendsYAxisConfig when isPercentStackView is true and passes through tooltip / showCrosshair', () => {const config = buildTrendsLineTimeSeriesConfig({...baseOpts,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.tsindex 8aad6bc597c2..3bb66b88004e 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts@@ -181,6 +181,10 @@ export interface BuildTrendsLineTimeSeriesConfigOpts<R extends TrendsResultLike>isPercentStackView: booleanisStickiness?: booleanyAxisScaleType?: string | null+ /** Y-axis range controls. See `buildTrendsYAxisConfig` for when each is honored. */+ yAxisStartAtZero?: boolean | null+ yAxisMin?: number | null+ yAxisMax?: number | nullinterval?: TimeInterval | nulltimezone?: stringallDays?: string[]@@ -215,6 +219,9 @@ export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, opts.isPercentStackView, opts.baseCurrency, {yAxisScaleType: opts.yAxisScaleType,showGrid: true,+ startAtZero: opts.yAxisStartAtZero,+ min: opts.yAxisMin,+ max: opts.yAxisMax,})const goalLineConfigs = schemaGoalLinesToConfigs(opts.goalLines)const derivedConfigs = buildDerivedConfigs(opts.results, {diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.tsindex 498afdc7c2ea..56fce9793c94 100644--- a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts+++ b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts@@ -110,4 +110,33 @@ describe('buildTrendsYAxisConfig', () => {const trendsFilter: TrendsFilter = { aggregationAxisFormat: 'currency', aggregationAxisPrefix: '$' }expect(buildTrendsYAxisConfig(trendsFilter, true, 'USD' as CurrencyCode).format).toBe('percentage_scaled')})++ // The suppression rules live only here, so these cases are their specification: a chart built+ // outside the UI never passes through the greyed-out controls that would otherwise explain them.+ const RANGE = { startAtZero: false, min: 40, max: 80 }++ it('forwards the y-axis range', () => {+ expect(buildTrendsYAxisConfig(null, false, undefined, RANGE)).toMatchObject(RANGE)+ })++ it.each([+ ['isPercentStackView', true, undefined],+ ['a logarithmic scale', false, 'log10'],+ ])('drops the y-axis range under %s', (_name, isPercentStackView, yAxisScaleType) => {+ const cfg = buildTrendsYAxisConfig(null, isPercentStackView, undefined, { ...RANGE, yAxisScaleType })+ expect(cfg.startAtZero).toBeUndefined()+ expect(cfg.min).toBeUndefined()+ expect(cfg.max).toBeUndefined()+ })++ // The library applies a bound after its own zero clamp, so forwarding both would leave the+ // toggle inert the moment a minimum was set. The maximum is unrelated and has to survive.+ it.each<[string, boolean | undefined]>([+ ['left at its default', undefined],+ ['explicitly on', true],+ ])('holds back the minimum but keeps the maximum with begin-at-zero %s', (_name, startAtZero) => {+ const cfg = buildTrendsYAxisConfig(null, false, undefined, { ...RANGE, startAtZero })+ expect(cfg.min).toBeUndefined()+ expect(cfg.max).toBe(80)+ })})diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.tsindex f3e99153e313..7e4071536f3a 100644--- a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts+++ b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts@@ -21,15 +21,57 @@ export function trendsFilterToYFormatterConfig(}}+export interface TrendsYAxisRangeOpts {+ isPercentStackView: boolean+ yAxisScaleType?: string | null+ startAtZero?: boolean | null+ min?: number | null+ max?: number | null+}++/**+ * The y-axis range a chart should actually apply. A percent stack fixes the axis to 0..1 and a log+ * axis has no zero baseline, so both veto the range; "begin at zero" vetoes just the minimum, since+ * the library applies a bound after its own zero clamp and forwarding both would leave the toggle+ * inert. Vetoed values stay in the filter, so switching the display back restores them.+ *+ * This is the only place these rules live, because a chart built from a stored query, the API, or+ * MCP never passes through the greyed-out controls that explain them.+ */+function resolveTrendsYAxisRange(opts: TrendsYAxisRangeOpts): {+ startAtZero?: boolean+ min?: number+ max?: number+} {+ if (opts.isPercentStackView || opts.yAxisScaleType === 'log10') {+ return {}+ }+ const bound = (value: number | null | undefined): number | undefined =>+ typeof value === 'number' && isFinite(value) ? value : undefined+ const beginsAtZero = opts.startAtZero !== false+ return {+ startAtZero: beginsAtZero ? undefined : false,+ min: beginsAtZero ? undefined : bound(opts.min),+ max: bound(opts.max),+ }+}+export function buildTrendsYAxisConfig(trendsFilter: YFormatterFields | null | undefined,isPercentStackView: boolean,baseCurrency: string | undefined,- extras: { yAxisScaleType?: string | null; showGrid?: boolean } = {}+ extras: {+ yAxisScaleType?: string | null+ showGrid?: boolean+ startAtZero?: boolean | null+ min?: number | null+ max?: number | null+ } = {}): YAxisConfig {return {...trendsFilterToYFormatterConfig(trendsFilter, isPercentStackView, baseCurrency),scale: extras.yAxisScaleType === 'log10' ? 'log' : 'linear',showGrid: extras.showGrid,+ ...resolveTrendsYAxisRange({ ...extras, isPercentStackView }),}}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5b32c4b0d0e1..e56c42d286f6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3225,7 +3225,13 @@ export namespace Schemas {xAxisLabel?: string | null;/** Custom label rendered alongside the Y axis. */yAxisLabel?: string | null;+ /** Pins the top of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, and when `yAxisMin` is not below it. */+ yAxisMax?: number | null;+ /** Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`. */+ yAxisMin?: number | null;yAxisScaleType?: YAxisScaleType | null;+ /** Y-axis baseline. When false the axis floats to the data range instead of starting at zero. Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while showing percentages. */+ yAxisStartAtZero?: boolean | null;}export interface TrendsQuery {