Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(insights): group chart options into tabs (#98615)

Sam Pennington89e285575c16
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
index e731bdb9a654..18d454beda67 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
@@ -1,26 +1,42 @@
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
+import { LemonMenuItems, LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu'
+
+import { DisplayOptionTab } from '~/queries/nodes/InsightViz/insightDisplayOptions'
+import { InsightDisplayOptionsPanel } from '~/queries/nodes/InsightViz/InsightDisplayOptionsPanel'
// Items are computed in InsightMeta (always mounted) and passed down to avoid mounting
// useInsightDisplayOptions lazily inside the More popover overlay, which triggers kea logic
// mounts that cascade and close the popover before the user can interact with it.
-export function DashboardInsightDisplayOptions({ items }: { items: LemonMenuItems }): JSX.Element | null {
- if (items.length === 0) {
+export function DashboardInsightDisplayOptions({
+ visualizationItems,
+ tabs,
+}: {
+ visualizationItems: LemonMenuItems
+ tabs: DisplayOptionTab[]
+}): JSX.Element | null {
+ if (visualizationItems.length === 0 && tabs.length === 0) {
return null
}
return (
<>
<LemonDivider />
- <LemonMenu
- items={items}
+ <LemonDropdown
+ overlay={
+ <>
+ {visualizationItems.length > 0 && <LemonMenuOverlay items={visualizationItems} />}
+ {visualizationItems.length > 0 && tabs.length > 0 && <LemonDivider />}
+ <InsightDisplayOptionsPanel tabs={tabs} />
+ </>
+ }
closeOnClickInside={false}
placement="right-start"
fallbackPlacements={['left-start']}
>
<LemonButton fullWidth>Display options</LemonButton>
- </LemonMenu>
+ </LemonDropdown>
</>
)
}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index b670673487d5..bbdcb97d1424 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -253,7 +253,7 @@ export function InsightMeta({
const showDisplayOptionsMenu = isUsedAsDashboardTile && canEditInsight && !!persistDisplayOptions
// Hoist the hooks out of the More overlay so kea logics they mount don't do so lazily inside a
// portal, which cascades into closing the dropdown before the user can interact with it.
- const { items: displayOptionItems } = useInsightDisplayOptions()
+ const { tabs: displayOptionTabs } = useInsightDisplayOptions()
const dashboardVisualizationPersistence: DashboardVisualizationPersistence | undefined = persistDisplayOptions
? {
saving: savingSqlVisualization,
@@ -271,7 +271,6 @@ export function InsightMeta({
persistence: dashboardVisualizationPersistence,
savingDisplayOptions,
})
- const displayMenuItems = [...visualizationItems, ...displayOptionItems]
const hasTileStyleActions = !!(showCompactTile && toggleShowDescription && insight.description) || !!updateColor
const canShowCopyToDashboardTile = showCompactTile && !!copyToDashboard && canViewInsight
@@ -550,7 +549,12 @@ export function InsightMeta({
Alerts
</LemonButton>
) : null}
- {showDisplayOptionsMenu && <DashboardInsightDisplayOptions items={displayMenuItems} />}
+ {showDisplayOptionsMenu && (
+ <DashboardInsightDisplayOptions
+ visualizationItems={visualizationItems}
+ tabs={displayOptionTabs}
+ />
+ )}
{canShowCopyToDashboardTile && !canEditDashboard && (
<>
diff --git a/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx
index 0569cb104b40..dbf728f95f80 100644
--- a/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx
+++ b/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx
@@ -4,13 +4,12 @@ import { ReactNode } from 'react'
import { useDebouncedCallback } from 'use-debounce'
import { IconInfo } from '@posthog/icons'
-import { LemonCheckbox, LemonInput, LemonSwitch, Tooltip } from '@posthog/lemon-ui'
+import { LemonCheckbox, LemonInput, Tooltip } from '@posthog/lemon-ui'
import { SmoothingFilter } from 'lib/components/SmoothingFilter/SmoothingFilter'
import { UnitPicker } from 'lib/components/UnitPicker/UnitPicker'
-import { LemonMenuItem } from 'lib/lemon-ui/LemonMenu'
import { DEFAULT_DECIMAL_PLACES } from 'lib/utils/numbers'
-import { AxisLabelsFilter } from 'scenes/insights/EditorFilters/AxisLabelsFilter'
+import { AxisLabelFilter } from 'scenes/insights/EditorFilters/AxisLabelFilter'
import { HideIncompleteConversionWindowPeriodsFilter } from 'scenes/insights/EditorFilters/HideIncompleteConversionWindowPeriodsFilter'
import { LegendOptionsFilter } from 'scenes/insights/EditorFilters/LegendOptionsFilter'
import { LifecyclePercentagesFilter } from 'scenes/insights/EditorFilters/LifecyclePercentagesFilter'
@@ -104,10 +103,10 @@ function ConfidenceInterval(): JSX.Element {
const { isLineGraph, isLinearScale } = useLineGraphState()
return (
- <LemonSwitch
- label="Show confidence intervals"
- className="pb-2"
- fullWidth
+ <LemonCheckbox
+ label={<span className="font-normal">Show confidence intervals</span>}
+ className="p-1 px-2"
+ size="small"
checked={showConfidenceIntervals}
disabledReason={
!isLineGraph
@@ -135,10 +134,10 @@ function MovingAverage(): JSX.Element {
const { isLineGraph, isLinearScale } = useLineGraphState()
return (
- <LemonSwitch
- label="Show moving average"
- className="pb-2"
- fullWidth
+ <LemonCheckbox
+ label={<span className="font-normal">Show moving average</span>}
+ className="p-1 px-2"
+ size="small"
checked={showMovingAverage}
disabledReason={
!isLineGraph
@@ -211,40 +210,43 @@ export function SectionHeader({
)
}
-// Every insight display toggle as a ready-to-use menu item, so callers assemble the Options menu by
-// referencing `DisplayOptions.X` instead of repeating `{ label: () => <X /> }` for each one.
+// Every insight display toggle, keyed so the Options panel is assembled by referencing
+// `DisplayOptions.X` instead of importing each filter component.
export const DisplayOptions = {
- Smoothing: { label: () => <Smoothing /> },
- Legend: { label: () => <ShowLegendFilter /> },
- LegendOptions: { label: () => <LegendOptionsFilter /> },
- ExcludeOutliers: { label: () => <ExcludeOutliers /> },
- MetricSummary: { label: () => <MetricSummaryFilter /> },
- MetricShowChange: { label: () => <MetricShowChangeFilter /> },
- MetricColor: { label: () => <MetricColorFilter /> },
- LifecycleStacking: { label: () => <LifecycleStackingFilter /> },
- LifecyclePercentages: { label: () => <LifecyclePercentagesFilter /> },
- ValueLabels: { label: () => <ValueOnSeriesFilter /> },
- PercentStack: { label: () => <PercentStackViewFilter /> },
- StackBreakdown: { label: () => <StackBreakdownFilter /> },
- SliceNames: { label: () => <SliceNamesFilter /> },
- PieTotal: { label: () => <ShowPieTotalFilter /> },
- AlertThresholdLines: { label: () => <ShowAlertThresholdLinesFilter /> },
- AlertAnomalyPoints: { label: () => <ShowAlertAnomalyPointsFilter /> },
- MultipleYAxes: { label: () => <ShowMultipleYAxesFilter /> },
- TrendLines: { label: () => <ShowTrendLinesFilter /> },
- HideIncompleteFunnelPeriods: { label: () => <HideIncompleteConversionWindowPeriodsFilter /> },
- Annotations: { label: () => <ShowAnnotationsFilter /> },
- ResultCustomizationBy: { label: () => <ResultCustomizationByPicker /> },
- Unit: { label: () => <UnitPicker /> },
- Scale: { label: () => <ScalePicker /> },
- YAxisRange: { label: () => <YAxisRangeFilter /> },
- LineStyle: { label: () => <LineStylePicker /> },
- ConfidenceInterval: { label: () => <ConfidenceInterval /> },
- ConfidenceLevel: { label: () => <ConfidenceLevelInput /> },
- MovingAverage: { label: () => <MovingAverage /> },
- MovingAverageIntervals: { label: () => <MovingAverageIntervalsInput /> },
- AxisLabels: { label: () => <AxisLabelsFilter /> },
- DecimalPrecision: { label: () => <DecimalPrecision /> },
- RetentionDashboardDisplay: { label: () => <RetentionDashboardDisplayPicker /> },
- RetentionCohortLabelStart: { label: () => <RetentionCohortLabelStartIndexPicker /> },
-} satisfies Record<string, LemonMenuItem>
+ Smoothing,
+ Legend: ShowLegendFilter,
+ LegendOptions: LegendOptionsFilter,
+ ExcludeOutliers,
+ MetricSummary: MetricSummaryFilter,
+ MetricShowChange: MetricShowChangeFilter,
+ MetricColor: MetricColorFilter,
+ LifecycleStacking: LifecycleStackingFilter,
+ LifecyclePercentages: LifecyclePercentagesFilter,
+ ValueLabels: ValueOnSeriesFilter,
+ PercentStack: PercentStackViewFilter,
+ StackBreakdown: StackBreakdownFilter,
+ SliceNames: SliceNamesFilter,
+ PieTotal: ShowPieTotalFilter,
+ AlertThresholdLines: ShowAlertThresholdLinesFilter,
+ AlertAnomalyPoints: ShowAlertAnomalyPointsFilter,
+ MultipleYAxes: ShowMultipleYAxesFilter,
+ TrendLines: ShowTrendLinesFilter,
+ HideIncompleteFunnelPeriods: HideIncompleteConversionWindowPeriodsFilter,
+ Annotations: ShowAnnotationsFilter,
+ ResultCustomizationBy: ResultCustomizationByPicker,
+ Unit: UnitPicker,
+ Scale: ScalePicker,
+ YAxisRange: YAxisRangeFilter,
+ LineStyle: LineStylePicker,
+ ConfidenceInterval,
+ ConfidenceLevel: ConfidenceLevelInput,
+ MovingAverage,
+ MovingAverageIntervals: MovingAverageIntervalsInput,
+ XAxisLabel: () => <AxisLabelFilter axis="x" />,
+ YAxisLabel: () => <AxisLabelFilter axis="y" />,
+ DecimalPrecision,
+ RetentionDashboardDisplay: RetentionDashboardDisplayPicker,
+ RetentionCohortLabelStart: RetentionCohortLabelStartIndexPicker,
+} satisfies Record<string, () => JSX.Element | null>
+
+export type DisplayOption = (typeof DisplayOptions)[keyof typeof DisplayOptions]
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
index a21b3f12fe8e..040d22ef1d8a 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
@@ -69,8 +69,31 @@ function makeLifecycleQuery(): LifecycleQuery {
}
}
+function normalizeText(text: string | null | undefined): string {
+ return text?.replace(/\s+/g, ' ').trim() ?? ''
+}
+
+function getPanel(): HTMLElement {
+ return screen.getByTestId('insight-display-options-panel')
+}
+
+function getTabLabels(): string[] {
+ return within(getPanel())
+ .queryAllByRole('tab')
+ .map((tab) => normalizeText(tab.textContent))
+}
+
+async function openTab(label: string): Promise<void> {
+ const tab = within(getPanel())
+ .getAllByRole('tab')
+ .find((el) => normalizeText(el.textContent).startsWith(label))!
+ await userEvent.click(tab)
+}
+
function getSectionTitles(): string[] {
- return screen.getAllByRole('heading', { level: 5 }).map((h) => h.textContent?.replace(/\s+/g, ' ').trim() ?? '')
+ return within(getPanel())
+ .queryAllByRole('heading', { level: 5 })
+ .map((h) => normalizeText(h.textContent))
}
async function openOptionsMenu(): Promise<void> {
@@ -78,10 +101,16 @@ async function openOptionsMenu(): Promise<void> {
await userEvent.click(optionsButtons[0])
}
+function getSectionItems(dataAttr: string): string[] {
+ const section = screen.getByTestId(dataAttr).closest('section')!
+ return within(section)
+ .queryAllByRole('listitem')
+ .map((li) => normalizeText(li.textContent))
+ .filter(Boolean)
+}
+
function getDisplaySectionItems(): string[] {
- const displaySection = screen.getByTestId('options-display-section').closest('section')!
- const listItems = within(displaySection).queryAllByRole('listitem')
- return listItems.map((li) => li.textContent?.trim() || '').filter(Boolean)
+ return getSectionItems('options-display-section')
}
describe('InsightDisplayConfig', () => {
@@ -116,78 +145,82 @@ describe('InsightDisplayConfig', () => {
)
}
- describe('Options menu sections per insight/chart type', () => {
- const cases: [string, InsightQueryNode, { sections: string[]; displayItems?: string[] }][] = [
+ describe('Options panel tabs and sections per insight/chart type', () => {
+ type Expected = {
+ tabs: string[]
+ sections: Partial<Record<string, string[]>>
+ displayItems?: string[]
+ overlayItems?: string[]
+ }
+ const lineOverlays = [
+ 'Show trend lines',
+ 'Show moving average',
+ 'Show confidence intervals',
+ 'Show alert threshold lines',
+ ]
+ const cases: [string, InsightQueryNode, Expected][] = [
[
'trends line graph',
makeTrendsQuery(ChartDisplayType.ActionsLineGraph),
{
- sections: [
- 'Display',
- 'Color customization by',
- 'Y-axis unit',
- 'Y-axis scale',
- 'Y-axis range',
- 'Line style',
- 'Statistical analysis',
- 'Axis labels',
- ],
- displayItems: [
- 'Show values on series',
- 'Show alert threshold lines',
- 'Show multiple Y-axes',
- 'Show trend lines',
- 'Show annotations',
- 'Show legendBottom',
- ],
+ tabs: ['General', 'Axes', 'Lines'],
+ sections: {
+ General: ['Unit', 'Color customization by'],
+ Axes: ['X-axis', 'Y-axis'],
+ Lines: ['Style', 'Overlays'],
+ },
+ displayItems: ['Show values on series', 'Show annotations', 'Show legendBottom'],
+ overlayItems: lineOverlays,
},
],
[
'trends bar chart',
makeTrendsQuery(ChartDisplayType.ActionsBar),
{
- sections: ['Display', 'Y-axis unit', 'Y-axis scale', 'Statistical analysis', 'Axis labels'],
+ tabs: ['General', 'Axes', 'Lines'],
+ sections: {
+ General: ['Unit'],
+ Axes: ['X-axis', 'Y-axis'],
+ Lines: ['Overlays'],
+ },
displayItems: [
'Show values on series',
'Show as % of total',
- 'Show alert threshold lines',
- 'Show multiple Y-axes',
- 'Show trend lines',
'Show annotations',
'Show legendBottom',
],
+ overlayItems: lineOverlays,
},
],
[
'trends area graph',
makeTrendsQuery(ChartDisplayType.ActionsAreaGraph),
{
- sections: [
- 'Display',
- 'Y-axis unit',
- 'Y-axis scale',
- 'Y-axis range',
- 'Line style',
- 'Statistical analysis',
- 'Axis labels',
- ],
+ tabs: ['General', 'Axes', 'Lines'],
+ sections: {
+ General: ['Unit'],
+ Axes: ['X-axis', 'Y-axis'],
+ Lines: ['Style', 'Overlays'],
+ },
displayItems: [
'Show values on series',
'Show as % of total',
- 'Show alert threshold lines',
- 'Show multiple Y-axes',
- 'Show trend lines',
'Show annotations',
'Show legendBottom',
],
},
],
- ['trends number', makeTrendsQuery(ChartDisplayType.BoldNumber), { sections: ['Unit'] }],
+ [
+ 'trends number',
+ makeTrendsQuery(ChartDisplayType.BoldNumber),
+ { tabs: [], sections: { General: ['Unit'] } },
+ ],
[
'trends pie',
makeTrendsQuery(ChartDisplayType.ActionsPie),
{
- sections: ['Display', 'Unit'],
+ tabs: [],
+ sections: { General: ['Unit'] },
displayItems: [
'Show values on series',
'Show as % of total',
@@ -202,7 +235,8 @@ describe('InsightDisplayConfig', () => {
'trends donut',
makeTrendsQuery(ChartDisplayType.ActionsDonut),
{
- sections: ['Display', 'Unit'],
+ tabs: [],
+ sections: { General: ['Unit'] },
displayItems: [
'Show values on series',
'Show as % of total',
@@ -212,45 +246,64 @@ describe('InsightDisplayConfig', () => {
],
},
],
- ['trends table', makeTrendsQuery(ChartDisplayType.ActionsTable), { sections: ['Unit'] }],
+ [
+ 'trends table',
+ makeTrendsQuery(ChartDisplayType.ActionsTable),
+ { tabs: [], sections: { General: ['Unit'] } },
+ ],
[
'trends bar value (horizontal)',
makeTrendsQuery(ChartDisplayType.ActionsBarValue),
- { sections: ['Display', 'X-axis unit', 'Axis labels'], displayItems: ['Show values on series'] },
+ {
+ tabs: ['General', 'Axes'],
+ sections: { General: ['Unit'], Axes: ['X-axis', 'Y-axis'] },
+ displayItems: ['Show values on series'],
+ },
+ ],
+ [
+ 'trends world map',
+ makeTrendsQuery(ChartDisplayType.WorldMap),
+ { tabs: [], sections: { General: ['Unit'] } },
],
- ['trends world map', makeTrendsQuery(ChartDisplayType.WorldMap), { sections: ['Unit'] }],
[
'box plot',
makeTrendsQuery(ChartDisplayType.BoxPlot),
- { sections: ['Display', 'Unit', 'Y-axis scale'], displayItems: ['Show legend', 'Exclude outliers'] },
+ {
+ tabs: ['General', 'Axes'],
+ sections: { General: ['Unit'], Axes: ['Y-axis'] },
+ displayItems: ['Show legend', 'Exclude outliers'],
+ },
],
[
'slope graph',
makeTrendsQuery(ChartDisplayType.SlopeGraph),
- { sections: ['Display', 'Unit'], displayItems: ['Show legend'] },
+ { tabs: [], sections: { General: ['Unit'] }, displayItems: ['Show legend'] },
],
[
'retention',
makeRetentionQuery(),
{
- sections: ['Display', 'Line style', 'On dashboards', 'Cohort labels start at'],
- displayItems: ['Show trend lines'],
+ tabs: [],
+ sections: { General: ['On dashboards', 'Cohort labels start at', 'Style', 'Overlays'] },
+ overlayItems: ['Show trend lines'],
},
],
[
'stickiness',
makeStickinessQuery(),
{
- sections: ['Display', 'Line style'],
- displayItems: ['Show values on series', 'Show multiple Y-axes', 'Show legendBottom'],
+ tabs: [],
+ sections: { General: ['Y-axis', 'Style'] },
+ displayItems: ['Show values on series', 'Show legendBottom'],
},
],
- ['stickiness table', makeStickinessQuery(ChartDisplayType.ActionsTable), { sections: [] }],
+ ['stickiness table', makeStickinessQuery(ChartDisplayType.ActionsTable), { tabs: [], sections: {} }],
[
'lifecycle',
makeLifecycleQuery(),
{
- sections: ['Display'],
+ tabs: [],
+ sections: { General: [] },
displayItems: [
'Stack bars',
'Show values on series',
@@ -261,87 +314,85 @@ describe('InsightDisplayConfig', () => {
],
]
- it.each(cases)('%s shows the expected sections and display options', async (_name, query, expected) => {
+ it.each(cases)('%s shows the expected tabs, sections and items', async (_name, query, expected) => {
setupAndRender(query)
- if (expected.sections.length === 0) {
+ if (Object.keys(expected.sections).length === 0) {
expect(screen.queryByLabelText('Options')).not.toBeInTheDocument()
return
}
await openOptionsMenu()
-
- expect(getSectionTitles()).toEqual(expected.sections)
- if (!expected.displayItems) {
- expect(screen.queryByTestId('options-display-section')).not.toBeInTheDocument()
- } else {
- expect(getDisplaySectionItems()).toEqual(expected.displayItems)
+ expect(getTabLabels()).toEqual(expected.tabs)
+
+ for (const [tab, titles] of Object.entries(expected.sections)) {
+ if (expected.tabs.length > 0) {
+ await openTab(tab)
+ }
+ expect(getSectionTitles()).toEqual(titles)
+ if (tab === 'General') {
+ if (!expected.displayItems) {
+ expect(screen.queryByTestId('options-display-section')).not.toBeInTheDocument()
+ } else {
+ expect(getDisplaySectionItems()).toEqual(expected.displayItems)
+ }
+ }
+ if ((tab === 'Lines' || expected.tabs.length === 0) && expected.overlayItems) {
+ expect(getSectionItems('options-overlays-section')).toEqual(expected.overlayItems)
+ }
}
})
})
- describe('section header tooltips', () => {
- it('renders an info tooltip on tooltip-backed headers but not on plain ones', async () => {
- setupAndRender(makeRetentionQuery())
- await openOptionsMenu()
-
- const tooltipHeader = screen.getByText('Cohort labels start at').closest('h5')!
- expect(tooltipHeader.querySelector('svg')).toBeInTheDocument()
-
- const plainHeader = screen.getByText('On dashboards').closest('h5')!
- expect(plainHeader.querySelector('svg')).not.toBeInTheDocument()
- })
- })
+ describe('options count', () => {
+ it('sums non-default options across every tab, but keeps tab labels fixed', async () => {
+ setupAndRender(
+ makeTrendsQuery(ChartDisplayType.ActionsLineGraph, {
+ showValuesOnSeries: true,
+ showAnnotations: false,
+ yAxisScaleType: 'log10',
+ showTrendLines: true,
+ })
+ )
+ expect(screen.getAllByLabelText('Options')[0]).toHaveTextContent(/\(4\)/)
- describe('box plot display options', () => {
- it('only shows "Show legend" in the Display section', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.BoxPlot))
await openOptionsMenu()
-
- const items = getDisplaySectionItems()
- expect(items).toEqual(['Show legend', 'Exclude outliers'])
+ expect(getTabLabels()).toEqual(['General', 'Axes', 'Lines'])
})
+ })
- it('shows unit picker and Y-axis scale but not statistical analysis', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.BoxPlot))
+ describe('overlays tab', () => {
+ it('shows the moving average window and confidence level inputs only while their overlay is on', async () => {
+ setupAndRender(
+ makeTrendsQuery(ChartDisplayType.ActionsLineGraph, {
+ showMovingAverage: true,
+ showConfidenceIntervals: true,
+ })
+ )
await openOptionsMenu()
-
- expect(screen.getByText('Y-axis scale')).toBeInTheDocument()
- expect(screen.queryByText('Statistical analysis')).not.toBeInTheDocument()
+ await openTab('Lines')
+
+ expect(getSectionItems('options-overlays-section')).toEqual([
+ 'Show trend lines',
+ 'Show moving average',
+ 'Intervalsdays',
+ 'Show confidence intervals',
+ 'Confidence level%',
+ 'Show alert threshold lines',
+ ])
})
})
- describe('slope graph display options', () => {
- it('shows the "group by time period" interval picker — grouping defines the slope', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
- expect(screen.getByText(/grouped/i)).toBeInTheDocument()
- })
-
- it('hides the compare picker', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
- expect(screen.queryByText(/Compare to|Previous period/i)).not.toBeInTheDocument()
- })
-
- it('shows only the legend in the Display section', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
+ describe('section header tooltips', () => {
+ it('renders an info tooltip on tooltip-backed headers but not on plain ones', async () => {
+ setupAndRender(makeRetentionQuery())
await openOptionsMenu()
- const items = getDisplaySectionItems()
- expect(items).toEqual(['Show legend'])
- // None of the time-series-only options should leak in.
- expect(items).not.toContain('Show values on series')
- expect(items).not.toContain('Show trend lines')
- expect(items).not.toContain('Show alert threshold lines')
- expect(items).not.toContain('Show multiple Y-axes')
- expect(items).not.toContain('Show annotations')
- })
-
- it('hides the Y-axis scale and statistical analysis sections', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
- await openOptionsMenu()
+ const tooltipHeader = screen.getByText('Cohort labels start at').closest('h5')!
+ expect(tooltipHeader.querySelector('svg')).toBeInTheDocument()
- expect(screen.queryByText('Y-axis scale')).not.toBeInTheDocument()
- expect(screen.queryByText('Statistical analysis')).not.toBeInTheDocument()
+ const plainHeader = screen.getByText('On dashboards').closest('h5')!
+ expect(plainHeader.querySelector('svg')).not.toBeInTheDocument()
})
})
@@ -351,24 +402,6 @@ describe('InsightDisplayConfig', () => {
expect(screen.getByText(/grouped/i)).toBeInTheDocument()
})
- it('shows multiple options in the Display section', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))
- await openOptionsMenu()
-
- const items = getDisplaySectionItems()
- expect(items.some((item) => item.includes('Show legend'))).toBe(true)
- expect(items).toContain('Show values on series')
- expect(items).toContain('Show alert threshold lines')
- expect(items).toContain('Show trend lines')
- })
-
- it('shows Y-axis scale section', async () => {
- setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))
- await openOptionsMenu()
-
- expect(screen.getByText('Y-axis scale')).toBeInTheDocument()
- })
-
it('removes axis label option count after clearing a committed label', async () => {
setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph, { xAxisLabel: 'Signup date' }))
@@ -376,7 +409,8 @@ describe('InsightDisplayConfig', () => {
expect(optionsButton).toHaveTextContent(/\(1\)/)
await openOptionsMenu()
- const input = await screen.findByPlaceholderText('X-axis label')
+ await openTab('Axes')
+ const input = await screen.findByTestId('trends-x-axis-label-input')
await userEvent.clear(input)
expect(optionsButton).toHaveTextContent(/\(1\)/)
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index a53ac87f7925..1fd6274b0fb2 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -8,7 +8,7 @@ import { ChartFilter } from 'lib/components/ChartFilter'
import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
import { IntervalFilter } from 'lib/components/IntervalFilter'
import { NON_TIME_SERIES_DISPLAY_TYPES } from 'lib/constants'
-import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
import { alignResolvedDateRangeToInterval, formatResolvedDateRange } from 'lib/utils/datetime'
import { InsightDateFilter } from 'scenes/insights/filters/InsightDateFilter'
import { RetentionChartPicker } from 'scenes/insights/filters/RetentionChartPicker'
@@ -26,6 +26,7 @@ import { funnelDataLogic } from 'products/product_analytics/frontend/insights/fu
import { RetentionBreakdownFilter } from 'products/product_analytics/frontend/insights/retention/filters/RetentionBreakdownFilter'
import { useInsightDisplayOptions } from './insightDisplayOptions'
+import { InsightDisplayOptionsPanel } from './InsightDisplayOptionsPanel'
export function InsightDisplayConfig(): JSX.Element {
const { insightProps, canEditInsight, editingDisabledReason } = useValues(insightLogic)
@@ -69,7 +70,7 @@ export function InsightDisplayConfig(): JSX.Element {
isLifecycle ||
((isTrends || isStickiness) && !(display && NON_TIME_SERIES_DISPLAY_TYPES.includes(display)))
- const { items: advancedOptions, count: advancedOptionsCount } = useInsightDisplayOptions()
+ const { tabs: displayOptionTabs, count: advancedOptionsCount } = useInsightDisplayOptions()
return (
<div
@@ -117,9 +118,13 @@ export function InsightDisplayConfig(): JSX.Element {
)}
</div>
<div className="flex items-center gap-x-2">
- {advancedOptions.length > 0 && (
+ {displayOptionTabs.length > 0 && (
<>
- <LemonMenu items={advancedOptions} closeOnClickInside={false} placement="bottom-end">
+ <LemonDropdown
+ overlay={<InsightDisplayOptionsPanel tabs={displayOptionTabs} />}
+ closeOnClickInside={false}
+ placement="bottom-end"
+ >
<LemonButton
size="small"
disabledReason={editingDisabledReason}
@@ -135,8 +140,12 @@ export function InsightDisplayConfig(): JSX.Element {
) : null}
</span>
</LemonButton>
- </LemonMenu>
- <LemonMenu items={advancedOptions} closeOnClickInside={false} placement="bottom-end">
+ </LemonDropdown>
+ <LemonDropdown
+ overlay={<InsightDisplayOptionsPanel tabs={displayOptionTabs} />}
+ closeOnClickInside={false}
+ placement="bottom-end"
+ >
<LemonButton
size="small"
disabledReason={editingDisabledReason}
@@ -144,7 +153,7 @@ export function InsightDisplayConfig(): JSX.Element {
aria-label="Options"
className="hidden @max-[780px]:flex order-[999]"
/>
- </LemonMenu>
+ </LemonDropdown>
</>
)}
{supportsDisplay && (
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayOptionsPanel.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayOptionsPanel.tsx
new file mode 100644
index 000000000000..63fd498896f3
--- /dev/null
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayOptionsPanel.tsx
@@ -0,0 +1,79 @@
+import { useState } from 'react'
+
+import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { cn } from 'lib/utils/css-classes'
+
+import { SectionHeader } from './DisplayOptions'
+import { DisplayOptionSection, DisplayOptionTab, DisplayOptionTabKey } from './insightDisplayOptions'
+
+function DisplayOptionSectionList({ sections }: { sections: DisplayOptionSection[] }): JSX.Element {
+ return (
+ <ul>
+ {sections.map((section) => (
+ <li key={section.key}>
+ <section className="deprecated-space-y-px">
+ {section.title && (
+ <SectionHeader tooltip={section.tooltip} dataAttr={section.dataAttr}>
+ {section.title}
+ </SectionHeader>
+ )}
+ <ul className="deprecated-space-y-px" data-attr={section.title ? undefined : section.dataAttr}>
+ {section.items.map((Item, index) => (
+ <li key={index}>
+ <Item />
+ </li>
+ ))}
+ </ul>
+ </section>
+ </li>
+ ))}
+ </ul>
+ )
+}
+
+export function InsightDisplayOptionsPanel({ tabs }: { tabs: DisplayOptionTab[] }): JSX.Element | null {
+ const [activeKey, setActiveKey] = useState<DisplayOptionTabKey>(tabs[0]?.key ?? 'general')
+ const activeTab = tabs.find((tab) => tab.key === activeKey) ?? tabs[0]
+
+ if (!activeTab) {
+ return null
+ }
+
+ if (tabs.length === 1) {
+ return (
+ <div className="py-1" data-attr="insight-display-options-panel">
+ <DisplayOptionSectionList sections={activeTab.sections} />
+ </div>
+ )
+ }
+
+ return (
+ <div className="py-1" data-attr="insight-display-options-panel">
+ <LemonTabs
+ size="small"
+ activeKey={activeTab.key}
+ onChange={setActiveKey}
+ barClassName="mx-2 mb-1 overflow-x-visible"
+ data-attr="insight-display-options-tabs"
+ tabs={tabs.map((tab) => ({
+ key: tab.key,
+ label: tab.label,
+ 'data-attr': `insight-display-options-tab-${tab.key}`,
+ }))}
+ />
+ {/* Inactive tabs stay mounted at zero height so the widest tab sets the panel width for all of them */}
+ {tabs.map((tab) => {
+ const isActive = tab.key === activeTab.key
+ return (
+ <div
+ key={tab.key}
+ className={cn(!isActive && 'invisible h-0 overflow-hidden')}
+ aria-hidden={!isActive || undefined}
+ >
+ <DisplayOptionSectionList sections={tab.sections} />
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx
index 6c05ac8827d5..34f9a0d22cb8 100644
--- a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx
+++ b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx
@@ -4,8 +4,6 @@ import { normalizeAxisLabel } from '@posthog/quill-charts'
import { smoothingOptions } from 'lib/components/SmoothingFilter/smoothings'
import { PIE_DISPLAY_TYPES } from 'lib/constants'
-import { LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
-import { axisLabel } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
@@ -16,12 +14,33 @@ import { ChartDisplayType } from '~/types'
import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'
-import { DisplayOptions, SectionHeader } from './DisplayOptions'
+import { DisplayOption, DisplayOptions } 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.
-export function useInsightDisplayOptions(): { items: LemonMenuItems; count: number } {
+export interface DisplayOptionSection {
+ key: string
+ title?: string
+ tooltip?: string
+ dataAttr?: string
+ items: DisplayOption[]
+}
+
+export type DisplayOptionTabKey = 'general' | 'axes' | 'lines'
+
+export interface DisplayOptionTab {
+ key: DisplayOptionTabKey
+ label: string
+ sections: DisplayOptionSection[]
+ count: number
+}
+
+function countTruthy(...flags: (boolean | null | undefined)[]): number {
+ return flags.filter(Boolean).length
+}
+
+// The "Options" panel in the insight editor's display config bar. `count` is the total number of
+// non-default active options across all tabs, badged on the Options button.
+export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: number } {
const { insightProps } = useValues(insightLogic)
const {
querySource,
@@ -41,6 +60,7 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb
supportsResultCustomizationBy,
yAxisScaleType,
showMultipleYAxes,
+ showAlertThresholdLines,
showAnnotations,
isNonTimeSeriesDisplay,
interval,
@@ -60,6 +80,7 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb
// between them (smoothing, multiple axes, alert/annotation overlays, statistical analysis).
const isSlopeGraph = display === ChartDisplayType.SlopeGraph
const isMetric = display === ChartDisplayType.Metric
+ const isBoxPlot = display === ChartDisplayType.BoxPlot
const hideContinuousChartOptions = isNonTimeSeriesDisplay || isMetric || isSlopeGraph
const showSmoothing =
isTrends &&
@@ -67,9 +88,10 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb
(!display || display === ChartDisplayType.ActionsLineGraph || display === ChartDisplayType.ActionsAreaGraph) &&
!!interval &&
(smoothingOptions[interval]?.length ?? 0) > 0
- const showMultipleYAxesConfig = (isTrends || isStickiness) && !hideContinuousChartOptions
+ const showMultipleYAxesConfig = (isTrends || isStickiness) && !hideContinuousChartOptions && !isBoxPlot
const showAlertThresholdLinesConfig = isTrends && !hideContinuousChartOptions
const showAnnotationsConfig = (isTrends && !hideContinuousChartOptions) || isTrendsFunnel
+ const showTrendLinesConfig = (isTrends || isRetention || isTrendsFunnel) && !hideContinuousChartOptions
// Stickiness defaults to its line chart when display is unset, same as trends does — but
// isDefaultTrendsLineDisplay only matches TrendsQuery, so we handle the stickiness case here.
const isLineDisplay =
@@ -79,7 +101,6 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb
const isBarDisplay = displayMatches(display, BAR_DISPLAYS)
const showAxisLabelsConfig = isTrends && (isLineDisplay || isBarDisplay)
const showFunnelLegendConfig = isTrendsFunnel && hasBreakdownFilter(breakdownFilter)
- const isBoxPlot = display === ChartDisplayType.BoxPlot
const isCalendarHeatmap = display === ChartDisplayType.CalendarHeatmap
const isPie = !!display && PIE_DISPLAY_TYPES.includes(display)
// Percent stacking swaps the raw values out for percentages, so there is no unit left to pick.
@@ -102,11 +123,14 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb
// funnel trends default to their line graph when display is unset.
const isLineChartInsight = isLineDisplay || ((isRetention || isTrendsFunnel) && !display)
const showLineStyleConfig = (isTrends || isStickiness || isRetention || isTrendsFunnel) && isLineChartInsight
+ const showStatisticalOverlays = showYAxisScale && !isBoxPlot
+ const showUnit = showsRawValues && isTrends && !isCalendarHeatmap
+ const showDecimalPlaces = mightContainFractionalNumbers && isTrends && !isCalendarHeatmap
// The box plot and slope graph only show a couple of options each; everything else falls
// through to the full shared list.
- const getDisplayItems = (): LemonMenuItem[] => {
- const displayItems: LemonMenuItem[] = []
+ const getDisplayItems = (): DisplayOption[] => {
+ const displayItems: DisplayOption[] = []
if (isBoxPlot) {
if (hasLegend) {
@@ -149,129 +173,169 @@ export function useInsightDisplayOptions(): { items: LemonMenuItems; count: numb
if (isPie) {
displayItems.push(DisplayOptions.SliceNames, DisplayOptions.PieTotal)
}
- if (showAlertThresholdLinesConfig) {
- displayItems.push(DisplayOptions.AlertThresholdLines, DisplayOptions.AlertAnomalyPoints)
- }
- if (showMultipleYAxesConfig) {
- displayItems.push(DisplayOptions.MultipleYAxes)
- }
- if ((isTrends || isRetention || isTrendsFunnel) && !hideContinuousChartOptions) {
- displayItems.push(DisplayOptions.TrendLines)
- }
if (isTrendsFunnel && !hideContinuousChartOptions) {
displayItems.push(DisplayOptions.HideIncompleteFunnelPeriods)
}
if (showAnnotationsConfig) {
displayItems.push(DisplayOptions.Annotations)
}
+ if (showAlertThresholdLinesConfig) {
+ displayItems.push(DisplayOptions.AlertAnomalyPoints)
+ }
if (useQuillLegendOptions) {
displayItems.push(DisplayOptions.LegendOptions)
}
return displayItems
}
- const items: LemonMenuItems = []
+ const displaySections: DisplayOptionSection[] = []
const displayItems = getDisplayItems()
-
- if (showSmoothing) {
- items.push({ title: 'Smoothing', items: [DisplayOptions.Smoothing] })
- }
-
if (showDisplaySection && displayItems.length > 0) {
- items.push({
- title: <SectionHeader dataAttr="options-display-section">Display</SectionHeader>,
- items: displayItems,
- })
+ displaySections.push({ key: 'display', dataAttr: 'options-display-section', items: displayItems })
+ }
+ if (showUnit) {
+ displaySections.push({ key: 'unit', title: 'Unit', items: [DisplayOptions.Unit] })
}
-
if (supportsResultCustomizationBy) {
- items.push({
- title: (
- <SectionHeader tooltip="You can customize the appearance of individual results in your insights. This can be done based on the result's name (e.g., customize the breakdown value 'pizza' for the first series) or based on the result's rank (e.g., customize the first dataset in the results).">
- Color customization by
- </SectionHeader>
- ),
+ displaySections.push({
+ key: 'color-customization',
+ title: 'Color customization by',
+ tooltip:
+ "You can customize the appearance of individual results in your insights. This can be done based on the result's name (e.g., customize the breakdown value 'pizza' for the first series) or based on the result's rank (e.g., customize the first dataset in the results).",
items: [DisplayOptions.ResultCustomizationBy],
})
}
-
- if (showsRawValues && isTrends && !isCalendarHeatmap) {
- items.push({
- title: axisLabel(display || ChartDisplayType.ActionsLineGraph),
- items: [DisplayOptions.Unit],
+ if (showDecimalPlaces) {
+ displaySections.push({
+ key: 'decimal-places',
+ title: 'Decimal places',
+ items: [DisplayOptions.DecimalPrecision],
+ })
+ }
+ if (isRetention) {
+ displaySections.push({
+ key: 'retention-dashboards',
+ title: 'On dashboards',
+ items: [DisplayOptions.RetentionDashboardDisplay],
+ })
+ displaySections.push({
+ key: 'retention-cohort-labels',
+ title: 'Cohort labels start at',
+ tooltip:
+ 'Controls the starting index used to label cohort columns. Display only, does not affect the calculations.',
+ items: [DisplayOptions.RetentionCohortLabelStart],
})
}
+ // Scale sits directly above the range, so the log scale that disables the range is in view.
+ const axesSections: DisplayOptionSection[] = []
+ if (showAxisLabelsConfig) {
+ axesSections.push({ key: 'x-axis', title: 'X-axis', items: [DisplayOptions.XAxisLabel] })
+ }
+ const yAxisItems: DisplayOption[] = []
+ if (showAxisLabelsConfig) {
+ yAxisItems.push(DisplayOptions.YAxisLabel)
+ }
+ if (showMultipleYAxesConfig) {
+ yAxisItems.push(DisplayOptions.MultipleYAxes)
+ }
if (showYAxisScale) {
- items.push({ title: 'Y-axis scale', items: [DisplayOptions.Scale] })
+ yAxisItems.push(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] })
+ yAxisItems.push(DisplayOptions.YAxisRange)
+ }
+ if (yAxisItems.length > 0) {
+ axesSections.push({ key: 'y-axis', title: 'Y-axis', items: yAxisItems })
}
+ const styleItems: DisplayOption[] = []
if (showLineStyleConfig) {
- items.push({ title: 'Line style', items: [DisplayOptions.LineStyle] })
+ styleItems.push(DisplayOptions.LineStyle)
}
-
- if (showYAxisScale && !isBoxPlot) {
- const statisticalItems: LemonMenuItem[] = [DisplayOptions.ConfidenceInterval]
- if (showConfidenceIntervals) {
- statisticalItems.push(DisplayOptions.ConfidenceLevel)
- }
- statisticalItems.push(DisplayOptions.MovingAverage)
+ if (showSmoothing) {
+ styleItems.push(DisplayOptions.Smoothing)
+ }
+ const overlayItems: DisplayOption[] = []
+ if (showTrendLinesConfig && !isBoxPlot) {
+ overlayItems.push(DisplayOptions.TrendLines)
+ }
+ if (showStatisticalOverlays) {
+ overlayItems.push(DisplayOptions.MovingAverage)
if (showMovingAverage) {
- statisticalItems.push(DisplayOptions.MovingAverageIntervals)
+ overlayItems.push(DisplayOptions.MovingAverageIntervals)
+ }
+ overlayItems.push(DisplayOptions.ConfidenceInterval)
+ if (showConfidenceIntervals) {
+ overlayItems.push(DisplayOptions.ConfidenceLevel)
}
- items.push({ title: 'Statistical analysis', items: statisticalItems })
}
-
- if (showAxisLabelsConfig) {
- items.push({ title: 'Axis labels', items: [DisplayOptions.AxisLabels] })
+ if (showAlertThresholdLinesConfig && !isBoxPlot) {
+ overlayItems.push(DisplayOptions.AlertThresholdLines)
}
-
- if (mightContainFractionalNumbers && isTrends && !isCalendarHeatmap) {
- items.push({ title: 'Decimal places', items: [DisplayOptions.DecimalPrecision] })
+ const linesSections: DisplayOptionSection[] = []
+ if (styleItems.length > 0) {
+ linesSections.push({ key: 'style', title: 'Style', items: styleItems })
}
-
- if (isRetention) {
- items.push({ title: 'On dashboards', items: [DisplayOptions.RetentionDashboardDisplay] })
- items.push({
- title: (
- <SectionHeader tooltip="Controls the starting index used to label cohort columns. Display only, does not affect the calculations.">
- Cohort labels start at
- </SectionHeader>
- ),
- items: [DisplayOptions.RetentionCohortLabelStart],
+ if (overlayItems.length > 0) {
+ linesSections.push({
+ key: 'overlays',
+ title: 'Overlays',
+ dataAttr: 'options-overlays-section',
+ items: overlayItems,
})
}
- const count: number =
- (showSmoothing && (trendsFilter?.smoothingIntervals ?? 1) !== 1 ? 1 : 0) +
- (supportsValueOnSeries && showValuesOnSeries ? 1 : 0) +
- (isLifecycle && showPercentagesOnSeries ? 1 : 0) +
- (showPercentStackView ? 1 : 0) +
- (isPie && trendsFilter?.showLabelsOnSeries ? 1 : 0) +
- (showsRawValues &&
- isTrends &&
- trendsFilter?.aggregationAxisFormat &&
- trendsFilter.aggregationAxisFormat !== 'numeric'
- ? 1
- : 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) +
- (showMultipleYAxes ? 1 : 0) +
- (showAnnotationsConfig && showAnnotations === false ? 1 : 0) +
- (isMetric && trendsFilter?.metricShowChange === false ? 1 : 0) +
- (isMetric && trendsFilter?.metricColorByDirection ? 1 : 0) +
- (isMetric && !!trendsFilter?.metricSummary && trendsFilter.metricSummary !== 'total' ? 1 : 0)
+ const unitIsSet =
+ showUnit && !!trendsFilter?.aggregationAxisFormat && trendsFilter.aggregationAxisFormat !== 'numeric'
+ const displayCount = countTruthy(
+ supportsValueOnSeries && showValuesOnSeries,
+ isLifecycle && showPercentagesOnSeries,
+ showPercentStackView,
+ isPie && trendsFilter?.showLabelsOnSeries,
+ unitIsSet,
+ (hasLegend || showFunnelLegendConfig) && showLegend,
+ showAnnotationsConfig && showAnnotations === false,
+ isMetric && trendsFilter?.metricShowChange === false,
+ isMetric && trendsFilter?.metricColorByDirection,
+ isMetric && !!trendsFilter?.metricSummary && trendsFilter.metricSummary !== 'total'
+ )
+ const axesCount = countTruthy(
+ showMultipleYAxesConfig && showMultipleYAxes,
+ showYAxisScale && !!yAxisScaleType && yAxisScaleType !== 'linear',
+ showYAxisRangeConfig && trendsFilter?.yAxisStartAtZero === false,
+ showYAxisRangeConfig && trendsFilter?.yAxisStartAtZero === false && typeof trendsFilter?.yAxisMin === 'number',
+ showYAxisRangeConfig && typeof trendsFilter?.yAxisMax === 'number',
+ showAxisLabelsConfig && !!normalizeAxisLabel(trendsFilter?.xAxisLabel),
+ showAxisLabelsConfig && !!normalizeAxisLabel(trendsFilter?.yAxisLabel)
+ )
+ const linesCount = countTruthy(
+ showSmoothing && (trendsFilter?.smoothingIntervals ?? 1) !== 1,
+ showLineStyleConfig && (insightFilter as TrendsFilter | undefined)?.chartStyle?.curve === 'linear',
+ showTrendLinesConfig && !isBoxPlot && (insightFilter as TrendsFilter | undefined)?.showTrendLines,
+ showStatisticalOverlays && showMovingAverage,
+ showStatisticalOverlays && showConfidenceIntervals,
+ showAlertThresholdLinesConfig && !isBoxPlot && showAlertThresholdLines
+ )
+
+ const allTabs: DisplayOptionTab[] = [
+ { key: 'general', label: 'General', sections: displaySections, count: displayCount },
+ { key: 'axes', label: 'Axes', sections: axesSections, count: axesCount },
+ { key: 'lines', label: 'Lines', sections: linesSections, count: linesCount },
+ ]
+ // Only trends has enough options to need tabs; the other insight types keep one flat list.
+ const tabs = (
+ isTrends
+ ? allTabs
+ : [
+ {
+ key: 'general' as const,
+ label: 'General',
+ sections: allTabs.flatMap((tab) => tab.sections),
+ count: allTabs.reduce((sum, tab) => sum + tab.count, 0),
+ },
+ ]
+ ).filter((tab) => tab.sections.length > 0)
- return { items, count }
+ return { tabs, count: tabs.reduce((sum, tab) => sum + tab.count, 0) }
}
diff --git a/frontend/src/scenes/insights/EditorFilters/AxisLabelFilter.tsx b/frontend/src/scenes/insights/EditorFilters/AxisLabelFilter.tsx
new file mode 100644
index 000000000000..855a69d20ddc
--- /dev/null
+++ b/frontend/src/scenes/insights/EditorFilters/AxisLabelFilter.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { LemonInput } from '@posthog/lemon-ui'
+import { normalizeAxisLabel } from '@posthog/quill-charts'
+
+import { insightLogic } from 'scenes/insights/insightLogic'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+
+export function AxisLabelFilter({ axis }: { axis: 'x' | 'y' }): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+ const savedLabel = axis === 'x' ? trendsFilter?.xAxisLabel : trendsFilter?.yAxisLabel
+ const [draft, setDraft] = useState(savedLabel ?? '')
+
+ useEffect(() => {
+ setDraft(savedLabel ?? '')
+ }, [savedLabel])
+
+ const commit = (): void => {
+ const normalized = normalizeAxisLabel(draft)
+ setDraft(normalized ?? '')
+ updateInsightFilter(axis === 'x' ? { xAxisLabel: normalized } : { yAxisLabel: normalized })
+ }
+
+ return (
+ <div className="flex p-1 px-2">
+ <LemonInput
+ size="small"
+ className="w-0 flex-1"
+ data-attr={`trends-${axis}-axis-label-input`}
+ value={draft}
+ placeholder="Label"
+ onChange={setDraft}
+ onBlur={commit}
+ onPressEnter={commit}
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/insights/EditorFilters/AxisLabelsFilter.tsx b/frontend/src/scenes/insights/EditorFilters/AxisLabelsFilter.tsx
deleted file mode 100644
index 29cc97d9b172..000000000000
--- a/frontend/src/scenes/insights/EditorFilters/AxisLabelsFilter.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useEffect, useState } from 'react'
-
-import { LemonInput, LemonLabel } from '@posthog/lemon-ui'
-import { normalizeAxisLabel } from '@posthog/quill-charts'
-
-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
-
-import { insightLogic } from '../insightLogic'
-
-export function AxisLabelsFilter(): JSX.Element {
- const { insightProps } = useValues(insightLogic)
- const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
- const [xAxisLabelDraft, setXAxisLabelDraft] = useState(trendsFilter?.xAxisLabel ?? '')
- const [yAxisLabelDraft, setYAxisLabelDraft] = useState(trendsFilter?.yAxisLabel ?? '')
-
- useEffect(() => {
- setXAxisLabelDraft(trendsFilter?.xAxisLabel ?? '')
- }, [trendsFilter?.xAxisLabel])
-
- useEffect(() => {
- setYAxisLabelDraft(trendsFilter?.yAxisLabel ?? '')
- }, [trendsFilter?.yAxisLabel])
-
- const commitXAxisLabel = (): void => {
- const normalized = normalizeAxisLabel(xAxisLabelDraft)
- setXAxisLabelDraft(normalized ?? '')
- updateInsightFilter({ xAxisLabel: normalized })
- }
-
- const commitYAxisLabel = (): void => {
- const normalized = normalizeAxisLabel(yAxisLabelDraft)
- setYAxisLabelDraft(normalized ?? '')
- updateInsightFilter({ yAxisLabel: normalized })
- }
-
- return (
- <div className="p-1 px-2 flex flex-col gap-2 w-64">
- <div className="flex flex-col gap-1">
- <LemonLabel>X-axis label</LemonLabel>
- <LemonInput
- size="small"
- data-attr="trends-x-axis-label-input"
- value={xAxisLabelDraft}
- placeholder="X-axis label"
- onChange={setXAxisLabelDraft}
- onBlur={commitXAxisLabel}
- onPressEnter={commitXAxisLabel}
- />
- </div>
- <div className="flex flex-col gap-1">
- <LemonLabel>Y-axis label</LemonLabel>
- <LemonInput
- size="small"
- data-attr="trends-y-axis-label-input"
- value={yAxisLabelDraft}
- placeholder="Y-axis label"
- onChange={setYAxisLabelDraft}
- onBlur={commitYAxisLabel}
- onPressEnter={commitYAxisLabel}
- />
- </div>
- </div>
- )
-}
diff --git a/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsx b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsx
index 2a805c7c66a6..db20430e620a 100644
--- a/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.test.tsx
@@ -61,26 +61,35 @@ describe('YAxisRangeFilter', () => {
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" and the minimum both set the axis floor, so the minimum only appears once
+ // the toggle is off. 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 | 'hidden'; max: boolean }, ChartDisplayType | undefined]
+ >([
+ ['begin at zero is on by default', {}, { toggle: false, min: 'hidden', 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],
+ ['a logarithmic scale', { yAxisScaleType: 'log10' }, { toggle: true, min: 'hidden', max: true }, undefined],
+ [
+ 'a logarithmic scale with begin at zero off',
+ { yAxisScaleType: 'log10', yAxisStartAtZero: false },
+ { toggle: true, min: true, max: true },
+ undefined,
+ ],
[
'percentages are shown',
{ showPercentStackView: true },
- { toggle: true, min: true, max: true },
+ { toggle: true, min: 'hidden', 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)
+ const minInput = container.querySelector<HTMLInputElement>('[data-attr="trends-y-axis-min-input"]')
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(minInput ? minInput.disabled : 'hidden').toBe(expected.min)
expect(control(container, 'trends-y-axis-max-input')).toHaveProperty('disabled', expected.max)
})
diff --git a/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsx b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsx
index e7d6327bace6..02bd5ac8523d 100644
--- a/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/YAxisRangeFilter.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useEffect, useState } from 'react'
-import { LemonInput, LemonLabel, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonInput, LemonSwitch } from '@posthog/lemon-ui'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -29,10 +29,9 @@ export function YAxisRangeFilter(): JSX.Element {
: showPercentStackView
? 'Not available while showing percentages'
: undefined
- // Disabled rather than cleared, so the typed value applies again when the toggle goes off.
+ // The minimum is hidden rather than cleared while the axis begins at zero, 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.
@@ -51,7 +50,7 @@ export function YAxisRangeFilter(): JSX.Element {
const commitMax = (): void => updateInsightFilter({ yAxisMax: asBound(maxDraft) })
return (
- <div className="p-1 px-2 flex flex-col gap-2 w-64">
+ <div className="p-1 px-2 flex flex-col gap-2">
<LemonSwitch
className="flex-1 w-full"
label="Begin at zero"
@@ -61,25 +60,29 @@ export function YAxisRangeFilter(): JSX.Element {
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>
+ {!beginsAtZero && (
+ <label className="flex items-center gap-2">
+ <span className="w-16 shrink-0">Minimum</span>
+ <LemonInput
+ type="number"
+ size="small"
+ className="w-0 flex-1"
+ data-attr="trends-y-axis-min-input"
+ value={minDraft}
+ placeholder="Auto"
+ disabledReason={rangeDisabledReason}
+ onChange={setMinDraft}
+ onBlur={commitMin}
+ onPressEnter={commitMin}
+ />
+ </label>
+ )}
+ <label className="flex items-center gap-2">
+ <span className="w-16 shrink-0">Maximum</span>
<LemonInput
type="number"
size="small"
+ className="w-0 flex-1"
data-attr="trends-y-axis-max-input"
value={maxDraft}
placeholder="Auto"
@@ -88,12 +91,8 @@ export function YAxisRangeFilter(): JSX.Element {
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>
- )}
+ </label>
+ {invalidRange && <span className="text-xs text-danger">Maximum must be greater than minimum.</span>}
</div>
)
}
diff --git a/frontend/src/scenes/insights/aggregationAxisFormat.ts b/frontend/src/scenes/insights/aggregationAxisFormat.ts
index f63fa7d1c0b2..a651e3904d08 100644
--- a/frontend/src/scenes/insights/aggregationAxisFormat.ts
+++ b/frontend/src/scenes/insights/aggregationAxisFormat.ts
@@ -182,18 +182,3 @@ export const formatAggregationAxisValueWithShareOfTotal = (
const shareOfTotal = parseFloat(((Number(value) / total) * 100).toFixed(1))
return `${formatted} (${shareOfTotal}%)`
}
-
-export const axisLabel = (chartDisplayType: ChartDisplayType | null | undefined): string => {
- switch (chartDisplayType) {
- case ChartDisplayType.ActionsLineGraph:
- case ChartDisplayType.ActionsLineGraphCumulative:
- case ChartDisplayType.ActionsBar:
- case ChartDisplayType.ActionsUnstackedBar:
- case ChartDisplayType.ActionsAreaGraph:
- return 'Y-axis unit'
- case ChartDisplayType.ActionsBarValue:
- return 'X-axis unit'
- default:
- return 'Unit'
- }
-}
diff --git a/frontend/src/scenes/insights/views/LineGraph/ConfidenceLevelInput.tsx b/frontend/src/scenes/insights/views/LineGraph/ConfidenceLevelInput.tsx
index 0d47d1e5d76a..6548d6ae70c0 100644
--- a/frontend/src/scenes/insights/views/LineGraph/ConfidenceLevelInput.tsx
+++ b/frontend/src/scenes/insights/views/LineGraph/ConfidenceLevelInput.tsx
@@ -45,6 +45,7 @@ export function ConfidenceLevelInput(): JSX.Element {
setLocalValue(numValue)
debouncedUpdate(numValue)
}}
+ onBlur={() => debouncedUpdate.flush()}
min={0}
max={100}
step={1}
diff --git a/frontend/src/scenes/insights/views/LineGraph/MovingAverageIntervalsInput.tsx b/frontend/src/scenes/insights/views/LineGraph/MovingAverageIntervalsInput.tsx
index 8ff56264940c..649d855563b6 100644
--- a/frontend/src/scenes/insights/views/LineGraph/MovingAverageIntervalsInput.tsx
+++ b/frontend/src/scenes/insights/views/LineGraph/MovingAverageIntervalsInput.tsx
@@ -47,6 +47,7 @@ export function MovingAverageIntervalsInput(): JSX.Element {
setLocalValue(numValue)
debouncedUpdate(numValue)
}}
+ onBlur={() => debouncedUpdate.flush()}
min={2}
suffix={<span>{`${interval}s`}</span>}
step={1}
diff --git a/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts b/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts
index 15778d67bbb7..4a35547d4164 100644
--- a/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts
+++ b/products/metrics/frontend/emptyState/metricsSetupLogic.test.ts
@@ -11,6 +11,11 @@ import { metricsSetupLogic } from './metricsSetupLogic'
jest.mock('../metricsAccess', () => ({ canViewMetrics: jest.fn() }))
jest.mock('../generated/api', () => ({ metricsHasMetricsRetrieve: jest.fn() }))
+// Real backoff waits would put the error cases over the 5s test limit; the retry policy is not what these assert.
+jest.mock('lib/utils/async', () => ({
+ ...jest.requireActual('lib/utils/async'),
+ retryWithBackoff: (fn: () => Promise<unknown>) => fn(),
+}))
describe('metricsSetupLogic', () => {
beforeEach(() => {