OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): conversion charts can switch the y-axis between fixed 0–100% and auto (#569)
Carl-Gerhard Lindesvärd7c259ded77cc
diff --git a/apps/start/e2e/reports-conversion-y-axis.spec.ts b/apps/start/e2e/reports-conversion-y-axis.spec.tsnew file mode 100644index 000000000..50dd3b919--- /dev/null+++ b/apps/start/e2e/reports-conversion-y-axis.spec.ts@@ -0,0 +1,65 @@+import { expect, test } from './fixtures';+import {+ addEvent,+ closeSidebar,+ openSidebar,+ pickChartType,+ shot,+ trackProblems,+ waitForChart,+} from './reports-helpers';++const SHOP = 'acme-shop';+const FIXED_LABEL = 'Fixed (0–100%)';+const PERCENT_LABEL = /^(\d+(\.\d+)?)%$/;++async function yAxisTickValues(page: Parameters<typeof shot>[0]) {+ const labels = await page+ .locator('[data-report-chart="conversion"] .text-chart-label')+ .allInnerTexts();+ return labels+ .map((label) => label.match(PERCENT_LABEL)?.[1])+ .filter((value): value is string => value !== undefined)+ .map(Number);+}++test.use({ actionTimeout: 20_000 });++test('conversion y-axis is fixed at 100% by default and auto fits the peak', async ({+ page,+}) => {+ test.setTimeout(300_000);+ const problems = trackProblems(page);+ await page.goto(`/acme/${SHOP}/reports`);+ await page.waitForLoadState('networkidle');+ // Two events first: the conversion query rejects anything less.+ await addEvent(page, 'session_start');+ await addEvent(page, 'purchase');+ await closeSidebar(page);+ await pickChartType(page, 'Linear', 'Conversion');+ await waitForChart(page);++ const sheet = await openSidebar(page);+ const yAxis = sheet.getByRole('combobox').filter({ hasText: FIXED_LABEL });+ await expect(yAxis).toBeVisible();+ await closeSidebar(page);+ await waitForChart(page);+ await shot(page, 'conversion-y-axis-01-fixed');+ await expect.poll(() => yAxisTickValues(page)).not.toHaveLength(0);+ await expect.poll(() => yAxisTickValues(page)).toContain(100);++ await openSidebar(page);+ await yAxis.click();+ await page.getByRole('option', { name: 'Auto' }).click();+ await expect(+ sheet.getByRole('combobox').filter({ hasText: 'Auto' })+ ).toBeVisible();+ await closeSidebar(page);+ await waitForChart(page);+ await shot(page, 'conversion-y-axis-02-auto');+ await expect.poll(() => yAxisTickValues(page)).not.toHaveLength(0);+ await expect.poll(() => yAxisTickValues(page)).not.toContain(100);++ expect(problems.pageErrors).toEqual([]);+ expect(problems.responses).toEqual([]);+});diff --git a/apps/start/src/components/report-chart/conversion/chart.tsx b/apps/start/src/components/report-chart/conversion/chart.tsxindex 53cde0740..c080391e3 100644--- a/apps/start/src/components/report-chart/conversion/chart.tsx+++ b/apps/start/src/components/report-chart/conversion/chart.tsx@@ -41,7 +41,15 @@ export function Chart({series: (ConversionSeries[number] & { index: number })[];}) {const {- report: { interval, projectId, startDate, endDate, range, lineType },+ report: {+ interval,+ projectId,+ startDate,+ endDate,+ range,+ lineType,+ options,+ },isEditMode,shareId,} = useReportChartContext();@@ -79,6 +87,10 @@ export function Chart({[rechartData, averageRate]);const curve = getCurve(lineType);+ const funnelOptions = options?.type === 'funnel' ? options : undefined;+ const isAutoYAxis = funnelOptions?.yAxisScale === 'auto';+ // Auto lets the chart shell add headroom above the peak; fixed pins 0–100%.+ const yDomain = isAutoYAxis ? undefined : PERCENT_DOMAIN;const formatDateLabel = useCallback((date: Date) => formatDateInterval({ interval, date, short: true }),@@ -134,7 +146,7 @@ export function Chart({margin={chrome.margin}style={{ touchAction: 'pan-y' }}xDataKey="date"- yDomain={PERCENT_DOMAIN}+ yDomain={yDomain}><Grid horizontal />{chrome.showYAxis && (diff --git a/apps/start/src/components/report/report-slice.test.ts b/apps/start/src/components/report/report-slice.test.tsindex 9f94781f0..41e34f393 100644--- a/apps/start/src/components/report/report-slice.test.ts+++ b/apps/start/src/components/report/report-slice.test.ts@@ -1,6 +1,11 @@import type { IReport } from '@openpanel/core/modules/report/report.constants';import { describe, expect, test } from 'vitest';-import reducer, { removeEvent, setReport } from './reportSlice';+import reducer, {+ changeConversionYAxisScale,+ changeFunnelWindow,+ removeEvent,+ setReport,+} from './reportSlice';const event = (id: string) => ({id,@@ -39,3 +44,25 @@ describe('breakdown step', () => {expect(state.breakdowns[0]?.step).toBe(2);});});++describe('conversion y-axis scale', () => {+ test('lives on the funnel options next to the funnel window', () => {+ const withWindow = reducer(funnelWithStep(2), changeFunnelWindow(48));+ const state = reducer(withWindow, changeConversionYAxisScale('auto'));+ expect(state.options).toEqual({+ type: 'funnel',+ funnelGroup: undefined,+ funnelWindow: 48,+ yAxisScale: 'auto',+ });+ });++ test('is unset for the fixed default', () => {+ const auto = reducer(funnelWithStep(2), changeConversionYAxisScale('auto'));+ const state = reducer(auto, changeConversionYAxisScale(undefined));+ expect(state.options?.type).toBe('funnel');+ expect(+ state.options?.type === 'funnel' ? state.options.yAxisScale : 'wrong'+ ).toBeUndefined();+ });+});diff --git a/apps/start/src/components/report/reportSlice.ts b/apps/start/src/components/report/reportSlice.tsindex 3349f7343..c640f807a 100644--- a/apps/start/src/components/report/reportSlice.ts+++ b/apps/start/src/components/report/reportSlice.ts@@ -6,6 +6,7 @@ import type {IChartMetric,IChartRange,IChartType,+ IConversionYAxisScale,IInterval,IReport,IReportOptions,@@ -352,6 +353,22 @@ export const reportSlice = createSlice({state.options.funnelWindow = action.payload;}},+ changeConversionYAxisScale(+ state,+ action: PayloadAction<IConversionYAxisScale | undefined>+ ) {+ state.dirty = true;+ if (!state.options || state.options.type !== 'funnel') {+ state.options = {+ type: 'funnel',+ funnelGroup: undefined,+ funnelWindow: undefined,+ yAxisScale: action.payload,+ };+ } else {+ state.options.yAxisScale = action.payload;+ }+ },changeOptions(state, action: PayloadAction<IReportOptions | undefined>) {state.dirty = true;state.options = action.payload || undefined;@@ -470,6 +487,7 @@ export const {changeMetric,changeFunnelGroup,changeFunnelWindow,+ changeConversionYAxisScale,changeOptions,changeSankeyMode,changeSankeySteps,diff --git a/apps/start/src/components/report/sidebar/ReportSettings.tsx b/apps/start/src/components/report/sidebar/ReportSettings.tsxindex cdc883002..2a3e1a3a6 100644--- a/apps/start/src/components/report/sidebar/ReportSettings.tsx+++ b/apps/start/src/components/report/sidebar/ReportSettings.tsx@@ -1,6 +1,11 @@-import type { IChartMetric } from '@openpanel/core/modules/report/report.constants';+import type {+ IChartMetric,+ IConversionYAxisScale,+} from '@openpanel/core/modules/report/report.constants';+import { conversionYAxisScales } from '@openpanel/core/modules/report/report.constants';import { useMemo } from 'react';import {+ changeConversionYAxisScale,changeCriteria,changeFunnelGroup,changeFunnelWindow,@@ -21,6 +26,9 @@ import { Switch } from '@/components/ui/switch';import { useAppParams } from '@/hooks/use-app-params';import { useEventNames } from '@/hooks/use-event-names';import { useDispatch, useSelector } from '@/redux';+import { objectToZodEnums } from '@/utils/object-to-zod-enums';++const DEFAULT_CONVERSION_Y_AXIS_SCALE: IConversionYAxisScale = 'fixed';export function ReportSettings() {const chartType = useSelector((state) => state.report.chartType);@@ -35,6 +43,8 @@ export function ReportSettings() {const funnelOptions = options?.type === 'funnel' ? options : undefined;const funnelGroup = funnelOptions?.funnelGroup;const funnelWindow = funnelOptions?.funnelWindow;+ const conversionYAxisScale =+ funnelOptions?.yAxisScale ?? DEFAULT_CONVERSION_Y_AXIS_SCALE;const histogramOptions = options?.type === 'histogram' ? options : undefined;const stacked = histogramOptions?.stacked ?? false;@@ -44,7 +54,7 @@ export function ReportSettings() {const eventNames = useEventNames({ projectId });const fields = useMemo(() => {- const fields = [];+ const fields: string[] = [];if (chartType !== 'retention' && chartType !== 'sankey') {fields.push('previous');@@ -60,6 +70,10 @@ export function ReportSettings() {fields.push('funnelWindow');}+ if (chartType === 'conversion') {+ fields.push('conversionYAxisScale');+ }+if (chartType === 'sankey') {fields.push('sankeyMode');fields.push('sankeySteps');@@ -212,6 +226,27 @@ export function ReportSettings() {/></div>)}+ {fields.includes('conversionYAxisScale') && (+ <div className="flex items-center justify-between gap-4">+ <Label className="mb-0 whitespace-nowrap font-medium">Y axis</Label>+ <Combobox+ align="end"+ items={objectToZodEnums(conversionYAxisScales).map((key) => ({+ label: conversionYAxisScales[key],+ value: key,+ }))}+ onChange={(val) => {+ dispatch(+ changeConversionYAxisScale(+ val === DEFAULT_CONVERSION_Y_AXIS_SCALE ? undefined : val+ )+ );+ }}+ placeholder="Default: Fixed"+ value={conversionYAxisScale}+ />+ </div>+ )}{fields.includes('sankeyMode') && options?.type === 'sankey' && (<div className="flex items-center justify-between gap-4"><Label className="mb-0 whitespace-nowrap font-medium">Mode</Label>diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.tsindex 4d4f9809c..99ee1a455 100644--- a/packages/core/src/modules/report/report.constants.ts+++ b/packages/core/src/modules/report/report.constants.ts@@ -838,10 +838,21 @@ export const zRange = z.enum(objectToZodEnums(timeWindows));export const zCriteria = z.enum(['on_or_after', 'on']);+export const conversionYAxisScales = {+ fixed: 'Fixed (0–100%)',+ auto: 'Auto',+} as const;+export const zConversionYAxisScale = z.enum(+ objectToZodEnums(conversionYAxisScales)+);+export type IConversionYAxisScale = z.infer<typeof zConversionYAxisScale>;++// Conversion reports share the funnel options (group, window) and add a y-axis scale.export const zFunnelOptions = z.object({type: z.literal('funnel'),funnelGroup: z.string().optional(),funnelWindow: z.number().optional(),+ yAxisScale: zConversionYAxisScale.optional(),});export const zRetentionOptions = z.object({