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.

refactor(insights): render the sql display tab from the shared option list (#127638)

Sam Pennington974694820b38
diff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsLayer.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsLayer.tsx
index de09be8a2526..4d7e54201469 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsLayer.tsx
+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsLayer.tsx
@@ -2,7 +2,7 @@ import React, { useMemo } from 'react'
import { computeVisibleXLabels, useChartLayout } from '@posthog/quill-charts'
-import { AnnotationsOverlay } from './AnnotationsOverlay'
+import { AnnotationsOverlay, type AnnotationsOverlayProps } from './AnnotationsOverlay'
import type { AnnotationsChartGeometry } from './useAnnotationsPositioning'
interface AnnotationsLayerProps {
@@ -21,6 +21,7 @@ interface AnnotationsLayerProps {
/** Series key for the previous-period bar. Required for previous-period annotations
* to anchor on the correct bar within each band. */
previousSeriesKey?: string
+ annotationsScope?: AnnotationsOverlayProps['annotationsScope']
}
const WRAPPER_STYLE: React.CSSProperties = {
@@ -40,6 +41,7 @@ export function AnnotationsLayer({
seriesKey,
previousDates,
previousSeriesKey,
+ annotationsScope,
}: AnnotationsLayerProps): React.ReactElement | null {
const { scales, dimensions, labels, axis } = useChartLayout()
const xTickFormatter = axis.xTickFormatter
@@ -97,6 +99,7 @@ export function AnnotationsLayer({
dates={dates}
chartWidth={dimensions.width}
insightNumericId={insightNumericId}
+ annotationsScope={annotationsScope}
/>
{previousGeometry && previousDates && (
<AnnotationsOverlay
@@ -105,6 +108,7 @@ export function AnnotationsLayer({
chartWidth={dimensions.width}
insightNumericId={insightNumericId}
kind="previous"
+ annotationsScope={annotationsScope}
/>
)}
</div>
diff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
index 960ac32811b8..c9ffb4ad5160 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx
@@ -75,6 +75,7 @@ export interface AnnotationsOverlayProps {
/** Forwarded to the kea logic key so multiple overlays on the same insight don't
* collide. Used by compare-against-previous bar charts to show one overlay per period. */
kind?: string
+ annotationsScope?: AnnotationsOverlayLogicProps['annotationsScope']
}
interface AnnotationsOverlayCSSProperties extends React.CSSProperties {
@@ -89,6 +90,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({
dates,
insightNumericId,
kind,
+ annotationsScope,
}: AnnotationsOverlayProps): JSX.Element {
const { insightProps } = useValues(insightLogic)
const { tickIntervalPx, firstTickLeftPx, getDataPointX } = useAnnotationsPositioning(geometry)
@@ -114,6 +116,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({
dates,
ticks: prevTicksRef.current,
kind,
+ annotationsScope,
}
const logic = annotationsOverlayLogic(annotationsOverlayLogicProps)
const { activeDate, tickDates, annotationBadgeDataIndices, groupedAnnotations, readOnly } = useValues(logic)
diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
index 2988bac36000..50d7e18b6f34 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
@@ -41,6 +41,8 @@ export interface AnnotationsOverlayLogicProps extends Omit<InsightLogicProps, 'd
* would share the same kea instance and the second mount's `dates`/`ticks` would
* overwrite the first. */
kind?: string
+ // Charts without an insight query, like SQL charts, pass the scope in. Unset reads it from the insight.
+ annotationsScope?: AnnotationScope | null
}
/** Week/month charts bucket annotations by day so distinct dates don't collapse into one badge. */
@@ -183,7 +185,8 @@ export interface annotationsOverlayLogicMeta {
savedInsight: Partial<InsightModel<Node<Record<string, any>>>>,
properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined,
breakdownFilter: BreakdownFilter | null | undefined,
- annotationsScope: AnnotationScope | null | undefined
+ annotationsScope: AnnotationScope | null | undefined,
+ arg: AnnotationScope | null | undefined
) => DatedAnnotationType[]
groupedAnnotations: (
relevantAnnotations: DatedAnnotationType[],
@@ -370,6 +373,7 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
s.properties,
s.breakdownFilter,
s.annotationsScope,
+ (_, props: AnnotationsOverlayLogicProps) => props.annotationsScope,
],
(
annotations: AnnotationType[],
@@ -383,8 +387,10 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
>,
properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined,
breakdownFilter: BreakdownFilter | null | undefined,
- annotationsScope: AnnotationScope | null | undefined
+ insightAnnotationsScope: AnnotationScope | null | undefined,
+ annotationsScopeOverride: AnnotationScope | null | undefined
) => {
+ const annotationsScope = annotationsScopeOverride ?? insightAnnotationsScope
// This assumes that there are no more annotations in the project than AnnotationsViewSet
// pagination class's default_limit of 100. As of June 2023, this is not true on Cloud US,
// where 3 projects exceed this limit. To accommodate those, we should always make a request for the
diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts
index 360c81e02b5f..c61a41ef6801 100644
--- a/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts
+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardVisualizationOptions.test.ts
@@ -321,8 +321,8 @@ describe('dashboardVisualizationOptions', () => {
)
const view = render(displayOptionsElement(result.current))
- expect(await screen.findByText('Right Y-axis')).toBeInTheDocument()
- expect(screen.getByText('Goals')).toBeInTheDocument()
+ expect(await screen.findByText('X-axis')).toBeInTheDocument()
+ expect(screen.getByText('Goal lines')).toBeInTheDocument()
rerender({
...baseProps,
@@ -334,8 +334,8 @@ describe('dashboardVisualizationOptions', () => {
view.rerender(displayOptionsElement(result.current))
expect(await screen.findByText('Show on slices')).toBeInTheDocument()
- expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()
- expect(screen.queryByText('Goals')).not.toBeInTheDocument()
+ expect(screen.queryByText('X-axis')).not.toBeInTheDocument()
+ expect(screen.queryByText('Goal lines')).not.toBeInTheDocument()
})
it('routes display setting changes through SQL-safe persistence', async () => {
@@ -417,7 +417,10 @@ describe('dashboardVisualizationOptions', () => {
).toBe(displayLabel && 'label' in displayLabel ? displayLabel.label : null)
view.rerender(displayOptionsElement(result.current))
expect(screen.getByLabelText('Show legend')).toBeChecked()
- await userEvent.click(screen.getByLabelText('Show annotations'))
+ await userEvent.click(
+ view.container.querySelector('[data-attr="data-visualization-show-annotations"]') as HTMLElement
+ )
+ await userEvent.click(await screen.findByText('All'))
expect(persistSqlDisplayOptions).toHaveBeenLastCalledWith(
expect.objectContaining({
diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionGroup.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionGroup.tsx
new file mode 100644
index 000000000000..c8f138139846
--- /dev/null
+++ b/frontend/src/lib/components/ChartOptions/ChartOptionGroup.tsx
@@ -0,0 +1,21 @@
+import { ReactNode } from 'react'
+
+import { ChartOptionLabel } from './ChartOptionLabel'
+
+export interface ChartOptionGroupProps {
+ title: string
+ info?: string
+ children: ReactNode
+}
+
+export function ChartOptionGroup(props: ChartOptionGroupProps): JSX.Element {
+ const { title, info, children } = props
+ return (
+ <section className="flex flex-col gap-2">
+ <h5 className="m-0 font-semibold">
+ <ChartOptionLabel label={title} info={info} />
+ </h5>
+ {children}
+ </section>
+ )
+}
diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionSections.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionSections.tsx
new file mode 100644
index 000000000000..dbcfcd325c2b
--- /dev/null
+++ b/frontend/src/lib/components/ChartOptions/ChartOptionSections.tsx
@@ -0,0 +1,21 @@
+import { Fragment } from 'react'
+
+import { ChartOptionGroup } from './ChartOptionGroup'
+import type { DisplayOptionSection } from './displayOptions'
+
+export function ChartOptionSections({ sections }: { sections: DisplayOptionSection[] }): JSX.Element {
+ return (
+ <>
+ {sections.map((section) => {
+ const items = section.items.map((item) => <Fragment key={item.name}>{item.element}</Fragment>)
+ return section.title ? (
+ <ChartOptionGroup key={section.key} title={section.title} info={section.tooltip}>
+ {items}
+ </ChartOptionGroup>
+ ) : (
+ <Fragment key={section.key}>{items}</Fragment>
+ )
+ })}
+ </>
+ )
+}
diff --git a/frontend/src/lib/components/ChartOptions/displayOptions.ts b/frontend/src/lib/components/ChartOptions/displayOptions.ts
index 2d313980f20c..d521ccd34079 100644
--- a/frontend/src/lib/components/ChartOptions/displayOptions.ts
+++ b/frontend/src/lib/components/ChartOptions/displayOptions.ts
@@ -186,7 +186,6 @@ export const DISPLAY_OPTIONS = [
name: 'annotations',
label: 'Annotations',
info: 'Annotations are saved on an insight, a dashboard, the project, or the organization. Choose which of those to show here.',
- stacked: true,
group: 'display',
control: 'select',
options: [
@@ -285,13 +284,7 @@ export const DISPLAY_OPTIONS = [
{ name: 'yAxisBorder', label: 'Show border', group: 'y-axis', control: 'checkbox' },
{ name: 'yAxisScale', label: 'Scale', hideLabel: true, group: 'y-axis', control: 'toggle', options: SCALE_OPTIONS },
- {
- name: 'rightYAxisLabel',
- label: 'Label',
- group: 'right-y-axis',
- control: 'text',
- placeholder: 'Right Y-axis label',
- },
+ { name: 'rightYAxisLabel', label: 'Label', group: 'right-y-axis', control: 'text', placeholder: 'None' },
{
name: 'rightYAxisBeginAtZero',
label: 'Begin at zero',
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
index 69d49b307867..f8fdaf656aab 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
@@ -118,7 +118,11 @@ export const SqlBarGraph = (props: SqlChartProps): JSX.Element => {
>
{props.children}
{props.showAnnotations && props.insightNumericId && (
- <AnnotationsLayer insightNumericId={props.insightNumericId} dates={model.labels} />
+ <AnnotationsLayer
+ insightNumericId={props.insightNumericId}
+ dates={model.labels}
+ annotationsScope={props.chartSettings.annotationsScope}
+ />
)}
</TimeSeriesBarChart>
))}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx
index 7e4af843d525..8a22f9137ba1 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx
@@ -57,7 +57,11 @@ export const SqlComboGraph = (props: SqlChartProps): JSX.Element => {
>
{props.children}
{props.showAnnotations && props.insightNumericId && (
- <AnnotationsLayer insightNumericId={props.insightNumericId} dates={model.labels} />
+ <AnnotationsLayer
+ insightNumericId={props.insightNumericId}
+ dates={model.labels}
+ annotationsScope={props.chartSettings.annotationsScope}
+ />
)}
</TimeSeriesComboChart>
)}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
index c6515d4c2119..6c9dee7588d4 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
@@ -70,7 +70,11 @@ export const SqlLineGraph = (props: SqlChartProps): JSX.Element => {
>
{props.children}
{props.showAnnotations && props.insightNumericId && (
- <AnnotationsLayer insightNumericId={props.insightNumericId} dates={model.labels} />
+ <AnnotationsLayer
+ insightNumericId={props.insightNumericId}
+ dates={model.labels}
+ annotationsScope={props.chartSettings.annotationsScope}
+ />
)}
</TimeSeriesLineChart>
)}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
index ddef788e2ec4..239d2dfcdc86 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
@@ -51,11 +51,11 @@ describe('DisplayTab', () => {
const user = userEvent.setup()
+ await user.click(await screen.findByText('X-axis'))
await user.click(await screen.findByText('Left Y-axis'))
- await user.click(screen.getByText('Right Y-axis'))
+ await user.click(await screen.findByText('Right Y-axis'))
- expect(screen.getByText('Show X-axis tick labels')).toBeInTheDocument()
- expect(screen.getAllByText('Show tick labels')).toHaveLength(2)
+ expect(screen.getAllByText('Show tick labels')).toHaveLength(3)
expect(screen.queryByText('Show X-axis labels')).not.toBeInTheDocument()
expect(screen.queryByText('Show labels')).not.toBeInTheDocument()
})
@@ -99,7 +99,7 @@ describe('DisplayTab', () => {
dataVisualizationLogic(props).mount()
displayLogic({ key }).mount()
- render(
+ const { container } = render(
<BindLogic logic={dataVisualizationLogic} props={props}>
<BindLogic logic={displayLogic} props={{ key }}>
<DisplayTab />
@@ -107,10 +107,12 @@ describe('DisplayTab', () => {
</BindLogic>
)
- const annotationsToggle = await screen.findByLabelText('Show annotations')
- expect(annotationsToggle).not.toBeChecked()
+ await screen.findByText('Annotations')
+ const annotationsSelect = container.querySelector('[data-attr="data-visualization-show-annotations"]')
+ expect(annotationsSelect).toHaveTextContent('None')
- await userEvent.click(annotationsToggle)
+ await userEvent.click(annotationsSelect as HTMLElement)
+ await userEvent.click(await screen.findByText('All'))
await waitFor(() => {
expect(query.chartSettings?.showAnnotations).toBe(true)
@@ -162,13 +164,17 @@ describe('DisplayTab', () => {
const user = userEvent.setup()
- await user.type(await screen.findByPlaceholderText('X-axis label'), 'Company size')
-
- await user.click(screen.getByText('Left Y-axis'))
- await user.type(await screen.findByPlaceholderText('Left Y-axis label'), 'Accounts')
-
- await user.click(screen.getByText('Right Y-axis'))
- await user.type(await screen.findByPlaceholderText('Right Y-axis label'), 'Revenue')
+ await user.click(await screen.findByText('X-axis'))
+ await user.click(await screen.findByText('Left Y-axis'))
+ await user.click(await screen.findByText('Right Y-axis'))
+ const labelInput = (dataAttr: string): HTMLElement =>
+ document.querySelector<HTMLElement>(`[data-attr="${dataAttr}"]`) as HTMLElement
+ await user.type(labelInput('data-visualization-x-axis-label-input'), 'Company size')
+ await user.tab()
+ await user.type(labelInput('data-visualization-left-y-axis-label-input'), 'Accounts')
+ await user.tab()
+ await user.type(labelInput('data-visualization-right-y-axis-label-input'), 'Revenue')
+ await user.tab()
await waitFor(() => {
expect(setQuery).toHaveBeenCalled()
@@ -224,13 +230,13 @@ describe('DisplayTab', () => {
const user = userEvent.setup()
expect(await screen.findByText('Y-axis')).toBeInTheDocument()
- expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()
- expect(screen.queryByText('Goals')).not.toBeInTheDocument()
+ expect(screen.queryByText('Goal lines')).not.toBeInTheDocument()
expect(screen.queryByText('Show total row')).not.toBeInTheDocument()
- expect(screen.queryByText('Show annotations')).not.toBeInTheDocument()
+ expect(screen.queryByText('Annotations')).not.toBeInTheDocument()
await user.click(screen.getByText('Exclude outliers'))
await user.click(screen.getByText('Y-axis'))
+ expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()
expect(screen.queryByText('Begin at zero')).not.toBeInTheDocument()
await waitFor(() => expect(query.chartSettings?.boxPlot?.excludeOutliers).toBe(false))
@@ -274,8 +280,8 @@ describe('DisplayTab', () => {
expect(await screen.findByText('Headline value')).toBeInTheDocument()
expect(screen.queryByText('Show legend')).not.toBeInTheDocument()
- expect(screen.queryByText('Left Y-axis')).not.toBeInTheDocument()
- expect(screen.queryByText('Goals')).not.toBeInTheDocument()
+ expect(screen.queryByText('X-axis')).not.toBeInTheDocument()
+ expect(screen.queryByText('Goal lines')).not.toBeInTheDocument()
await user.click(screen.getByText('Show change'))
@@ -318,16 +324,16 @@ describe('DisplayTab', () => {
const user = userEvent.setup()
- // One gutter per axis, and quill's scatter takes no goal lines.
- expect(await screen.findByText('X-axis')).toBeInTheDocument()
+ await user.click(await screen.findByText('Lines'))
+ await user.click(await screen.findByText('Show trend lines'))
+ // Quill's scatter takes no goal lines.
+ expect(screen.queryByText('Goal lines')).not.toBeInTheDocument()
+
+ // One gutter per axis.
expect(screen.getByText('Y-axis')).toBeInTheDocument()
expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()
- expect(screen.queryByText('Goals')).not.toBeInTheDocument()
-
- await user.click(screen.getByText('Show line of best fit'))
-
await user.click(screen.getByText('X-axis'))
- await user.click(await screen.findByText('Begin at zero'))
+ await user.click(screen.getByText('Begin at zero'))
// Both live under `scatter`, so the second write must merge into the first rather than replace it.
await waitFor(() => {
@@ -339,43 +345,42 @@ describe('DisplayTab', () => {
})
})
- it.each([
- [ChartDisplayType.ActionsPie, 'Show total below chart'],
- [ChartDisplayType.ActionsDonut, 'Show total in center'],
- [ChartDisplayType.ActionsProportionBar, 'Show total below chart'],
- ])('honors the legacy top-level showPieTotal when pie.showTotal is unset (%s)', async (display, switchLabel) => {
- initKeaTests()
-
- const key = `display-tab-legacy-show-total-test-${display}`
- const query: VisualizationNode = {
- kind: NodeKind.DataVisualizationNode,
- source: {
- kind: NodeKind.HogQLQuery,
- query: 'select label, total from numbers(2)',
- },
- display,
- chartSettings: { showPieTotal: false },
- }
-
- const props: DataVisualizationLogicProps = {
- key,
- query,
- dataNodeCollectionId: key,
- setQuery: jest.fn(),
- }
-
- dataVisualizationLogic(props).mount()
- displayLogic({ key }).mount()
-
- render(
- <BindLogic logic={dataVisualizationLogic} props={props}>
- <BindLogic logic={displayLogic} props={{ key }}>
- <DisplayTab />
+ it.each([ChartDisplayType.ActionsPie, ChartDisplayType.ActionsDonut, ChartDisplayType.ActionsProportionBar])(
+ 'honors the legacy top-level showPieTotal when pie.showTotal is unset (%s)',
+ async (display) => {
+ initKeaTests()
+
+ const key = `display-tab-legacy-show-total-test-${display}`
+ const query: VisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'select label, total from numbers(2)',
+ },
+ display,
+ chartSettings: { showPieTotal: false },
+ }
+
+ const props: DataVisualizationLogicProps = {
+ key,
+ query,
+ dataNodeCollectionId: key,
+ setQuery: jest.fn(),
+ }
+
+ dataVisualizationLogic(props).mount()
+ displayLogic({ key }).mount()
+
+ render(
+ <BindLogic logic={dataVisualizationLogic} props={props}>
+ <BindLogic logic={displayLogic} props={{ key }}>
+ <DisplayTab />
+ </BindLogic>
</BindLogic>
- </BindLogic>
- )
+ )
- const toggle = (await screen.findByText(switchLabel)).closest('div')?.querySelector('[role="switch"]')
- expect(toggle).toHaveAttribute('aria-checked', 'false')
- })
+ const toggle = (await screen.findByText('Show total')).closest('div')?.querySelector('[role="switch"]')
+ expect(toggle).toHaveAttribute('aria-checked', 'false')
+ }
+ )
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
index 8bdbd7c6d522..96e76b9c45dc 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
@@ -1,693 +1,94 @@
import { useActions, useValues } from 'kea'
-import { useMemo } from 'react'
import { IconPlusSmall } from '@posthog/icons'
-import {
- LemonBadge,
- LemonButton,
- LemonCollapse,
- LemonInput,
- LemonLabel,
- LemonSegmentedButton,
- LemonSelect,
- LemonSwitch,
-} from '@posthog/lemon-ui'
+import { LemonBadge, LemonButton } from '@posthog/lemon-ui'
+import { ChartOptionSections } from 'lib/components/ChartOptions/ChartOptionSections'
+import { useDisplayOptions } from 'lib/components/ChartOptions/useDisplayOptions'
import { GoalLinesList } from 'lib/components/GoalLinesList'
-import { MetricDirectionColorPickers } from 'lib/components/Metric/MetricDirectionColorPickers'
-import {
- METRIC_COLOR_BY_DIRECTION_DEFAULT,
- METRIC_DEFAULT_DECREASE_COLOR,
- METRIC_DEFAULT_INCREASE_COLOR,
- METRIC_SHOW_CHANGE_DEFAULT,
- type MetricSummary,
-} from 'lib/components/Metric/metricSummary'
-import { PART_OF_WHOLE_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { ChartDisplayType } from '~/types'
import { dataVisualizationLogic } from '../dataVisualizationLogic'
import { displayLogic } from '../displayLogic'
-import { buildPieSlices, partOfWholeChartData, showsLegendByDefault, showsPieTotal } from './Charts/sqlPieGraphAdapter'
-import { SQL_METRIC_SUMMARY_DEFAULT } from './Charts/useSqlMetricModel'
-import { seriesBreakdownLogic } from './seriesBreakdownLogic'
-
-const PIE_SLICE_CONTENT_OPTIONS: { value: 'labels' | 'values' | 'none'; label: string }[] = [
- { value: 'labels', label: 'Labels' },
- { value: 'values', label: 'Values' },
- { value: 'none', label: 'Nothing' },
-]
-
-const PIE_VALUE_DISPLAY_OPTIONS: { value: 'absolute' | 'percentage'; label: string }[] = [
- { value: 'absolute', label: 'Absolute' },
- { value: 'percentage', label: 'Percentage' },
-]
-
-const LEGEND_POSITION_OPTIONS: { value: 'top' | 'bottom' | 'left' | 'right'; label: string }[] = [
- { value: 'top', label: 'Top' },
- { value: 'bottom', label: 'Bottom' },
- { value: 'left', label: 'Left' },
- { value: 'right', label: 'Right' },
-]
-
-const METRIC_SUMMARY_OPTIONS: { value: MetricSummary; label: string }[] = [
- { value: 'latest', label: 'Latest' },
- { value: 'total', label: 'Total' },
- { value: 'average', label: 'Average' },
-]
-
-const LINE_STYLE_OPTIONS: { value: 'smooth' | 'linear'; label: string }[] = [
- { value: 'smooth', label: 'Smooth' },
- { value: 'linear', label: 'Straight' },
-]
+import { DisplayTabPanel, DisplayTabPanels } from './DisplayTabPanels'
+import { sqlDisplayOptions } from './sqlDisplayOptions'
export const DisplayTab = (): JSX.Element => {
- const { effectiveVisualizationType, xData, yData, dataVisualizationProps } = useValues(dataVisualizationLogic)
- const { seriesBreakdownData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
+ const { effectiveVisualizationType } = useValues(dataVisualizationLogic)
const { goalLines, chartSettings, query } = useValues(displayLogic)
- const { addGoalLine, updateGoalLine, removeGoalLine, updateChartSettings } = useActions(displayLogic)
+ const { addGoalLine, updateGoalLine, removeGoalLine } = useActions(displayLogic)
+ const { tabs } = useDisplayOptions(sqlDisplayOptions)
const isStackedBarChart = effectiveVisualizationType === ChartDisplayType.ActionsStackedBar
- const isPieChart = PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)
- const isDonutChart = effectiveVisualizationType === ChartDisplayType.ActionsDonut
- const isProportionBar = effectiveVisualizationType === ChartDisplayType.ActionsProportionBar
- const isPartOfWholeChart = PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)
- const proportionBarPartCount = useMemo(() => {
- if (!isProportionBar) {
- return 0
- }
- const pieData = partOfWholeChartData(seriesBreakdownData, xData, yData)
- return buildPieSlices(pieData.xData, pieData.yData).length
- }, [isProportionBar, seriesBreakdownData, xData, yData])
- const showLegend = chartSettings.showLegend ?? showsLegendByDefault(isProportionBar, proportionBarPartCount)
- const isScatterPlot = effectiveVisualizationType === ChartDisplayType.ScatterPlot
- const isBoxPlot = effectiveVisualizationType === ChartDisplayType.BoxPlot
- const isMetric = effectiveVisualizationType === ChartDisplayType.Metric
- const isHorizontalBarChart = effectiveVisualizationType === ChartDisplayType.ActionsBarValue
- // Scatter and box plots have a single Y axis, so there is no separate right axis to configure.
- const isSingleAxisChart = isScatterPlot || isBoxPlot
- const supportsRightYAxis = !isSingleAxisChart && !isHorizontalBarChart
- const isLineChart =
- effectiveVisualizationType === ChartDisplayType.ActionsLineGraph ||
- effectiveVisualizationType === ChartDisplayType.ActionsAreaGraph
- const isDateXAxis = xData?.column.type.name === 'DATE' || xData?.column.type.name === 'DATETIME'
- const supportsAnnotations =
- isLineChart ||
- effectiveVisualizationType === ChartDisplayType.ActionsBar ||
- effectiveVisualizationType === ChartDisplayType.ActionsStackedBar
-
- const renderYAxisSettings = (name: 'leftYAxisSettings' | 'rightYAxisSettings'): JSX.Element => {
- const leftPlaceholder = isHorizontalBarChart
- ? 'X-axis label'
- : supportsRightYAxis
- ? 'Left Y-axis label'
- : 'Y-axis label'
- const labelPlaceholder = name === 'leftYAxisSettings' ? leftPlaceholder : 'Right Y-axis label'
-
- return (
- <>
- <div className="flex flex-col gap-1">
- <LemonLabel>Axis label</LemonLabel>
- <LemonInput
- data-attr={`data-visualization-${name === 'leftYAxisSettings' ? 'left' : 'right'}-y-axis-label-input`}
- value={chartSettings[name]?.label ?? ''}
- placeholder={labelPlaceholder}
- onChange={(value) => {
- updateChartSettings({ [name]: { label: value } })
- }}
- />
- </div>
- <div className="flex gap-2 items-center justify-between">
- <span className="font-medium">Scale</span>
- <LemonSelect
- size="xsmall"
- value={chartSettings[name]?.scale ?? 'linear'}
- options={[
- { value: 'linear', label: 'Linear' },
- { value: 'logarithmic', label: 'Logarithmic' },
- ]}
- onChange={(value) => {
- updateChartSettings({ [name]: { scale: value } })
- }}
- />
+ const isBIVisualization = query.kind === 'BIVisualizationNode'
+ const supportsGoalLines =
+ effectiveVisualizationType !== ChartDisplayType.Metric &&
+ effectiveVisualizationType !== ChartDisplayType.ScatterPlot &&
+ effectiveVisualizationType !== ChartDisplayType.BoxPlot &&
+ !PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)
+
+ // Each axis gets its own panel: together they hold too many settings for one.
+ const panels: DisplayTabPanel[] = tabs.flatMap((tab): DisplayTabPanel[] =>
+ tab.key === 'axes'
+ ? tab.sections.map((section) => ({
+ key: section.key,
+ header: section.title,
+ content: <ChartOptionSections sections={[{ ...section, title: undefined }]} />,
+ }))
+ : [
+ {
+ key: tab.key,
+ header: tab.label,
+ content: (
+ <ChartOptionSections
+ sections={
+ tab.sections.length === 1 ? [{ ...tab.sections[0], title: undefined }] : tab.sections
+ }
+ />
+ ),
+ },
+ ]
+ )
+ if (supportsGoalLines) {
+ panels.push({
+ key: 'goals',
+ header: (
+ <div className="flex items-center gap-1 flex-1">
+ <span className="flex-1">{isBIVisualization ? 'Reference lines' : 'Goal lines'}</span>
+ {goalLines.length > 0 && <LemonBadge.Number status="muted" size="small" count={goalLines.length} />}
</div>
- <LemonSwitch
- className="flex-1 w-full"
- label="Show tick labels"
- checked={chartSettings[name]?.showTicks ?? true}
- onChange={(value) => {
- updateChartSettings({ [name]: { showTicks: value } })
- }}
- />
-
- {!isBoxPlot && (
- <LemonSwitch
- className="flex-1 w-full"
- label="Begin at zero"
- checked={
- chartSettings[name]?.startAtZero ??
- (isScatterPlot ? false : (chartSettings.yAxisAtZero ?? true))
+ ),
+ content: (
+ <>
+ <GoalLinesList
+ allowCalculations={isBIVisualization}
+ calculationDisabledReason={
+ isStackedBarChart && chartSettings.stackBars100
+ ? 'Calculated lines are hidden on 100% stacked charts. Use a constant or turn off percentage stacking.'
+ : undefined
}
- onChange={(value) => {
- updateChartSettings({ [name]: { startAtZero: value } })
- }}
+ goalLines={goalLines}
+ removeGoalLine={removeGoalLine}
+ updateGoalLine={updateGoalLine}
/>
- )}
- <LemonSwitch
- className="flex-1 w-full"
- label="Show grid lines"
- checked={chartSettings[name]?.showGridLines ?? true}
- onChange={(value) => {
- updateChartSettings({ [name]: { showGridLines: value } })
- }}
- />
- </>
- )
+ <LemonButton onClick={addGoalLine} icon={<IconPlusSmall />} fullWidth>
+ {isBIVisualization ? 'Add reference line' : 'Add goal line'}
+ </LemonButton>
+ {isBIVisualization && (
+ <p className="text-xs text-secondary mb-0">
+ Calculations use returned marks on the left axis after aggregation and table calculations.
+ Per series adds a line for each color group or measure. Result limits apply.
+ {isStackedBarChart && chartSettings.stackBars100 && (
+ <span> Calculated lines are hidden on 100% stacked charts.</span>
+ )}
+ </p>
+ )}
+ </>
+ ),
+ })
}
- if (isMetric) {
- const metric = chartSettings.metric ?? {}
- const showChange = metric.showChange ?? METRIC_SHOW_CHANGE_DEFAULT
- const colorByDirection = metric.colorByDirection ?? METRIC_COLOR_BY_DIRECTION_DEFAULT
-
- return (
- <div className="flex flex-col w-full">
- <LemonCollapse
- embedded
- defaultActiveKeys={['metric']}
- multiple
- panels={[
- {
- key: 'metric',
- header: 'Metric',
- className: 'p-2 flex flex-col gap-2',
- content: (
- <>
- <div className="flex flex-col gap-1">
- <LemonLabel>Headline value</LemonLabel>
- <LemonSelect
- className="w-full"
- data-attr="data-visualization-metric-summary"
- value={metric.summary ?? SQL_METRIC_SUMMARY_DEFAULT}
- options={METRIC_SUMMARY_OPTIONS}
- onChange={(value) => updateChartSettings({ metric: { summary: value } })}
- fullWidth
- />
- </div>
- <LemonSwitch
- className="flex-1 w-full"
- label="Show change"
- checked={showChange}
- onChange={(value) => updateChartSettings({ metric: { showChange: value } })}
- />
- {showChange && (
- <MetricDirectionColorPickers
- className="gap-2"
- increaseColor={metric.changeIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR}
- decreaseColor={metric.changeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR}
- onIncrease={(color) =>
- updateChartSettings({ metric: { changeIncreaseColor: color } })
- }
- onDecrease={(color) =>
- updateChartSettings({ metric: { changeDecreaseColor: color } })
- }
- />
- )}
- <LemonSwitch
- className="flex-1 w-full"
- label="Color by trend"
- checked={colorByDirection}
- onChange={(value) =>
- updateChartSettings({ metric: { colorByDirection: value } })
- }
- />
- {colorByDirection && (
- <MetricDirectionColorPickers
- className="gap-2"
- increaseColor={metric.lineIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR}
- decreaseColor={metric.lineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR}
- onIncrease={(color) =>
- updateChartSettings({ metric: { lineIncreaseColor: color } })
- }
- onDecrease={(color) =>
- updateChartSettings({ metric: { lineDecreaseColor: color } })
- }
- />
- )}
- </>
- ),
- },
- ]}
- />
- </div>
- )
- }
-
- return (
- <div className="flex flex-col w-full">
- <LemonCollapse
- embedded
- defaultActiveKeys={['general']}
- multiple
- panels={[
- {
- key: 'general',
- header: 'General',
- className: 'p-2 flex flex-col gap-2',
- content: (
- <>
- <LemonSwitch
- className="flex-1 w-full"
- label="Show legend"
- checked={showLegend}
- onChange={(value) => {
- updateChartSettings({ showLegend: value })
- }}
- />
- <div className="flex items-center justify-between gap-2">
- <LemonLabel>Legend position</LemonLabel>
- <LemonSelect
- size="xsmall"
- value={
- chartSettings.legendPosition ??
- (isProportionBar ? 'bottom' : isPieChart ? 'right' : 'top')
- }
- options={LEGEND_POSITION_OPTIONS}
- disabledReason={
- showLegend ? undefined : 'Turn the legend on to set its position'
- }
- onChange={(value) => updateChartSettings({ legendPosition: value })}
- />
- </div>
- {isBoxPlot && (
- <LemonSwitch
- className="flex-1 w-full"
- label="Exclude outliers"
- checked={chartSettings.boxPlot?.excludeOutliers !== false}
- onChange={(value) => {
- updateChartSettings({ boxPlot: { excludeOutliers: value } })
- }}
- />
- )}
- {supportsAnnotations && (
- <LemonSwitch
- className="flex-1 w-full"
- data-attr="data-visualization-show-annotations"
- label="Show annotations"
- disabledReason={
- !isDateXAxis && 'Annotations need a Date or DateTime column on the X-axis'
- }
- checked={isDateXAxis && (chartSettings.showAnnotations ?? false)}
- onChange={(value) => {
- updateChartSettings({ showAnnotations: value })
- }}
- />
- )}
- {isPartOfWholeChart ? (
- <>
- {isPieChart && (
- <>
- <div className="flex flex-col gap-1">
- <LemonLabel>Show on slices</LemonLabel>
- <LemonSegmentedButton
- className="w-full"
- value={chartSettings.pie?.sliceContent ?? 'values'}
- onChange={(value) =>
- updateChartSettings({ pie: { sliceContent: value } })
- }
- options={PIE_SLICE_CONTENT_OPTIONS}
- fullWidth
- />
- </div>
- <div className="flex flex-col gap-1">
- <LemonLabel>Show values as</LemonLabel>
- <LemonSegmentedButton
- className="w-full"
- value={chartSettings.pie?.valueDisplay ?? 'absolute'}
- onChange={(value) =>
- updateChartSettings({ pie: { valueDisplay: value } })
- }
- options={PIE_VALUE_DISPLAY_OPTIONS}
- fullWidth
- />
- </div>
- </>
- )}
- <LemonSwitch
- className="flex-1 w-full"
- label={isDonutChart ? 'Show total in center' : 'Show total below chart'}
- checked={showsPieTotal(chartSettings, isProportionBar)}
- onChange={(value) => {
- updateChartSettings({ pie: { showTotal: value } })
- }}
- />
- </>
- ) : (
- <>
- {isScatterPlot && (
- <LemonSwitch
- className="flex-1 w-full"
- label="Show line of best fit"
- checked={chartSettings.scatter?.showBestFit ?? false}
- onChange={(value) => {
- updateChartSettings({ scatter: { showBestFit: value } })
- }}
- />
- )}
- {!isSingleAxisChart && (
- <>
- <LemonSwitch
- className="flex-1 w-full"
- label="Show total row"
- checked={chartSettings.showTotalRow ?? true}
- onChange={(value) => {
- updateChartSettings({ showTotalRow: value })
- }}
- />
- <LemonSwitch
- className="flex-1 w-full"
- label="Show nulls as zero"
- checked={chartSettings.showNullsAsZero ?? false}
- onChange={(value) => {
- updateChartSettings({ showNullsAsZero: value })
- }}
- />
- <LemonSwitch
- className="flex-1 w-full"
- label="Show values on series"
- checked={chartSettings.showValuesOnSeries ?? false}
- onChange={(value) => {
- updateChartSettings({ showValuesOnSeries: value })
- }}
- />
- </>
- )}
- {chartSettings.showValuesOnSeries && !isSingleAxisChart && (
- <>
- {!isLineChart && (
- <div className="flex items-center justify-between gap-2">
- <LemonLabel>Value position</LemonLabel>
- <LemonSelect
- size="xsmall"
- value={chartSettings.valueLabelPosition ?? 'end'}
- options={[
- { value: 'end', label: 'At the end' },
- { value: 'center', label: 'Inside' },
- ]}
- onChange={(valueLabelPosition) =>
- updateChartSettings({ valueLabelPosition })
- }
- />
- </div>
- )}
- <LemonSwitch
- label="Value background"
- checked={chartSettings.valueLabelBackground ?? true}
- onChange={(valueLabelBackground) =>
- updateChartSettings({ valueLabelBackground })
- }
- />
- <div className="flex items-center justify-between gap-2">
- <LemonLabel>Value font size</LemonLabel>
- <LemonSelect
- size="xsmall"
- value={chartSettings.valueLabelFontSize ?? 12}
- options={[8, 10, 12, 14, 16, 20, 24, 32].map((value) => ({
- value,
- label: `${value}px`,
- }))}
- onChange={(valueLabelFontSize) =>
- updateChartSettings({ valueLabelFontSize })
- }
- />
- </div>
- <div className="flex items-center justify-between gap-2">
- <LemonLabel>Value rotation</LemonLabel>
- <LemonSelect
- size="xsmall"
- value={chartSettings.valueLabelRotation ?? 0}
- options={[0, -45, -90, 45, 90].map((value) => ({
- value,
- label: `${value}°`,
- }))}
- onChange={(valueLabelRotation) =>
- updateChartSettings({ valueLabelRotation })
- }
- />
- </div>
- </>
- )}
- {(isStackedBarChart ||
- isHorizontalBarChart ||
- effectiveVisualizationType === ChartDisplayType.ActionsBar) && (
- <div className="flex items-center justify-between gap-2">
- <LemonLabel>Bar spacing</LemonLabel>
- <LemonSelect
- size="xsmall"
- value={chartSettings.barGap ?? 0.2}
- options={[
- { value: 0, label: 'None' },
- { value: 0.1, label: 'Small' },
- { value: 0.2, label: 'Medium' },
- { value: 0.4, label: 'Large' },
- ]}
- onChange={(barGap) => updateChartSettings({ barGap })}
- />
- </div>
- )}
- {isDateXAxis && (
- <div className="flex flex-col gap-1">
- <LemonLabel>Date format</LemonLabel>
- <LemonInput
- value={chartSettings.xAxisDateFormat ?? ''}
- placeholder="Automatic"
- onChange={(xAxisDateFormat) =>
- updateChartSettings({
- xAxisDateFormat: xAxisDateFormat || undefined,
- })
- }
- data-attr="chart-date-format"
- />
- <span className="text-xs text-secondary">
- For example, YYYY-MM-DD, MMM YYYY, or DD/MM/YYYY.
- </span>
- </div>
- )}
- {!isSingleAxisChart && (
- <div className="flex items-center justify-between gap-2">
- <LemonLabel>Tick label rotation</LemonLabel>
- <LemonSelect
- size="xsmall"
- value={chartSettings.xAxisTickRotation ?? null}
- options={[
- { value: null, label: 'Automatic' },
- ...[0, -45, -90, 45, 90].map((value) => ({
- value,
- label: `${value}°`,
- })),
- ]}
- onChange={(xAxisTickRotation) =>
- updateChartSettings({
- xAxisTickRotation: xAxisTickRotation ?? undefined,
- })
- }
- />
- </div>
- )}
- {isLineChart && (
- <div className="flex flex-col gap-1">
- <LemonLabel>Line style</LemonLabel>
- <LemonSegmentedButton
- className="w-full"
- data-attr="data-visualization-line-style"
- value={chartSettings.chartStyle?.curve ?? 'smooth'}
- onChange={(value) =>
- updateChartSettings({ chartStyle: { curve: value } })
- }
- options={LINE_STYLE_OPTIONS}
- fullWidth
- />
- </div>
- )}
- <div className="flex flex-col gap-1">
- <LemonLabel>
- {isHorizontalBarChart ? 'Y-axis label' : 'X-axis label'}
- </LemonLabel>
- <LemonInput
- data-attr="data-visualization-x-axis-label-input"
- value={chartSettings.xAxisLabel ?? ''}
- placeholder={isHorizontalBarChart ? 'Y-axis label' : 'X-axis label'}
- onChange={(value) => {
- updateChartSettings({ xAxisLabel: value })
- }}
- />
- </div>
- <LemonSwitch
- className="flex-1 w-full"
- label={
- isHorizontalBarChart
- ? 'Show Y-axis tick labels'
- : 'Show X-axis tick labels'
- }
- checked={chartSettings.showXAxisTicks ?? true}
- onChange={(value) => {
- updateChartSettings({ showXAxisTicks: value })
- }}
- />
- {/* Quill's scatter draws both axis lines together, so a
- per-edge toggle can't be honored there. */}
- {!isScatterPlot && (
- <>
- <LemonSwitch
- className="flex-1 w-full"
- label={
- isHorizontalBarChart
- ? 'Show Y-axis border'
- : 'Show X-axis border'
- }
- checked={chartSettings.showXAxisBorder ?? true}
- onChange={(value) => {
- updateChartSettings({ showXAxisBorder: value })
- }}
- />
- <LemonSwitch
- className="flex-1 w-full"
- label={
- isHorizontalBarChart
- ? 'Show X-axis border'
- : 'Show Y-axis border'
- }
- checked={chartSettings.showYAxisBorder ?? true}
- onChange={(value) => {
- updateChartSettings({ showYAxisBorder: value })
- }}
- />
- </>
- )}
- </>
- )}
- </>
- ),
- },
- isScatterPlot
- ? {
- key: 'x-axis',
- header: 'X-axis',
- className: 'p-2 flex flex-col gap-2',
- content: (
- <>
- <div className="flex gap-2 items-center justify-between">
- <span className="font-medium">Scale</span>
- <LemonSelect
- size="xsmall"
- value={chartSettings.scatter?.xScale ?? 'linear'}
- options={[
- { value: 'linear', label: 'Linear' },
- { value: 'logarithmic', label: 'Logarithmic' },
- ]}
- onChange={(value) => {
- updateChartSettings({ scatter: { xScale: value } })
- }}
- />
- </div>
- <LemonSwitch
- className="flex-1 w-full"
- label="Begin at zero"
- checked={chartSettings.scatter?.xStartAtZero ?? false}
- onChange={(value) => {
- updateChartSettings({ scatter: { xStartAtZero: value } })
- }}
- />
- </>
- ),
- }
- : null,
- !isPartOfWholeChart
- ? {
- key: 'left-y-axis',
- header: isHorizontalBarChart ? 'X-axis' : supportsRightYAxis ? 'Left Y-axis' : 'Y-axis',
- className: 'p-2 flex flex-col gap-2',
- content: renderYAxisSettings('leftYAxisSettings'),
- }
- : null,
- !isPartOfWholeChart && supportsRightYAxis
- ? {
- key: 'right-y-axis',
- header: 'Right Y-axis',
- className: 'p-2 flex flex-col gap-2',
- content: renderYAxisSettings('rightYAxisSettings'),
- }
- : null,
- isStackedBarChart
- ? {
- key: 'stacked-bar-chart',
- header: 'Stack bars',
- className: 'p-2 flex flex-col gap-2',
- content: (
- <LemonSwitch
- className="flex-1"
- label="Stack bars 100%"
- checked={chartSettings.stackBars100 ?? false}
- onChange={(value) => {
- updateChartSettings({ stackBars100: value })
- }}
- />
- ),
- }
- : null,
- !isPartOfWholeChart && !isSingleAxisChart
- ? {
- key: 'goals',
- header: (
- <div className="flex items-center gap-1 flex-1">
- <span className="flex-1">
- {query.kind === 'BIVisualizationNode' ? 'Reference lines' : 'Goals'}
- </span>
- {goalLines.length > 0 && (
- <LemonBadge.Number status="muted" size="small" count={goalLines.length} />
- )}
- </div>
- ),
- className: 'p-2',
- content: (
- <>
- <GoalLinesList
- allowCalculations={query.kind === 'BIVisualizationNode'}
- calculationDisabledReason={
- isStackedBarChart && chartSettings.stackBars100
- ? 'Calculated lines are hidden on 100% stacked charts. Use a constant or turn off percentage stacking.'
- : undefined
- }
- goalLines={goalLines}
- removeGoalLine={removeGoalLine}
- updateGoalLine={updateGoalLine}
- />
- <LemonButton
- className="mt-1"
- onClick={addGoalLine}
- icon={<IconPlusSmall />}
- fullWidth
- >
- {query.kind === 'BIVisualizationNode'
- ? 'Add reference line'
- : 'Add goal line'}
- </LemonButton>
- {query.kind === 'BIVisualizationNode' && (
- <p className="text-xs text-secondary mt-2 mb-0">
- Calculations use returned marks on the left axis after aggregation and
- table calculations. Per series adds a line for each color group or
- measure. Result limits apply.
- {isStackedBarChart && chartSettings.stackBars100 && (
- <span> Calculated lines are hidden on 100% stacked charts.</span>
- )}
- </p>
- )}
- </>
- ),
- }
- : null,
- ]}
- />
- </div>
- )
+ return <DisplayTabPanels defaultOpenKeys={['general']} panels={panels} />
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTabPanels.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTabPanels.tsx
new file mode 100644
index 000000000000..d0a79f19601c
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTabPanels.tsx
@@ -0,0 +1,27 @@
+import { ReactNode } from 'react'
+
+import { LemonCollapse } from '@posthog/lemon-ui'
+
+export interface DisplayTabPanel {
+ key: string
+ header: ReactNode
+ content: ReactNode
+}
+
+export interface DisplayTabPanelsProps {
+ panels: DisplayTabPanel[]
+ defaultOpenKeys: string[]
+}
+
+export function DisplayTabPanels({ panels, defaultOpenKeys }: DisplayTabPanelsProps): JSX.Element {
+ return (
+ <div className="flex flex-col w-full">
+ <LemonCollapse
+ embedded
+ multiple
+ defaultActiveKeys={defaultOpenKeys}
+ panels={panels.map((panel) => ({ ...panel, className: 'p-2 flex flex-col gap-2' }))}
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/sqlDisplayOptions.tsx b/frontend/src/queries/nodes/DataVisualization/Components/sqlDisplayOptions.tsx
new file mode 100644
index 000000000000..fd8541cd6e9f
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/sqlDisplayOptions.tsx
@@ -0,0 +1,360 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { DisplayOptionBindings } from 'lib/components/ChartOptions/displayOptions'
+import type { DisplayOptionsAdapter } from 'lib/components/ChartOptions/useDisplayOptions'
+import {
+ METRIC_COLOR_BY_DIRECTION_DEFAULT,
+ METRIC_DEFAULT_DECREASE_COLOR,
+ METRIC_DEFAULT_INCREASE_COLOR,
+ METRIC_SHOW_CHANGE_DEFAULT,
+} from 'lib/components/Metric/metricSummary'
+import { PART_OF_WHOLE_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'
+
+import { ChartDisplayType } from '~/types'
+
+import { dataVisualizationLogic } from '../dataVisualizationLogic'
+import { displayLogic, type displayLogicType } from '../displayLogic'
+import { buildPieSlices, partOfWholeChartData, showsLegendByDefault, showsPieTotal } from './Charts/sqlPieGraphAdapter'
+import { SQL_METRIC_SUMMARY_DEFAULT } from './Charts/useSqlMetricModel'
+import { seriesBreakdownLogic } from './seriesBreakdownLogic'
+
+interface SqlDisplayContext
+ extends
+ Pick<displayLogicType['values'], 'chartSettings'>,
+ Pick<displayLogicType['actions'], 'updateChartSettings'> {
+ isMetric: boolean
+ isPieChart: boolean
+ isProportionBar: boolean
+ isPartOfWholeChart: boolean
+ isStackedBarChart: boolean
+ isBarChart: boolean
+ isScatterPlot: boolean
+ isBoxPlot: boolean
+ isHorizontalBarChart: boolean
+ isLineChart: boolean
+ isSingleAxisChart: boolean
+ isDateXAxis: boolean
+ supportsAnnotations: boolean
+ showsAxes: boolean
+ showsSeriesOptions: boolean
+ showsRightYAxis: boolean
+ showLegend: boolean
+}
+
+function useSqlDisplayContext(): SqlDisplayContext {
+ const { effectiveVisualizationType, xData, yData, dataVisualizationProps } = useValues(dataVisualizationLogic)
+ const { seriesBreakdownData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
+ const { chartSettings } = useValues(displayLogic)
+ const { updateChartSettings } = useActions(displayLogic)
+
+ const type = effectiveVisualizationType
+ const isMetric = type === ChartDisplayType.Metric
+ const isProportionBar = type === ChartDisplayType.ActionsProportionBar
+ const isPartOfWholeChart = PART_OF_WHOLE_DISPLAY_TYPES.includes(type)
+ const isScatterPlot = type === ChartDisplayType.ScatterPlot
+ const isBoxPlot = type === ChartDisplayType.BoxPlot
+ const isHorizontalBarChart = type === ChartDisplayType.ActionsBarValue
+ const isLineChart = type === ChartDisplayType.ActionsLineGraph || type === ChartDisplayType.ActionsAreaGraph
+ // Scatter and box plots have a single Y axis, so there is no separate right axis to configure.
+ const isSingleAxisChart = isScatterPlot || isBoxPlot
+ const showsAxes = !isMetric && !isPartOfWholeChart
+ const proportionBarPartCount = useMemo(() => {
+ if (!isProportionBar) {
+ return 0
+ }
+ const pieData = partOfWholeChartData(seriesBreakdownData, xData, yData)
+ return buildPieSlices(pieData.xData, pieData.yData).length
+ }, [isProportionBar, seriesBreakdownData, xData, yData])
+
+ return {
+ chartSettings,
+ updateChartSettings,
+ isMetric,
+ isPieChart: PIE_DISPLAY_TYPES.includes(type),
+ isProportionBar,
+ isPartOfWholeChart,
+ isStackedBarChart: type === ChartDisplayType.ActionsStackedBar,
+ isBarChart: type === ChartDisplayType.ActionsBar,
+ isScatterPlot,
+ isBoxPlot,
+ isHorizontalBarChart,
+ isLineChart,
+ isSingleAxisChart,
+ isDateXAxis: xData?.column.type.name === 'DATE' || xData?.column.type.name === 'DATETIME',
+ supportsAnnotations:
+ isLineChart || type === ChartDisplayType.ActionsBar || type === ChartDisplayType.ActionsStackedBar,
+ showsAxes,
+ showsSeriesOptions: showsAxes && !isSingleAxisChart,
+ showsRightYAxis: showsAxes && !isSingleAxisChart && !isHorizontalBarChart,
+ showLegend: chartSettings.showLegend ?? showsLegendByDefault(isProportionBar, proportionBarPartCount),
+ }
+}
+
+function showsMetricChange(c: SqlDisplayContext): boolean {
+ return c.chartSettings.metric?.showChange ?? METRIC_SHOW_CHANGE_DEFAULT
+}
+
+function colorsMetricByDirection(c: SqlDisplayContext): boolean {
+ return c.chartSettings.metric?.colorByDirection ?? METRIC_COLOR_BY_DIRECTION_DEFAULT
+}
+
+const SQL_BINDINGS: DisplayOptionBindings<SqlDisplayContext> = {
+ metricSummary: {
+ showCondition: (c) => c.isMetric,
+ value: (c) => c.chartSettings.metric?.summary ?? SQL_METRIC_SUMMARY_DEFAULT,
+ onChange: (summary, c) => c.updateChartSettings({ metric: { summary } }),
+ dataAttr: 'data-visualization-metric-summary',
+ },
+ metricShowChange: {
+ showCondition: (c) => c.isMetric,
+ value: showsMetricChange,
+ onChange: (showChange, c) => c.updateChartSettings({ metric: { showChange } }),
+ },
+ metricChangeColors: {
+ showCondition: (c) => c.isMetric && showsMetricChange(c),
+ value: (c) => ({
+ increase: c.chartSettings.metric?.changeIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR,
+ decrease: c.chartSettings.metric?.changeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR,
+ }),
+ onChange: ({ increase, decrease }, c) =>
+ c.updateChartSettings({ metric: { changeIncreaseColor: increase, changeDecreaseColor: decrease } }),
+ },
+ metricColorByDirection: {
+ showCondition: (c) => c.isMetric,
+ value: colorsMetricByDirection,
+ onChange: (colorByDirection, c) => c.updateChartSettings({ metric: { colorByDirection } }),
+ },
+ metricTrendColors: {
+ showCondition: (c) => c.isMetric && colorsMetricByDirection(c),
+ value: (c) => ({
+ increase: c.chartSettings.metric?.lineIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR,
+ decrease: c.chartSettings.metric?.lineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR,
+ }),
+ onChange: ({ increase, decrease }, c) =>
+ c.updateChartSettings({ metric: { lineIncreaseColor: increase, lineDecreaseColor: decrease } }),
+ },
+ valuesOnSeries: {
+ showCondition: (c) => c.showsSeriesOptions,
+ value: (c) => c.chartSettings.showValuesOnSeries ?? false,
+ onChange: (showValuesOnSeries, c) => c.updateChartSettings({ showValuesOnSeries }),
+ },
+ valueLabelPosition: {
+ showCondition: (c) => c.showsSeriesOptions && !!c.chartSettings.showValuesOnSeries && !c.isLineChart,
+ value: (c) => c.chartSettings.valueLabelPosition ?? 'end',
+ onChange: (valueLabelPosition, c) => c.updateChartSettings({ valueLabelPosition }),
+ },
+ valueLabelBackground: {
+ showCondition: (c) => c.showsSeriesOptions && !!c.chartSettings.showValuesOnSeries,
+ value: (c) => c.chartSettings.valueLabelBackground ?? true,
+ onChange: (valueLabelBackground, c) => c.updateChartSettings({ valueLabelBackground }),
+ },
+ valueLabelFontSize: {
+ showCondition: (c) => c.showsSeriesOptions && !!c.chartSettings.showValuesOnSeries,
+ value: (c) => c.chartSettings.valueLabelFontSize ?? 12,
+ onChange: (valueLabelFontSize, c) => c.updateChartSettings({ valueLabelFontSize }),
+ },
+ valueLabelRotation: {
+ showCondition: (c) => c.showsSeriesOptions && !!c.chartSettings.showValuesOnSeries,
+ value: (c) => c.chartSettings.valueLabelRotation ?? 0,
+ onChange: (valueLabelRotation, c) => c.updateChartSettings({ valueLabelRotation }),
+ },
+ percentStack: {
+ showCondition: (c) => c.isStackedBarChart,
+ value: (c) => c.chartSettings.stackBars100 ?? false,
+ onChange: (stackBars100, c) => c.updateChartSettings({ stackBars100 }),
+ },
+ pieSliceContent: {
+ showCondition: (c) => c.isPieChart,
+ value: (c) => c.chartSettings.pie?.sliceContent ?? 'values',
+ onChange: (sliceContent, c) => c.updateChartSettings({ pie: { sliceContent } }),
+ },
+ pieValueDisplay: {
+ showCondition: (c) => c.isPieChart,
+ value: (c) => c.chartSettings.pie?.valueDisplay ?? 'absolute',
+ onChange: (valueDisplay, c) => c.updateChartSettings({ pie: { valueDisplay } }),
+ },
+ pieTotal: {
+ showCondition: (c) => c.isPartOfWholeChart,
+ value: (c) => showsPieTotal(c.chartSettings, c.isProportionBar),
+ onChange: (showTotal, c) => c.updateChartSettings({ pie: { showTotal } }),
+ },
+ showTotalRow: {
+ showCondition: (c) => c.showsSeriesOptions,
+ value: (c) => c.chartSettings.showTotalRow ?? true,
+ onChange: (showTotalRow, c) => c.updateChartSettings({ showTotalRow }),
+ },
+ showNullsAsZero: {
+ showCondition: (c) => c.showsSeriesOptions,
+ value: (c) => c.chartSettings.showNullsAsZero ?? false,
+ onChange: (showNullsAsZero, c) => c.updateChartSettings({ showNullsAsZero }),
+ },
+ barSpacing: {
+ showCondition: (c) => c.isStackedBarChart || c.isHorizontalBarChart || c.isBarChart,
+ value: (c) => c.chartSettings.barGap ?? 0.2,
+ onChange: (barGap, c) => c.updateChartSettings({ barGap }),
+ },
+ legend: {
+ showCondition: (c) => !c.isMetric,
+ value: (c) => c.showLegend,
+ onChange: (showLegend, c) => c.updateChartSettings({ showLegend }),
+ },
+ legendPosition: {
+ showCondition: (c) => !c.isMetric,
+ value: (c) => c.chartSettings.legendPosition ?? (c.isProportionBar ? 'bottom' : c.isPieChart ? 'right' : 'top'),
+ onChange: (legendPosition, c) => c.updateChartSettings({ legendPosition }),
+ disabledReason: (c) => (c.showLegend ? undefined : 'Turn the legend on to set its position'),
+ },
+ excludeOutliers: {
+ showCondition: (c) => c.isBoxPlot,
+ value: (c) => c.chartSettings.boxPlot?.excludeOutliers !== false,
+ onChange: (excludeOutliers, c) => c.updateChartSettings({ boxPlot: { excludeOutliers } }),
+ },
+ annotations: {
+ showCondition: (c) => c.supportsAnnotations,
+ value: (c) =>
+ c.isDateXAxis && c.chartSettings.showAnnotations ? (c.chartSettings.annotationsScope ?? 'all') : 'none',
+ onChange: (selection, c) =>
+ c.updateChartSettings({
+ showAnnotations: selection !== 'none',
+ annotationsScope: selection === 'all' || selection === 'none' ? undefined : selection,
+ }),
+ disabledReason: (c) =>
+ !c.isDateXAxis ? 'Annotations need a Date or DateTime column on the X-axis' : undefined,
+ dataAttr: 'data-visualization-show-annotations',
+ },
+
+ xAxisLabel: {
+ showCondition: (c) => c.showsAxes,
+ value: (c) => c.chartSettings.xAxisLabel,
+ onChange: (xAxisLabel, c) => c.updateChartSettings({ xAxisLabel }),
+ dataAttr: 'data-visualization-x-axis-label-input',
+ },
+ xAxisScale: {
+ showCondition: (c) => c.showsAxes && c.isScatterPlot,
+ value: (c) => (c.chartSettings.scatter?.xScale === 'logarithmic' ? 'log' : 'linear'),
+ onChange: (scale, c) =>
+ c.updateChartSettings({ scatter: { xScale: scale === 'log' ? 'logarithmic' : 'linear' } }),
+ },
+ xAxisBeginAtZero: {
+ showCondition: (c) => c.showsAxes && c.isScatterPlot,
+ value: (c) => c.chartSettings.scatter?.xStartAtZero ?? false,
+ onChange: (xStartAtZero, c) => c.updateChartSettings({ scatter: { xStartAtZero } }),
+ },
+ xAxisDateFormat: {
+ showCondition: (c) => c.showsAxes && c.isDateXAxis,
+ value: (c) => c.chartSettings.xAxisDateFormat,
+ onChange: (xAxisDateFormat, c) => c.updateChartSettings({ xAxisDateFormat }),
+ dataAttr: 'chart-date-format',
+ },
+ xAxisTickRotation: {
+ showCondition: (c) => c.showsSeriesOptions,
+ value: (c) => c.chartSettings.xAxisTickRotation ?? 'auto',
+ onChange: (rotation, c) =>
+ c.updateChartSettings({ xAxisTickRotation: rotation === 'auto' ? undefined : rotation }),
+ },
+ xAxisShowTicks: {
+ showCondition: (c) => c.showsAxes,
+ value: (c) => c.chartSettings.showXAxisTicks ?? true,
+ onChange: (showXAxisTicks, c) => c.updateChartSettings({ showXAxisTicks }),
+ },
+ // Quill's scatter draws both axis lines together, so a per-edge toggle can't be honored there.
+ xAxisBorder: {
+ showCondition: (c) => c.showsAxes && !c.isScatterPlot,
+ value: (c) => c.chartSettings.showXAxisBorder ?? true,
+ onChange: (showXAxisBorder, c) => c.updateChartSettings({ showXAxisBorder }),
+ },
+
+ yAxisLabel: {
+ showCondition: (c) => c.showsAxes,
+ value: (c) => c.chartSettings.leftYAxisSettings?.label,
+ onChange: (label, c) => c.updateChartSettings({ leftYAxisSettings: { label } }),
+ dataAttr: 'data-visualization-left-y-axis-label-input',
+ },
+ yAxisBeginAtZero: {
+ showCondition: (c) => c.showsAxes && !c.isBoxPlot,
+ value: (c) =>
+ c.chartSettings.leftYAxisSettings?.startAtZero ??
+ (c.isScatterPlot ? false : (c.chartSettings.yAxisAtZero ?? true)),
+ onChange: (startAtZero, c) => c.updateChartSettings({ leftYAxisSettings: { startAtZero } }),
+ },
+ yAxisShowTicks: {
+ showCondition: (c) => c.showsAxes,
+ value: (c) => c.chartSettings.leftYAxisSettings?.showTicks ?? true,
+ onChange: (showTicks, c) => c.updateChartSettings({ leftYAxisSettings: { showTicks } }),
+ },
+ yAxisGridLines: {
+ showCondition: (c) => c.showsAxes,
+ value: (c) => c.chartSettings.leftYAxisSettings?.showGridLines ?? true,
+ onChange: (showGridLines, c) => c.updateChartSettings({ leftYAxisSettings: { showGridLines } }),
+ },
+ yAxisBorder: {
+ showCondition: (c) => c.showsAxes && !c.isScatterPlot,
+ value: (c) => c.chartSettings.showYAxisBorder ?? true,
+ onChange: (showYAxisBorder, c) => c.updateChartSettings({ showYAxisBorder }),
+ },
+ yAxisScale: {
+ showCondition: (c) => c.showsAxes,
+ value: (c) => (c.chartSettings.leftYAxisSettings?.scale === 'logarithmic' ? 'log' : 'linear'),
+ onChange: (scale, c) =>
+ c.updateChartSettings({ leftYAxisSettings: { scale: scale === 'log' ? 'logarithmic' : 'linear' } }),
+ },
+
+ rightYAxisLabel: {
+ showCondition: (c) => c.showsRightYAxis,
+ value: (c) => c.chartSettings.rightYAxisSettings?.label,
+ onChange: (label, c) => c.updateChartSettings({ rightYAxisSettings: { label } }),
+ dataAttr: 'data-visualization-right-y-axis-label-input',
+ },
+ rightYAxisBeginAtZero: {
+ showCondition: (c) => c.showsRightYAxis,
+ value: (c) => c.chartSettings.rightYAxisSettings?.startAtZero ?? c.chartSettings.yAxisAtZero ?? true,
+ onChange: (startAtZero, c) => c.updateChartSettings({ rightYAxisSettings: { startAtZero } }),
+ },
+ rightYAxisShowTicks: {
+ showCondition: (c) => c.showsRightYAxis,
+ value: (c) => c.chartSettings.rightYAxisSettings?.showTicks ?? true,
+ onChange: (showTicks, c) => c.updateChartSettings({ rightYAxisSettings: { showTicks } }),
+ },
+ rightYAxisGridLines: {
+ showCondition: (c) => c.showsRightYAxis,
+ value: (c) => c.chartSettings.rightYAxisSettings?.showGridLines ?? true,
+ onChange: (showGridLines, c) => c.updateChartSettings({ rightYAxisSettings: { showGridLines } }),
+ },
+ rightYAxisScale: {
+ showCondition: (c) => c.showsRightYAxis,
+ value: (c) => (c.chartSettings.rightYAxisSettings?.scale === 'logarithmic' ? 'log' : 'linear'),
+ onChange: (scale, c) =>
+ c.updateChartSettings({ rightYAxisSettings: { scale: scale === 'log' ? 'logarithmic' : 'linear' } }),
+ },
+
+ lineStyle: {
+ showCondition: (c) => c.isLineChart,
+ value: (c) => c.chartSettings.chartStyle?.curve ?? 'smooth',
+ onChange: (curve, c) => c.updateChartSettings({ chartStyle: { curve } }),
+ dataAttr: 'data-visualization-line-style',
+ },
+ trendLines: {
+ showCondition: (c) => c.isScatterPlot,
+ value: (c) => c.chartSettings.scatter?.showBestFit ?? false,
+ onChange: (showBestFit, c) => c.updateChartSettings({ scatter: { showBestFit } }),
+ },
+}
+
+// The SQL editor's Display tab and the options menu on a dashboard tile for a SQL chart.
+export const sqlDisplayOptions: DisplayOptionsAdapter<SqlDisplayContext> = {
+ useDisplayContext: useSqlDisplayContext,
+ bindings: SQL_BINDINGS,
+ settings: (c) => {
+ // The horizontal bar chart swaps its axes, so the category axis is the Y-axis there.
+ const categoryAxisName = c.isHorizontalBarChart ? 'Y-axis' : 'X-axis'
+ const valueAxisName = c.isHorizontalBarChart ? 'X-axis' : 'Y-axis'
+ return {
+ groups: {
+ 'x-axis': { title: categoryAxisName },
+ 'y-axis': { title: c.showsRightYAxis ? `Left ${valueAxisName}` : valueAxisName },
+ 'right-y-axis': { title: `Right ${valueAxisName}` },
+ },
+ }
+ },
+}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index ebfb6011a31f..b680bd7d7027 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -18143,6 +18143,10 @@
"ChartSettings": {
"additionalProperties": false,
"properties": {
+ "annotationsScope": {
+ "$ref": "#/definitions/AnnotationScope",
+ "description": "Shows only the annotations saved at this level. Unset shows every level."
+ },
"barGap": {
"type": "number"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 01cc4c39123b..bb460da26f3c 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1592,6 +1592,8 @@ export interface ChartSettings {
showYAxisBorder?: boolean
showLegend?: boolean
showAnnotations?: boolean
+ /** Shows only the annotations saved at this level. Unset shows every level. */
+ annotationsScope?: AnnotationScope
/** Where the legend sits relative to the chart. Unset falls back per chart type: right for pie and donut, bottom for proportion bar, top for the rest. */
legendPosition?: 'top' | 'bottom' | 'left' | 'right'
showValuesOnSeries?: boolean
diff --git a/playwright/e2e/sql-editor-axis-labels.spec.ts b/playwright/e2e/sql-editor-axis-labels.spec.ts
index 22230d59131c..643c64f9e0c6 100644
--- a/playwright/e2e/sql-editor-axis-labels.spec.ts
+++ b/playwright/e2e/sql-editor-axis-labels.spec.ts
@@ -72,11 +72,14 @@ test.describe('SQL editor axis labels', () => {
await page.getByTestId('sql-editor-visualization-settings-button').click()
await page.getByRole('tab', { name: 'Display' }).click()
+ await page.getByText('X-axis', { exact: true }).click()
+ await page.getByText('Left Y-axis', { exact: true }).click()
+ await page.getByText('Right Y-axis', { exact: true }).click()
await page.getByTestId('data-visualization-x-axis-label-input').fill('Event name')
- await page.getByText('Left Y-axis').click()
await page.getByTestId('data-visualization-left-y-axis-label-input').fill('Events')
- await page.getByText('Right Y-axis').click()
await page.getByTestId('data-visualization-right-y-axis-label-input').fill('People')
+ // Labels save when the field loses focus.
+ await page.keyboard.press('Tab')
const saveRequestPromise = page.waitForResponse(
(response) =>
@@ -93,10 +96,11 @@ test.describe('SQL editor axis labels', () => {
await page.getByTestId('sql-editor-visualization-settings-button').click()
await page.getByRole('tab', { name: 'Display' }).click()
+ await page.getByText('X-axis', { exact: true }).click()
+ await page.getByText('Left Y-axis', { exact: true }).click()
+ await page.getByText('Right Y-axis', { exact: true }).click()
await expect(page.getByTestId('data-visualization-x-axis-label-input')).toHaveValue('Event name')
- await page.getByText('Left Y-axis').click()
await expect(page.getByTestId('data-visualization-left-y-axis-label-input')).toHaveValue('Events')
- await page.getByText('Right Y-axis').click()
await expect(page.getByTestId('data-visualization-right-y-axis-label-input')).toHaveValue('People')
})
})
diff --git a/posthog/schema.py b/posthog/schema.py
index 9ec592437b31..c86533913bb5 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -17498,6 +17498,10 @@ class ChartSettings(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ annotationsScope: AnnotationScope | None = Field(
+ default=None,
+ description=("Shows only the annotations saved at this level. Unset shows every level."),
+ )
barGap: float | None = None
boxPlot: BoxPlotSettings | None = None
chartStyle: ChartStyle | None = Field(
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 3bf606736dc7..9c50420ae698 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9441,6 +9441,8 @@ export interface ChartAxisApi {
export type ChartSettingsApiResultCustomizations = { [key: string]: ResultCustomizationByValueApi } | null
export interface ChartSettingsApi {
+ /** Shows only the annotations saved at this level. Unset shows every level. */
+ annotationsScope?: AnnotationScopeApi | null
barGap?: number | null
boxPlot?: BoxPlotSettingsApi | null
/** Chart rendering style overrides (line shape). Only applies to line and area charts. */
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 6a3fef4953f6..1f8da1131518 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -4912,6 +4912,7 @@ export namespace Schemas {
settings?: (Settings | null) | undefined;
};
export type ChartSettings = Partial<{
+ annotationsScope: AnnotationScope | null;
barGap: number | null;
boxPlot: BoxPlotSettings | null;
chartStyle: ChartStyle | null;
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 01bb49ae5a3d..bc4c3f3c1276 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8247,6 +8247,8 @@ export interface ChartAxisApi {
export type ChartSettingsApiResultCustomizations = { [key: string]: ResultCustomizationByValueApi } | null
export interface ChartSettingsApi {
+ /** Shows only the annotations saved at this level. Unset shows every level. */
+ annotationsScope?: AnnotationScopeApi | null
barGap?: number | null
boxPlot?: BoxPlotSettingsApi | null
/** Chart rendering style overrides (line shape). Only applies to line and area charts. */
diff --git a/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx b/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx
index ebde34646771..4f51d2a00fa2 100644
--- a/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx
+++ b/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx
@@ -165,11 +165,11 @@ describe('InsightDisplayConfig', () => {
{
tabs: ['General', 'Axes', 'Lines'],
sections: {
- General: ['Annotations', 'Unit', 'Color customization by'],
+ General: ['Unit', 'Color customization by'],
Axes: ['X-axis', 'Y-axis'],
Lines: ['Style', 'Overlays'],
},
- displayItems: ['Show values on series', 'Show legend', 'Legend positionBottom'],
+ displayItems: ['Show values on series', 'Show legend', 'Legend positionBottom', 'Annotations All'],
overlayItems: lineOverlays,
},
],
@@ -179,7 +179,7 @@ describe('InsightDisplayConfig', () => {
{
tabs: ['General', 'Axes', 'Lines'],
sections: {
- General: ['Annotations', 'Unit'],
+ General: ['Unit'],
Axes: ['X-axis', 'Y-axis'],
Lines: ['Overlays'],
},
@@ -188,6 +188,7 @@ describe('InsightDisplayConfig', () => {
'Show as % of total',
'Show legend',
'Legend positionBottom',
+ 'Annotations All',
],
overlayItems: lineOverlays,
},
@@ -198,7 +199,7 @@ describe('InsightDisplayConfig', () => {
{
tabs: ['General', 'Axes', 'Lines'],
sections: {
- General: ['Annotations', 'Unit'],
+ General: ['Unit'],
Axes: ['X-axis', 'Y-axis'],
Lines: ['Style', 'Overlays'],
},
@@ -207,6 +208,7 @@ describe('InsightDisplayConfig', () => {
'Show as % of total',
'Show legend',
'Legend positionBottom',
+ 'Annotations All',
],
},
],
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a10c3bf4c6e4..13aabb65b289 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11231,6 +11231,8 @@ export namespace Schemas {
export type ChartSettingsResultCustomizations = {[key: string]: ResultCustomizationByValue} | null;
export interface ChartSettings {
+ /** Shows only the annotations saved at this level. Unset shows every level. */
+ annotationsScope?: AnnotationScope | null;
barGap?: number | null;
boxPlot?: BoxPlotSettings | null;
/** Chart rendering style overrides (line shape). Only applies to line and area charts. */