:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(insights): define chart display options once, starting with insights (#126737)
Sam Penningtoned683152b1d5
diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txtindex 350806c891fc..8993c30b6b1a 100644--- a/frontend/bin/layer-baseline.txt+++ b/frontend/bin/layer-baseline.txt@@ -247,9 +247,6 @@ frontend/src/lib/components/SessionTimeline/timeline/items/logs.tsx -> products/frontend/src/lib/components/SessionTimeline/timeline/items/page.tsx -> products/error_tracking/frontend/components/RuntimeIcon.tsxfrontend/src/lib/components/Sharing/SharingModal.tsx -> frontend/src/queries/nodes/InsightQuery/defaults.tsfrontend/src/lib/components/Sharing/SharingModal.tsx -> frontend/src/scenes/insights/insightVizDataLogic.ts-frontend/src/lib/components/SmoothingFilter/SmoothingFilter.tsx -> frontend/src/scenes/insights/insightLogic.tsx-frontend/src/lib/components/SmoothingFilter/SmoothingFilter.tsx -> frontend/src/scenes/insights/insightVizDataLogic.ts-frontend/src/lib/components/SmoothingFilter/SmoothingFilter.tsx -> products/product_analytics/frontend/insights/trends/trendsDataLogic.tsfrontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx -> frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsxfrontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx -> frontend/src/scenes/surveys/surveyLogic.tsxfrontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx -> frontend/src/scenes/surveys/utils.tsdiff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsxindex 47d8c3525f2e..c408d5ffae4c 100644--- a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx@@ -1,15 +1,15 @@import { IconChevronRight } from '@posthog/icons'+import { DisplayOptionTab } from 'lib/components/ChartOptions/displayOptions'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'import { LemonMenuItems, LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu'-import { DisplayOptionTab } from 'products/product_analytics/frontend/insights/editor/insightDisplayOptions'import { InsightDisplayOptionsPanel } from 'products/product_analytics/frontend/insights/editor/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+// useDisplayOptions(insightDisplayOptions) 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({visualizationItems,diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex 90808fd9d960..3c04f900bbfd 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -10,6 +10,7 @@ import { CardMetaRefreshButton } from 'lib/components/Cards/CardMetaRefreshButtoimport { CompactInfoPopover } from 'lib/components/Cards/InsightCard/CompactInfoPopover'import { DashboardTileRefreshDataButton } from 'lib/components/Cards/InsightCard/DashboardTileRefreshDataButton'import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'+import { useDisplayOptions } from 'lib/components/ChartOptions/useDisplayOptions'import { ExportButton } from 'lib/components/ExportButton/ExportButton'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { captureImageLogic } from 'lib/components/Scenes/InsightOrDashboard/captureImageLogic'@@ -77,7 +78,7 @@ import type { AlertType } from 'products/alerts/frontend/types'import { ManageAlertsModal } from 'products/alerts/frontend/views/ManageAlertsModal'import { dataRetentionBannerLogic } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'import { exceedsRetention } from 'products/product_analytics/frontend/insights/dataRetention/exceedsRetention'-import { useInsightDisplayOptions } from 'products/product_analytics/frontend/insights/editor/insightDisplayOptions'+import { insightDisplayOptions } from 'products/product_analytics/frontend/insights/editor/insightDisplayOptions'import { DashboardInsightDisplayOptions } from './DashboardInsightDisplayOptions'import { useDashboardVisualizationOptions } from './dashboardVisualizationOptions'@@ -303,7 +304,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 { tabs: displayOptionTabs } = useInsightDisplayOptions()+ const { tabs: displayOptionTabs } = useDisplayOptions(insightDisplayOptions)const dashboardVisualizationPersistence: DashboardVisualizationPersistence | undefined = persistDisplayOptions? {saving: savingSqlVisualization,diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionLabel.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionLabel.tsxnew file mode 100644index 000000000000..9dfaba2b634c--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionLabel.tsx@@ -0,0 +1,26 @@+import { IconInfo } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++export interface ChartOptionLabelProps {+ label: string+ info?: string+ /** The id of the input this label names. */+ htmlFor?: string+}++export function ChartOptionLabel({ label, info, htmlFor }: ChartOptionLabelProps): JSX.Element {+ const Element = htmlFor ? 'label' : 'span'+ return (+ <Element className="font-normal" htmlFor={htmlFor}>+ {label}+ {info && (+ <>+ {' '}+ <Tooltip title={info}>+ <IconInfo className="relative top-0.5 text-lg text-secondary" />+ </Tooltip>+ </>+ )}+ </Element>+ )+}diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionNumberInput.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionNumberInput.tsxnew file mode 100644index 000000000000..6f2d849d4525--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionNumberInput.tsx@@ -0,0 +1,48 @@+import { useId } from 'react'++import { LemonInput } from '@posthog/lemon-ui'++import { ChartOptionLabel } from './ChartOptionLabel'+import { parseChartOptionNumber, useChartOptionNumberDraft } from './useChartOptionNumberDraft'++export interface ChartOptionNumberInputProps {+ label: string+ info?: string+ value: number | undefined+ onChange: (value: number | undefined) => void+ min?: number+ max?: number+ suffix?: string+ placeholder?: string+ disabledReason?: string | null+ 'data-attr'?: string+}++export function ChartOptionNumberInput(props: ChartOptionNumberInputProps): JSX.Element {+ const id = useId()+ const { draft, setDraft, commit } = useChartOptionNumberDraft(props.value, props.onChange)++ const { label, info, min, max, suffix, placeholder, disabledReason, 'data-attr': dataAttr } = props+ return (+ <div className="flex items-center justify-between gap-2">+ <ChartOptionLabel label={label} info={info} htmlFor={id} />+ <LemonInput+ id={id}+ type="number"+ size="small"+ className="w-24"+ value={parseChartOptionNumber(draft)}+ min={min}+ max={max}+ step={1}+ placeholder={placeholder}+ suffix={suffix ? <span>{suffix}</span> : undefined}+ disabledReason={disabledReason ?? undefined}+ onChange={(next) => setDraft(next === undefined ? '' : String(next))}+ onBlur={commit}+ onPressEnter={commit}+ data-attr={dataAttr}+ />+ </div>+ )+}diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionSelect.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionSelect.tsxnew file mode 100644index 000000000000..6f8bb6321e1f--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionSelect.tsx@@ -0,0 +1,50 @@+import { useId } from 'react'++import { LemonSelect } from '@posthog/lemon-ui'++import { ChartOptionLabel } from './ChartOptionLabel'++export interface ChartOptionChoice<T extends string | number> {+ value: T+ label: string+}++export interface ChartOptionSelectProps<T extends string | number> {+ /** Without a label the select fills the row, for a group whose heading already names it. */+ label?: string+ info?: string+ value: T+ options: ChartOptionChoice<T>[]+ onChange: (value: T) => void+ disabledReason?: string | null+ 'data-attr'?: string+}++export function ChartOptionSelect<T extends string | number>(props: ChartOptionSelectProps<T>): JSX.Element {+ const id = useId()++ const { label, info, value, options, onChange, disabledReason, 'data-attr': dataAttr } = props+ const select = (+ <LemonSelect<T>+ id={id}+ size="small"+ fullWidth={!label}+ value={value}+ options={options}+ onChange={onChange}+ disabledReason={disabledReason ?? undefined}+ data-attr={dataAttr}+ />+ )++ if (!label) {+ return select+ }++ return (+ <div className="flex items-center justify-between gap-2">+ <ChartOptionLabel label={label} info={info} htmlFor={id} />+ {select}+ </div>+ )+}diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionSwitch.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionSwitch.tsxnew file mode 100644index 000000000000..155fbd72b88f--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionSwitch.tsx@@ -0,0 +1,28 @@+import { LemonSwitch } from '@posthog/lemon-ui'++import { ChartOptionLabel } from './ChartOptionLabel'++export interface ChartOptionSwitchProps {+ label: string+ info?: string+ checked: boolean+ onChange: (checked: boolean) => void+ disabledReason?: string | null+ 'data-attr'?: string+}++export function ChartOptionSwitch(props: ChartOptionSwitchProps): JSX.Element {+ const { label, info, checked, onChange, disabledReason, 'data-attr': dataAttr } = props+ return (+ <LemonSwitch+ fullWidth+ // Full-width switches pad their label to line up with buttons; here it lines up with the other labels.+ className="!px-0"+ label={<ChartOptionLabel label={label} info={info} />}+ checked={checked}+ onChange={onChange}+ disabledReason={disabledReason}+ data-attr={dataAttr}+ />+ )+}diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionTextInput.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionTextInput.tsxnew file mode 100644index 000000000000..d9c2a712c45a--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionTextInput.tsx@@ -0,0 +1,40 @@+import { useId } from 'react'++import { LemonInput } from '@posthog/lemon-ui'++import { ChartOptionLabel } from './ChartOptionLabel'+import { useChartOptionTextDraft } from './useChartOptionTextDraft'++export interface ChartOptionTextInputProps {+ /** Without a label the input fills the row, for a group whose heading already names it. */+ label?: string+ info?: string+ value: string | undefined+ placeholder?: string+ /** Called when the field loses focus or Enter is pressed, with `undefined` for a blank field. */+ onChange: (value: string | undefined) => void+ 'data-attr'?: string+}++export function ChartOptionTextInput(props: ChartOptionTextInputProps): JSX.Element {+ const id = useId()+ const { draft, setDraft, commit } = useChartOptionTextDraft(props.value, props.onChange)++ const { label, info, placeholder, 'data-attr': dataAttr } = props+ return (+ <div className="flex flex-col gap-1">+ {label && <ChartOptionLabel label={label} info={info} htmlFor={id} />}+ <LemonInput+ id={id}+ size="small"+ fullWidth+ value={draft}+ placeholder={placeholder}+ onChange={setDraft}+ onBlur={commit}+ onPressEnter={commit}+ data-attr={dataAttr}+ />+ </div>+ )+}diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionToggleGroup.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionToggleGroup.tsxnew file mode 100644index 000000000000..05e4e3492f45--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionToggleGroup.tsx@@ -0,0 +1,32 @@+import { LemonSegmentedButton } from '@posthog/lemon-ui'++import { ChartOptionLabel } from './ChartOptionLabel'+import type { ChartOptionChoice } from './ChartOptionSelect'++export interface ChartOptionToggleGroupProps<T extends string | number> {+ /** Without a label the choices fill the row, for a group whose heading already names it. */+ label?: string+ info?: string+ value: T+ options: ChartOptionChoice<T>[]+ onChange: (value: T) => void+ disabledReason?: string | null+ 'data-attr'?: string+}++export function ChartOptionToggleGroup<T extends string | number>(props: ChartOptionToggleGroupProps<T>): JSX.Element {+ const { label, info, value, options, onChange, disabledReason, 'data-attr': dataAttr } = props+ return (+ <div className="flex flex-col gap-1" data-attr={dataAttr}>+ {label && <ChartOptionLabel label={label} info={info} />}+ <LemonSegmentedButton<T>+ size="small"+ fullWidth+ value={value}+ options={options}+ onChange={(next) => onChange(next)}+ disabledReason={disabledReason ?? undefined}+ />+ </div>+ )+}diff --git a/frontend/src/lib/components/ChartOptions/ChartOptionWarning.tsx b/frontend/src/lib/components/ChartOptions/ChartOptionWarning.tsxnew file mode 100644index 000000000000..c0779f5e5046--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/ChartOptionWarning.tsx@@ -0,0 +1,3 @@+export function ChartOptionWarning({ children }: { children: string }): JSX.Element {+ return <span className="text-xs text-danger">{children}</span>+}diff --git a/frontend/src/lib/components/ChartOptions/buildDisplayOptions.tsx b/frontend/src/lib/components/ChartOptions/buildDisplayOptions.tsxnew file mode 100644index 000000000000..8b1190ba2820--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/buildDisplayOptions.tsx@@ -0,0 +1,218 @@+import { ReactNode } from 'react'++import { MetricDirectionColorPickers } from 'lib/components/Metric/MetricDirectionColorPickers'++import { ChartOptionNumberInput } from './ChartOptionNumberInput'+import { ChartOptionSelect } from './ChartOptionSelect'+import { ChartOptionSwitch } from './ChartOptionSwitch'+import { ChartOptionTextInput } from './ChartOptionTextInput'+import { ChartOptionToggleGroup } from './ChartOptionToggleGroup'+import { ChartOptionWarning } from './ChartOptionWarning'+import {+ DISPLAY_OPTION_GROUPS,+ DISPLAY_OPTION_TABS,+ DISPLAY_OPTIONS,+ DisplayOptionBinding,+ DisplayOptionBindings,+ DisplayOptionDefinition,+ DisplayOptionGroupKey,+ DisplayOptionItem,+ DisplayOptionSection,+ DisplayOptionTab,+ DirectionColors,+} from './displayOptions'++type AnyBinding<C> = DisplayOptionBinding<C, any>++export interface DisplayOptionGroupOverride {+ title?: string+}++export interface BuildDisplayOptionsSettings {+ // Lists every group under one tab, for a surface with too few options to need tabs.+ singleTab?: boolean+ groups?: Partial<Record<DisplayOptionGroupKey, DisplayOptionGroupOverride>>+}++function renderControl<C>(definition: DisplayOptionDefinition, binding: AnyBinding<C>, c: C): ReactNode {+ if (binding.render) {+ return binding.render(c)+ }+ const label = definition.label+ const visibleLabel = definition.hideLabel || definition.stacked ? undefined : label+ const value = binding.value?.(c)+ const onChange = (next: unknown): void => binding.onChange?.(next, c)+ const disabledReason = binding.disabledReason?.(c) ?? undefined+ const dataAttr = binding.dataAttr++ switch (definition.control) {+ case 'checkbox':+ return (+ <ChartOptionSwitch+ label={label}+ info={definition.info}+ checked={!!value}+ onChange={onChange}+ disabledReason={disabledReason}+ data-attr={dataAttr}+ />+ )+ case 'number':+ return (+ <ChartOptionNumberInput+ label={label}+ info={definition.info}+ value={value}+ min={definition.min}+ max={definition.max}+ suffix={binding.suffix?.(c) ?? definition.suffix}+ placeholder={binding.placeholder?.(c) ?? definition.placeholder}+ disabledReason={disabledReason}+ onChange={onChange}+ data-attr={dataAttr}+ />+ )+ case 'text':+ return (+ <ChartOptionTextInput+ label={visibleLabel}+ info={definition.info}+ value={value}+ placeholder={binding.placeholder?.(c) ?? definition.placeholder}+ onChange={onChange}+ data-attr={dataAttr}+ />+ )+ case 'select':+ case 'toggle': {+ const Control = definition.control === 'select' ? ChartOptionSelect : ChartOptionToggleGroup+ return (+ <Control+ label={visibleLabel}+ info={definition.info}+ value={value}+ options={binding.options?.(c) ?? [...(definition.options ?? [])]}+ onChange={onChange}+ disabledReason={disabledReason}+ data-attr={dataAttr}+ />+ )+ }+ case 'colors': {+ const colors = value as DirectionColors+ return (+ <MetricDirectionColorPickers+ className="gap-2"+ increaseColor={colors.increase}+ decreaseColor={colors.decrease}+ onIncrease={(increase) => onChange({ ...colors, increase })}+ onDecrease={(decrease) => onChange({ ...colors, decrease })}+ />+ )+ }+ case 'custom':+ return null+ }+}++function renderOption<C>(definition: DisplayOptionDefinition, binding: AnyBinding<C>, c: C): ReactNode {+ const control = renderControl(definition, binding, c)+ const warning = binding.warning?.(c)+ const content = warning ? (+ <>+ {control}+ <ChartOptionWarning>{warning}</ChartOptionWarning>+ </>+ ) : (+ control+ )+ return definition.nested ? <div className="pl-4">{content}</div> : content+}++// Turns one surface's bindings into tabs → sections → rendered options, in the shared order.+// `count` is the number of options set away from their default, badged on the Options button.+export function buildDisplayOptions<C>(+ bindings: DisplayOptionBindings<C>,+ c: C,+ { singleTab = false, groups: overrides = {} }: BuildDisplayOptionsSettings = {}+): { tabs: DisplayOptionTab[]; count: number } {+ const definitions: readonly DisplayOptionDefinition[] = DISPLAY_OPTIONS+ const shownByGroup = new Map<+ DisplayOptionGroupKey,+ { definition: DisplayOptionDefinition; item: DisplayOptionItem }[]+ >()+ const countByGroup = new Map<DisplayOptionGroupKey, number>()++ for (const definition of definitions) {+ const name = definition.name as keyof DisplayOptionBindings<C>+ const binding = bindings[name] as AnyBinding<C> | undefined+ if (!binding || !binding.showCondition(c)) {+ continue+ }+ const group = definition.group+ shownByGroup.set(group, [+ ...(shownByGroup.get(group) ?? []),+ { definition, item: { name, element: renderOption(definition, binding, c) } },+ ])+ countByGroup.set(group, (countByGroup.get(group) ?? 0) + Number(binding.changedCount?.(c) ?? 0))+ }++ const groupSections = (group: (typeof DISPLAY_OPTION_GROUPS)[number]): DisplayOptionSection[] => {+ const sections: DisplayOptionSection[] = []+ let run: DisplayOptionItem[] = []+ const flushRun = (): void => {+ if (run.length === 0) {+ return+ }+ const isFirstRun = !sections.some((section) => section.key === group.key)+ sections.push(+ isFirstRun+ ? {+ key: group.key,+ title: overrides[group.key]?.title ?? ('title' in group ? group.title : undefined),+ dataAttr: 'dataAttr' in group ? group.dataAttr : undefined,+ items: run,+ }+ : { key: `${group.key}-${sections.length}`, items: run }+ )+ run = []+ }+ for (const { definition, item } of shownByGroup.get(group.key) ?? []) {+ if (definition.stacked) {+ flushRun()+ sections.push({+ key: definition.name,+ title: definition.label,+ tooltip: definition.info,+ items: [item],+ })+ } else {+ run.push(item)+ }+ }+ flushRun()+ return sections+ }++ const allTabs: DisplayOptionTab[] = DISPLAY_OPTION_TABS.map((tab) => {+ const groups = DISPLAY_OPTION_GROUPS.filter((group) => group.tab === tab.key)+ const sections = groups.flatMap(groupSections)+ const count = groups.reduce((sum, group) => sum + (countByGroup.get(group.key) ?? 0), 0)+ return { key: tab.key, label: tab.label, sections, count }+ })++ const tabs = (+ singleTab+ ? [+ {+ key: 'general' as const,+ label: 'General',+ sections: allTabs.flatMap((tab) => tab.sections),+ count: allTabs.reduce((sum, tab) => sum + tab.count, 0),+ },+ ]+ : allTabs+ ).filter((tab) => tab.sections.length > 0)++ return { tabs, count: tabs.reduce((sum, tab) => sum + tab.count, 0) }+}diff --git a/frontend/src/lib/components/ChartOptions/displayOptions.ts b/frontend/src/lib/components/ChartOptions/displayOptions.tsnew file mode 100644index 000000000000..2d313980f20c--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/displayOptions.ts@@ -0,0 +1,432 @@+import { ReactNode } from 'react'++import { DEFAULT_DECIMAL_PLACES } from 'lib/utils/numbers'++import { ResultCustomizationBy } from '~/queries/schema/schema-general'+import { AnnotationScope, RetentionDashboardDisplayType } from '~/types'++import type { ChartOptionChoice } from './ChartOptionSelect'++export type DisplayOptionTabKey = 'general' | 'axes' | 'lines'++export const DISPLAY_OPTION_TABS: readonly { key: DisplayOptionTabKey; label: string }[] = [+ { key: 'general', label: 'General' },+ { key: 'axes', label: 'Axes' },+ { key: 'lines', label: 'Lines' },+]++interface DisplayOptionGroupDefinition {+ key: string+ tab: DisplayOptionTabKey+ title?: string+ tooltip?: string+ dataAttr?: string+}++export const DISPLAY_OPTION_GROUPS = [+ { key: 'display', tab: 'general', dataAttr: 'options-display-section' },+ { key: 'x-axis', tab: 'axes', title: 'X-axis' },+ { key: 'y-axis', tab: 'axes', title: 'Y-axis' },+ { key: 'right-y-axis', tab: 'axes', title: 'Right Y-axis' },+ { key: 'style', tab: 'lines', title: 'Style' },+ { key: 'overlays', tab: 'lines', title: 'Overlays', dataAttr: 'options-overlays-section' },+] as const satisfies readonly DisplayOptionGroupDefinition[]++export type DisplayOptionGroupKey = (typeof DISPLAY_OPTION_GROUPS)[number]['key']++type Choice = ChartOptionChoice<string | number>++interface DisplayOptionDefinitionBase {+ name: string+ label: string+ group: DisplayOptionGroupKey+ info?: string+ // The choices already say what the control is, so the label is only read aloud.+ hideLabel?: boolean+ // The label heads its own section, above a full-width control.+ stacked?: boolean+ // Indented under the option above it, which it refines.+ nested?: boolean+}++export type DisplayOptionDefinition = DisplayOptionDefinitionBase &+ (+ | { control: 'checkbox' }+ | { control: 'number'; min?: number; max?: number; suffix?: string; placeholder?: string }+ | { control: 'text'; placeholder?: string }+ | { control: 'select' | 'toggle'; options?: readonly Choice[] }+ | { control: 'colors' }+ // Options with a bespoke control; each surface renders its own.+ | { control: 'custom' }+ )++const SCALE_OPTIONS = [+ { value: 'linear', label: 'Linear' },+ { value: 'log', label: 'Logarithmic' },+] as const++const ROTATION_OPTIONS = [0, -45, -90, 45, 90].map((value) => ({ value, label: `${value}°` }))++// Every chart display option, in the order the insight Options panel and the SQL editor's Display tab+// show them. Each surface binds the options it supports: when they show, and how they read and save.+export const DISPLAY_OPTIONS = [+ {+ name: 'metricSummary',+ label: 'Headline value',+ group: 'display',+ control: 'select',+ options: [+ { value: 'total', label: 'Total' },+ { value: 'average', label: 'Average' },+ { value: 'latest', label: 'Latest' },+ ],+ },+ { name: 'metricShowChange', label: 'Show change', group: 'display', control: 'checkbox' },+ { name: 'metricChangeColors', label: 'Change colors', nested: true, group: 'display', control: 'colors' },+ { name: 'metricColorByDirection', label: 'Color by trend', group: 'display', control: 'checkbox' },+ { name: 'metricTrendColors', label: 'Trend colors', nested: true, group: 'display', control: 'colors' },+ { name: 'lifecycleStacking', label: 'Stack bars', group: 'display', control: 'checkbox' },+ { name: 'valuesOnSeries', label: 'Show values on series', group: 'display', control: 'checkbox' },+ {+ name: 'valueLabelPosition',+ label: 'Value position',+ group: 'display',+ control: 'select',+ options: [+ { value: 'end', label: 'At the end' },+ { value: 'center', label: 'Inside' },+ ],+ },+ { name: 'valueLabelBackground', label: 'Value background', group: 'display', control: 'checkbox' },+ {+ name: 'valueLabelFontSize',+ label: 'Value font size',+ group: 'display',+ control: 'select',+ options: [8, 10, 12, 14, 16, 20, 24, 32].map((value) => ({ value, label: `${value}px` })),+ },+ {+ name: 'valueLabelRotation',+ label: 'Value rotation',+ group: 'display',+ control: 'select',+ options: ROTATION_OPTIONS,+ },+ { name: 'lifecyclePercentages', label: 'Show percentages on series', group: 'display', control: 'checkbox' },+ { name: 'percentStack', label: 'Show as % of total', group: 'display', control: 'checkbox' },+ { name: 'stackBreakdown', label: 'Stack breakdown values', group: 'display', control: 'checkbox' },+ { name: 'sliceNames', label: 'Show names on slices', group: 'display', control: 'checkbox' },+ {+ name: 'pieSliceContent',+ label: 'Show on slices',+ group: 'display',+ control: 'toggle',+ options: [+ { value: 'labels', label: 'Labels' },+ { value: 'values', label: 'Values' },+ { value: 'none', label: 'Nothing' },+ ],+ },+ {+ name: 'pieValueDisplay',+ label: 'Show values as',+ group: 'display',+ control: 'toggle',+ options: [+ { value: 'absolute', label: 'Absolute' },+ { value: 'percentage', label: 'Percentage' },+ ],+ },+ { name: 'pieTotal', label: 'Show total', group: 'display', control: 'checkbox' },+ { name: 'showTotalRow', label: 'Show total row', group: 'display', control: 'checkbox' },+ { name: 'showNullsAsZero', label: 'Show nulls as zero', group: 'display', control: 'checkbox' },+ {+ name: 'barSpacing',+ label: 'Bar spacing',+ group: 'display',+ control: 'select',+ options: [+ { value: 0, label: 'None' },+ { value: 0.1, label: 'Small' },+ { value: 0.2, label: 'Medium' },+ { value: 0.4, label: 'Large' },+ ],+ },+ {+ name: 'hideIncompleteFunnelPeriods',+ label: 'Hide incomplete periods',+ info: "Hides recent periods whose conversion window hasn't fully elapsed, so the trend isn't dragged down by entrants who still have time to convert.",+ group: 'display',+ control: 'checkbox',+ },+ { name: 'alertAnomalyPoints', label: 'Show alert anomaly points', group: 'display', control: 'custom' },+ { name: 'legend', label: 'Show legend', group: 'display', control: 'checkbox' },+ {+ name: 'legendPosition',+ label: 'Legend position',+ nested: true,+ group: 'display',+ control: 'select',+ options: [+ { value: 'top', label: 'Top' },+ { value: 'bottom', label: 'Bottom' },+ { value: 'left', label: 'Left' },+ { value: 'right', label: 'Right' },+ ],+ },+ {+ name: 'excludeOutliers',+ label: 'Exclude outliers',+ info: 'When on, whiskers stop at 1.5 times the interquartile range, so differences between the quartiles are easier to see. When off, the Y-axis stretches to show every value.',+ group: 'display',+ control: 'checkbox',+ },++ {+ 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: [+ { value: 'all', label: 'All' },+ { value: 'none', label: 'None' },+ { value: AnnotationScope.Insight, label: 'Insight' },+ { value: AnnotationScope.Dashboard, label: 'Dashboard' },+ { value: AnnotationScope.Project, label: 'Project' },+ { value: AnnotationScope.Organization, label: 'Organization' },+ ],+ },+ { name: 'unit', label: 'Unit', stacked: true, group: 'display', control: 'custom' },+ {+ name: 'resultCustomizationBy',+ label: 'Color customization by',+ info: "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).",+ stacked: true,+ group: 'display',+ control: 'toggle',+ options: [+ { value: ResultCustomizationBy.Value, label: 'By name' },+ { value: ResultCustomizationBy.Position, label: 'By rank' },+ ],+ },+ {+ name: 'decimalPlaces',+ label: 'Decimal places',+ group: 'display',+ control: 'number',+ min: 0,+ max: 9,+ placeholder: String(DEFAULT_DECIMAL_PLACES),+ },+ {+ name: 'retentionDashboardDisplay',+ label: 'On dashboards',+ stacked: true,+ group: 'display',+ control: 'select',+ options: [+ { value: RetentionDashboardDisplayType.TableOnly, label: 'Show table only' },+ { value: RetentionDashboardDisplayType.GraphOnly, label: 'Show graph only' },+ { value: RetentionDashboardDisplayType.All, label: 'Show both' },+ ],+ },+ {+ name: 'retentionCohortLabelStart',+ label: 'Cohort labels start at',+ info: 'Controls the starting index used to label cohort columns. Display only, does not affect the calculations.',+ stacked: true,+ group: 'display',+ control: 'toggle',+ },++ { name: 'xAxisLabel', label: 'Label', group: 'x-axis', control: 'text', placeholder: 'None' },+ { name: 'xAxisScale', label: 'Scale', hideLabel: true, group: 'x-axis', control: 'toggle', options: SCALE_OPTIONS },+ {+ name: 'xAxisBeginAtZero',+ label: 'Begin at zero',+ info: 'When off, the axis starts just below your lowest value instead of at zero, so small changes are easier to see.',+ group: 'x-axis',+ control: 'checkbox',+ },+ {+ name: 'xAxisDateFormat',+ label: 'Date format',+ info: 'For example, YYYY-MM-DD, MMM YYYY, or DD/MM/YYYY.',+ group: 'x-axis',+ control: 'text',+ placeholder: 'Automatic',+ },+ {+ name: 'xAxisTickRotation',+ label: 'Tick label rotation',+ group: 'x-axis',+ control: 'select',+ // A select value can't be null, so "Automatic" stands in for an unset rotation.+ options: [{ value: 'auto', label: 'Automatic' }, ...ROTATION_OPTIONS],+ },+ { name: 'xAxisShowTicks', label: 'Show tick labels', group: 'x-axis', control: 'checkbox' },+ { name: 'xAxisBorder', label: 'Show border', group: 'x-axis', control: 'checkbox' },++ { name: 'yAxisLabel', label: 'Label', group: 'y-axis', control: 'text', placeholder: 'None' },+ { name: 'yAxisMin', label: 'Minimum', group: 'y-axis', control: 'number', placeholder: 'Auto' },+ { name: 'yAxisMax', label: 'Maximum', group: 'y-axis', control: 'number', placeholder: 'Auto' },+ {+ name: 'yAxisBeginAtZero',+ label: 'Begin at zero',+ info: 'When off, the axis starts just below your lowest value instead of at zero, so small changes are easier to see.',+ group: 'y-axis',+ control: 'checkbox',+ },+ { name: 'multipleYAxes', label: 'Show multiple Y-axes', group: 'y-axis', control: 'checkbox' },+ { name: 'yAxisShowTicks', label: 'Show tick labels', group: 'y-axis', control: 'checkbox' },+ { name: 'yAxisGridLines', label: 'Show grid lines', group: 'y-axis', control: 'checkbox' },+ { 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: 'rightYAxisBeginAtZero',+ label: 'Begin at zero',+ info: 'When off, the axis starts just below your lowest value instead of at zero, so small changes are easier to see.',+ group: 'right-y-axis',+ control: 'checkbox',+ },+ { name: 'rightYAxisShowTicks', label: 'Show tick labels', group: 'right-y-axis', control: 'checkbox' },+ { name: 'rightYAxisGridLines', label: 'Show grid lines', group: 'right-y-axis', control: 'checkbox' },+ {+ name: 'rightYAxisScale',+ label: 'Scale',+ hideLabel: true,+ group: 'right-y-axis',+ control: 'toggle',+ options: SCALE_OPTIONS,+ },++ {+ name: 'lineStyle',+ label: 'Line style',+ hideLabel: true,+ group: 'style',+ control: 'toggle',+ options: [+ { value: 'smooth', label: 'Smooth' },+ { value: 'linear', label: 'Straight' },+ ],+ },+ { name: 'smoothing', label: 'Smoothing', hideLabel: true, group: 'style', control: 'select' },+ {+ name: 'retentionSeriesColorMode',+ label: 'Cohort line colors',+ info: 'One shade draws every cohort in the same color, with the newest cohort the most solid.',+ stacked: true,+ group: 'style',+ control: 'toggle',+ options: [+ { value: 'palette', label: 'One per cohort' },+ { value: 'opacity', label: 'One shade' },+ ],+ },++ { name: 'trendLines', label: 'Show trend lines', group: 'overlays', control: 'checkbox' },+ { name: 'movingAverage', label: 'Show moving average', group: 'overlays', control: 'checkbox' },+ {+ name: 'movingAverageIntervals',+ label: 'Intervals',+ info: "The number of data points to use for calculating the moving average. A larger number will create a smoother line but with more lag. You can't use a number greater than the amount of intervals in your date range.",+ nested: true,+ group: 'overlays',+ control: 'number',+ min: 2,+ },+ { name: 'confidenceInterval', label: 'Show confidence intervals', group: 'overlays', control: 'checkbox' },+ {+ name: 'confidenceLevel',+ label: 'Confidence level',+ info: 'A 95% confidence level means that for each data point, we are 95% confident that the true value is within the confidence interval.',+ nested: true,+ group: 'overlays',+ control: 'number',+ min: 0,+ max: 100,+ suffix: '%',+ },+ { name: 'alertThresholdLines', label: 'Show alert threshold lines', group: 'overlays', control: 'checkbox' },+ { name: 'retentionMeanLine', label: 'Show mean line', group: 'overlays', control: 'checkbox' },+] as const satisfies readonly DisplayOptionDefinition[]++type Definitions = (typeof DISPLAY_OPTIONS)[number]+export type DisplayOptionName = Definitions['name']+type DefinitionOf<N extends DisplayOptionName> = Extract<Definitions, { name: N }>++// A number choice saves any number (a stored value may predate today's choices); a string keeps its literals.+type Widen<V> = V extends number ? number : V+type ChoiceValue<D> = D extends { options: readonly { value: infer V }[] } ? Widen<V> : string | number++// What an option reads and saves, from its control: a checkbox is a boolean, a number input may be empty.+export type DisplayOptionValue<N extends DisplayOptionName> =+ DefinitionOf<N> extends { control: 'checkbox' }+ ? boolean+ : DefinitionOf<N> extends { control: 'number' }+ ? number | undefined+ : DefinitionOf<N> extends { control: 'text' }+ ? string | undefined+ : DefinitionOf<N> extends { control: 'select' | 'toggle' }+ ? ChoiceValue<DefinitionOf<N>>+ : DefinitionOf<N> extends { control: 'colors' }+ ? DirectionColors+ : never++export interface DirectionColors {+ increase: string+ decrease: string+}++export interface DisplayOptionBinding<C, V> {+ showCondition: (c: C) => boolean | null | undefined+ value?: (c: C) => V+ onChange?: (value: V, c: C) => void+ // For a `custom` option, which has no generic control.+ render?: (c: C) => ReactNode+ disabledReason?: (c: C) => string | null | undefined+ // A message under the control, such as an inverted range.+ warning?: (c: C) => string | null | undefined+ // Choices that depend on the chart, such as smoothing windows for the current interval.+ options?: (c: C) => ChartOptionChoice<V & (string | number)>[]+ placeholder?: (c: C) => string+ suffix?: (c: C) => string+ // Options set away from their default, summed into the badge on the Options button.+ changedCount?: (c: C) => number | boolean | null | undefined+ dataAttr?: string+}++export type DisplayOptionBindings<C> = {+ [N in DisplayOptionName]?: DisplayOptionBinding<C, DisplayOptionValue<N>>+}++export interface DisplayOptionItem {+ name: DisplayOptionName+ element: ReactNode+}++export interface DisplayOptionSection {+ key: string+ title?: string+ tooltip?: string+ dataAttr?: string+ items: DisplayOptionItem[]+}++export interface DisplayOptionTab {+ key: DisplayOptionTabKey+ label: string+ sections: DisplayOptionSection[]+ count: number+}diff --git a/frontend/src/lib/components/ChartOptions/useChartOptionNumberDraft.test.ts b/frontend/src/lib/components/ChartOptions/useChartOptionNumberDraft.test.tsnew file mode 100644index 000000000000..a30ab10a03f3--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/useChartOptionNumberDraft.test.ts@@ -0,0 +1,54 @@+import { act, renderHook } from '@testing-library/react'++import { useChartOptionNumberDraft } from './useChartOptionNumberDraft'++describe('useChartOptionNumberDraft', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('drops a queued value when the field is cleared before it sends', () => {+ const onChange = jest.fn()+ const { result } = renderHook(() => useChartOptionNumberDraft(40, onChange))++ act(() => result.current.setDraft('55'))+ act(() => result.current.setDraft(''))+ act(() => jest.advanceTimersByTime(1000))+ expect(onChange).not.toHaveBeenCalled()++ act(() => result.current.commit())+ expect(onChange).toHaveBeenCalledWith(undefined)+ })++ it('keeps newer typing when an older save arrives', () => {+ const onChange = jest.fn()+ const { result, rerender } = renderHook(({ value }) => useChartOptionNumberDraft(value, onChange), {+ initialProps: { value: undefined as number | undefined },+ })++ act(() => result.current.setDraft('1'))+ act(() => jest.advanceTimersByTime(300))+ act(() => result.current.setDraft('12'))+ rerender({ value: 1 })+ expect(result.current.draft).toBe('12')++ act(() => result.current.commit())+ expect(onChange).toHaveBeenLastCalledWith(12)+ })++ it('keeps a lone minus sign so a negative value can be typed', () => {+ const onChange = jest.fn()+ const { result } = renderHook(() => useChartOptionNumberDraft(undefined, onChange))++ act(() => result.current.setDraft('-'))+ expect(result.current.draft).toBe('-')++ act(() => result.current.setDraft('-10'))+ act(() => jest.advanceTimersByTime(1000))+ expect(onChange).toHaveBeenLastCalledWith(-10)+ })+})diff --git a/frontend/src/lib/components/ChartOptions/useChartOptionNumberDraft.ts b/frontend/src/lib/components/ChartOptions/useChartOptionNumberDraft.tsnew file mode 100644index 000000000000..7b4599c662f4--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/useChartOptionNumberDraft.ts@@ -0,0 +1,55 @@+import { useEffect, useRef, useState } from 'react'+import { useDebouncedCallback } from 'use-debounce'++const toText = (value: number | undefined): string => (value === undefined ? '' : String(value))++export const parseChartOptionNumber = (text: string): number | undefined => {+ if (text.trim() === '') {+ return undefined+ }+ const parsed = Number(text)+ return Number.isFinite(parsed) ? parsed : undefined+}++// The draft stays raw text, so partial entries like "-" or "1." survive until they parse. Only a+// finite value is sent while typing; a field left empty clears the setting when it loses focus.+export function useChartOptionNumberDraft(+ value: number | undefined,+ onChange: (value: number | undefined) => void+): { draft: string; setDraft: (draft: string) => void; commit: () => void } {+ const [draft, setDraftState] = useState(toText(value))+ // Saves land after a delay, so a value arriving mid-edit can be older than what the user has typed since.+ const editing = useRef(false)++ useEffect(() => {+ if (editing.current) {+ return+ }+ setDraftState((current) => (parseChartOptionNumber(current) === value ? current : toText(value)))+ }, [value])++ const sendWhileTyping = useDebouncedCallback((next: number) => onChange(next), 300)++ const setDraft = (next: string): void => {+ editing.current = true+ setDraftState(next)+ const parsed = parseChartOptionNumber(next)+ if (parsed === undefined) {+ sendWhileTyping.cancel()+ } else {+ sendWhileTyping(parsed)+ }+ }++ const commit = (): void => {+ editing.current = false+ sendWhileTyping.cancel()+ const parsed = parseChartOptionNumber(draft)+ setDraftState(toText(parsed))+ if (parsed !== value) {+ onChange(parsed)+ }+ }++ return { draft, setDraft, commit }+}diff --git a/frontend/src/lib/components/ChartOptions/useChartOptionTextDraft.ts b/frontend/src/lib/components/ChartOptions/useChartOptionTextDraft.tsnew file mode 100644index 000000000000..3507ed06c24a--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/useChartOptionTextDraft.ts@@ -0,0 +1,20 @@+import { useEffect, useState } from 'react'++export function useChartOptionTextDraft(+ value: string | undefined,+ onChange: (value: string | undefined) => void+): { draft: string; setDraft: (draft: string) => void; commit: () => void } {+ const [draft, setDraft] = useState(value ?? '')++ useEffect(() => {+ setDraft(value ?? '')+ }, [value])++ const commit = (): void => {+ const trimmed = draft.trim()+ setDraft(trimmed)+ onChange(trimmed || undefined)+ }++ return { draft, setDraft, commit }+}diff --git a/frontend/src/lib/components/ChartOptions/useDisplayOptions.ts b/frontend/src/lib/components/ChartOptions/useDisplayOptions.tsnew file mode 100644index 000000000000..c569a415d4f0--- /dev/null+++ b/frontend/src/lib/components/ChartOptions/useDisplayOptions.ts@@ -0,0 +1,15 @@+import { buildDisplayOptions, BuildDisplayOptionsSettings } from './buildDisplayOptions'+import type { DisplayOptionBindings, DisplayOptionTab } from './displayOptions'++// What one surface (the insight Options panel, the SQL editor's Display tab) supplies: how to read its+// state, and for each option it supports, when the option shows and how it reads and saves.+export interface DisplayOptionsAdapter<C> {+ useDisplayContext: () => C+ bindings: DisplayOptionBindings<C>+ settings?: (c: C) => BuildDisplayOptionsSettings+}++export function useDisplayOptions<C>(adapter: DisplayOptionsAdapter<C>): { tabs: DisplayOptionTab[]; count: number } {+ const context = adapter.useDisplayContext()+ return buildDisplayOptions(adapter.bindings, context, adapter.settings?.(context))+}diff --git a/frontend/src/lib/components/SmoothingFilter/SmoothingFilter.tsx b/frontend/src/lib/components/SmoothingFilter/SmoothingFilter.tsxdeleted file mode 100644index 7a00e5fa9caf..000000000000--- a/frontend/src/lib/components/SmoothingFilter/SmoothingFilter.tsx+++ /dev/null@@ -1,59 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconPulse } from '@posthog/icons'-import { LemonSelect } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--import { smoothingOptions } from './smoothings'--export function SmoothingFilter(): JSX.Element | null {- const { insightProps, editingDisabledReason } = useValues(insightLogic)- const { isTrends, interval, trendsFilter } = useValues(trendsDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- if (!isTrends || !interval) {- return null- }-- const { smoothingIntervals } = trendsFilter || {}-- // Put a little icon next to the selected item- const options = smoothingOptions[interval].map(({ value, label }) => ({- value,- label:- value === smoothingIntervals ? (- <>- <IconPulse className="mr-1.5 text-secondary" />- {label}- </>- ) : (- label- ),- labelInMenu: label,- }))-- if (!options.length) {- return null- }-- return (- <LemonSelect- key={interval}- value={smoothingIntervals || 1}- fullWidth- onChange={(key) => {- updateInsightFilter({- smoothingIntervals: key,- })- }}- data-attr="smoothing-filter"- options={options}- size="small"- disabledReason={editingDisabledReason}- />- )-}diff --git a/frontend/src/lib/components/UnitPicker/UnitPicker.tsx b/frontend/src/lib/components/UnitPicker/UnitPicker.tsxindex 21c40dc338a3..6df3fe54cd57 100644--- a/frontend/src/lib/components/UnitPicker/UnitPicker.tsx+++ b/frontend/src/lib/components/UnitPicker/UnitPicker.tsx@@ -99,7 +99,7 @@ export function UnitPicker(): JSX.Element {}return (- <div className="flex-1 mb-2.5 mx-2">+ <div className="flex-1"><LemonButtonWithDropdownonClick={() => setIsVisible(!isVisible)}size="small"diff --git a/products/product_analytics/frontend/insights/editor/DisplayOptions.tsx b/products/product_analytics/frontend/insights/editor/DisplayOptions.tsxdeleted file mode 100644index e44b85ae6ec3..000000000000--- a/products/product_analytics/frontend/insights/editor/DisplayOptions.tsx+++ /dev/null@@ -1,257 +0,0 @@-import { useActions, useValues } from 'kea'-import posthog from 'posthog-js'-import { ReactNode } from 'react'-import { useDebouncedCallback } from 'use-debounce'--import { IconInfo } from '@posthog/icons'-import { LemonCheckbox, LemonInput, Tooltip } from '@posthog/lemon-ui'--import { SmoothingFilter } from 'lib/components/SmoothingFilter/SmoothingFilter'-import { UnitPicker } from 'lib/components/UnitPicker/UnitPicker'-import { DEFAULT_DECIMAL_PLACES } from 'lib/utils/numbers'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { isTrendsQuery } from '~/queries/schema/node-guards'-import { ChartDisplayType } from '~/types'--import { AnnotationsPicker } from 'products/product_analytics/frontend/insights/editor/filters/AnnotationsPicker'-import { AxisLabelFilter } from 'products/product_analytics/frontend/insights/editor/filters/AxisLabelFilter'-import { HideIncompleteConversionWindowPeriodsFilter } from 'products/product_analytics/frontend/insights/editor/filters/HideIncompleteConversionWindowPeriodsFilter'-import { LegendOptionsFilter } from 'products/product_analytics/frontend/insights/editor/filters/LegendOptionsFilter'-import { LineStylePicker } from 'products/product_analytics/frontend/insights/editor/filters/LineStylePicker'-import {- MetricColorFilter,- MetricShowChangeFilter,- MetricSummaryFilter,-} from 'products/product_analytics/frontend/insights/editor/filters/MetricFilters'-import { PercentStackViewFilter } from 'products/product_analytics/frontend/insights/editor/filters/PercentStackViewFilter'-import { ResultCustomizationByPicker } from 'products/product_analytics/frontend/insights/editor/filters/ResultCustomizationByPicker'-import { ScalePicker } from 'products/product_analytics/frontend/insights/editor/filters/ScalePicker'-import { ShowAlertAnomalyPointsFilter } from 'products/product_analytics/frontend/insights/editor/filters/ShowAlertAnomalyPointsFilter'-import { ShowAlertThresholdLinesFilter } from 'products/product_analytics/frontend/insights/editor/filters/ShowAlertThresholdLinesFilter'-import { ShowLegendFilter } from 'products/product_analytics/frontend/insights/editor/filters/ShowLegendFilter'-import { ShowMultipleYAxesFilter } from 'products/product_analytics/frontend/insights/editor/filters/ShowMultipleYAxesFilter'-import { ShowPieTotalFilter } from 'products/product_analytics/frontend/insights/editor/filters/ShowPieTotalFilter'-import { ShowTrendLinesFilter } from 'products/product_analytics/frontend/insights/editor/filters/ShowTrendLinesFilter'-import { SliceNamesFilter } from 'products/product_analytics/frontend/insights/editor/filters/SliceNamesFilter'-import { StackBreakdownFilter } from 'products/product_analytics/frontend/insights/editor/filters/StackBreakdownFilter'-import { ValueOnSeriesFilter } from 'products/product_analytics/frontend/insights/editor/filters/ValueOnSeriesFilter'-import { YAxisRangeFilter } from 'products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter'-import { LifecyclePercentagesFilter } from 'products/product_analytics/frontend/insights/lifecycle/filters/LifecyclePercentagesFilter'-import { LifecycleStackingFilter } from 'products/product_analytics/frontend/insights/lifecycle/filters/LifecycleStackingFilter'-import { RetentionCohortLabelStartIndexPicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionCohortLabelStartIndexPicker'-import { RetentionDashboardDisplayPicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionDashboardDisplayPicker'-import { RetentionMeanLineToggle } from 'products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle'-import { RetentionSeriesColorModePicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker'-import { ConfidenceLevelInput } from 'products/product_analytics/frontend/insights/trends/filters/ConfidenceLevelInput'-import { MovingAverageIntervalsInput } from 'products/product_analytics/frontend/insights/trends/filters/MovingAverageIntervalsInput'-import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--import { displayMatches, isDefaultTrendsLineDisplay, LINE_DISPLAYS } from './displayTypes'--function useLineGraphState(): { isLineGraph: boolean; isLinearScale: boolean } {- const { insightProps } = useValues(insightLogic)- const { querySource, display, yAxisScaleType } = useValues(insightVizDataLogic(insightProps))- const isLineDisplay = isDefaultTrendsLineDisplay(display, querySource) || displayMatches(display, LINE_DISPLAYS)- const isCumulativeLineDisplay = display === ChartDisplayType.ActionsLineGraphCumulative- return {- isLineGraph: isLineDisplay && !isCumulativeLineDisplay,- isLinearScale: !yAxisScaleType || yAxisScaleType === 'linear',- }-}--function Smoothing(): JSX.Element {- return (- <div className="px-2 pb-1.5 w-full">- <SmoothingFilter />- </div>- )-}--function ExcludeOutliers(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { querySource, trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))-- return (- <LemonCheckbox- label={- <span className="font-normal">- Exclude outliers{' '}- <Tooltip title="When enabled, whiskers are clipped to 1.5x the interquartile range, making it easier to see differences between the quartiles. When disabled, the y-axis extends to show the full range including extreme values.">- <IconInfo className="relative top-0.5 text-lg text-secondary" />- </Tooltip>- </span>- }- className="p-1 px-2"- size="small"- checked={trendsFilter?.excludeBoxPlotOutliers !== false}- onChange={(checked) => {- if (isTrendsQuery(querySource)) {- const newQuery = { ...querySource }- newQuery.trendsFilter = { ...trendsFilter, excludeBoxPlotOutliers: checked }- updateQuerySource(newQuery)- }- }}- />- )-}--function ConfidenceInterval(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { querySource, trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))- const { showConfidenceIntervals } = useValues(trendsDataLogic(insightProps))- const { isLineGraph, isLinearScale } = useLineGraphState()-- return (- <LemonCheckbox- label={<span className="font-normal">Show confidence intervals</span>}- className="p-1 px-2"- size="small"- checked={showConfidenceIntervals}- disabledReason={- !isLineGraph- ? 'Confidence intervals are only available for line graphs'- : !isLinearScale- ? 'Confidence intervals are only supported for linear scale.'- : undefined- }- onChange={(checked) => {- if (isTrendsQuery(querySource)) {- const newQuery = { ...querySource }- newQuery.trendsFilter = { ...trendsFilter, showConfidenceIntervals: checked }- updateQuerySource(newQuery)- }- }}- />- )-}--function MovingAverage(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { querySource, trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))- const { showMovingAverage } = useValues(trendsDataLogic(insightProps))- const { isLineGraph, isLinearScale } = useLineGraphState()-- return (- <LemonCheckbox- label={<span className="font-normal">Show moving average</span>}- className="p-1 px-2"- size="small"- checked={showMovingAverage}- disabledReason={- !isLineGraph- ? 'Moving average is only available for line and area graphs'- : !isLinearScale- ? 'Moving average is only supported for linear scale.'- : undefined- }- onChange={(checked) => {- if (isTrendsQuery(querySource)) {- const newQuery = { ...querySource }- newQuery.trendsFilter = { ...trendsFilter, showMovingAverage: checked }- updateQuerySource(newQuery)- }- }}- />- )-}--function DecimalPrecision(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const reportChange = useDebouncedCallback(() => {- posthog.capture('decimal places changed', {- decimal_places: trendsFilter?.decimalPlaces,- })- }, 500)-- return (- <LemonInput- type="number"- size="small"- step={1}- min={0}- max={9}- defaultValue={DEFAULT_DECIMAL_PLACES}- value={trendsFilter?.decimalPlaces}- onChange={(value) => {- updateInsightFilter({ decimalPlaces: value })- reportChange()- }}- className="mx-2 mb-1.5"- />- )-}--export function SectionHeader({- children,- tooltip,- dataAttr,-}: {- children: ReactNode- tooltip?: string- dataAttr?: string-}): JSX.Element {- return (- <h5 className="mx-2 my-1" data-attr={dataAttr}>- {children}- {tooltip && (- <>- {' '}- <Tooltip title={tooltip}>- <IconInfo className="relative top-0.5 text-lg text-secondary" />- </Tooltip>- </>- )}- </h5>- )-}--// 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,- 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: AnnotationsPicker,- 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,- RetentionSeriesColorMode: RetentionSeriesColorModePicker,- RetentionMeanLine: RetentionMeanLineToggle,-} satisfies Record<string, () => JSX.Element | null>--export type DisplayOption = (typeof DisplayOptions)[keyof typeof DisplayOptions]diff --git a/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx b/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsxindex d2ecff6c62e1..ebde34646771 100644--- a/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx+++ b/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.test.tsx@@ -169,7 +169,7 @@ describe('InsightDisplayConfig', () => {Axes: ['X-axis', 'Y-axis'],Lines: ['Style', 'Overlays'],},- displayItems: ['Show values on series', 'Show legendBottom'],+ displayItems: ['Show values on series', 'Show legend', 'Legend positionBottom'],overlayItems: lineOverlays,},],@@ -183,7 +183,12 @@ describe('InsightDisplayConfig', () => {Axes: ['X-axis', 'Y-axis'],Lines: ['Overlays'],},- displayItems: ['Show values on series', 'Show as % of total', 'Show legendBottom'],+ displayItems: [+ 'Show values on series',+ 'Show as % of total',+ 'Show legend',+ 'Legend positionBottom',+ ],overlayItems: lineOverlays,},],@@ -197,7 +202,12 @@ describe('InsightDisplayConfig', () => {Axes: ['X-axis', 'Y-axis'],Lines: ['Style', 'Overlays'],},- displayItems: ['Show values on series', 'Show as % of total', 'Show legendBottom'],+ displayItems: [+ 'Show values on series',+ 'Show as % of total',+ 'Show legend',+ 'Legend positionBottom',+ ],},],[@@ -215,9 +225,10 @@ describe('InsightDisplayConfig', () => {'Show values on series','Show as % of total','Show names on slices',- 'Show total below chart',+ 'Show total',// In-chart legend toggle + position select ("Bottom" is the prospective default)- 'Show legendBottom',+ 'Show legend',+ 'Legend positionBottom',],},],@@ -231,8 +242,9 @@ describe('InsightDisplayConfig', () => {'Show values on series','Show as % of total','Show names on slices',- 'Show total in center',- 'Show legendBottom',+ 'Show total',+ 'Show legend',+ 'Legend positionBottom',],},],@@ -286,7 +298,7 @@ describe('InsightDisplayConfig', () => {{tabs: [],sections: { General: ['Y-axis', 'Style'] },- displayItems: ['Show values on series', 'Show legendBottom'],+ displayItems: ['Show values on series', 'Show legend', 'Legend positionBottom'],},],['stickiness table', makeStickinessQuery(ChartDisplayType.ActionsTable), { tabs: [], sections: {} }],@@ -300,7 +312,8 @@ describe('InsightDisplayConfig', () => {'Stack bars','Show values on series','Show percentages on series',- 'Show legendRight',+ 'Show legend',+ 'Legend positionRight',],},],@@ -384,9 +397,9 @@ describe('InsightDisplayConfig', () => {expect(getSectionItems('options-overlays-section')).toEqual(['Show trend lines','Show moving average',- 'Intervalsdays',+ 'Intervals days','Show confidence intervals',- 'Confidence level%',+ 'Confidence level %','Show alert threshold lines',])})@@ -457,14 +470,14 @@ describe('InsightDisplayConfig', () => {})describe('in-chart legend position options', () => {- it('keeps the "Show legend" checkbox and adds a position select on the same row', async () => {+ it('shows the "Show legend" toggle with a position select', async () => {setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))await openOptionsMenu()- const legendItem = getDisplaySectionItems().find((item) => item.includes('Show legend'))- expect(legendItem).toBeTruthy()+ const items = getDisplaySectionItems()+ expect(items).toContain('Show legend')// legend is off, no saved position → shows 'Bottom' as the prospective default- expect(legendItem).toContain('Bottom')+ expect(items).toContain('Legend positionBottom')})it.each([@@ -478,13 +491,12 @@ describe('InsightDisplayConfig', () => {setupAndRender(makeQuery())await openOptionsMenu()- const legendItem = getDisplaySectionItems().find((item) => item.includes('Show legend'))- expect(legendItem).toBeTruthy()+ const positionItem = getDisplaySectionItems().find((item) => item.startsWith('Legend position'))// Lifecycle sets showLegend:true (no saved position → 'Right'); others have legend off (→ 'Bottom').- expect(legendItem).toMatch(/Bottom|Right/)+ expect(positionItem).toMatch(/Bottom|Right/)})- it('keeps the plain "Show legend" checkbox for the aggregated bar-value chart', async () => {+ it('keeps the plain "Show legend" toggle for the aggregated bar-value chart', async () => {setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsBarValue))await openOptionsMenu()diff --git a/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.tsx b/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.tsxindex 7bf86e0772af..4530acd08591 100644--- a/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.tsx+++ b/products/product_analytics/frontend/insights/editor/InsightDisplayConfig.tsx@@ -5,6 +5,7 @@ import { IconEllipsis } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { ChartFilter } from 'lib/components/ChartFilter'+import { useDisplayOptions } from 'lib/components/ChartOptions/useDisplayOptions'import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'import { IntervalFilter } from 'lib/components/IntervalFilter'import { NON_TIME_SERIES_DISPLAY_TYPES } from 'lib/constants'@@ -26,7 +27,7 @@ import { RetentionBreakdownFilter } from 'products/product_analytics/frontend/inimport { RetentionChartPicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionChartPicker'import { RetentionDatePicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionDatePicker'-import { useInsightDisplayOptions } from './insightDisplayOptions'+import { insightDisplayOptions } from './insightDisplayOptions'import { InsightDisplayOptionsPanel } from './InsightDisplayOptionsPanel'export function InsightDisplayConfig({ chartTypeControl }: { chartTypeControl?: ReactNode }): JSX.Element {@@ -71,7 +72,7 @@ export function InsightDisplayConfig({ chartTypeControl }: { chartTypeControl?:isLifecycle ||((isTrends || isStickiness) && !(display && NON_TIME_SERIES_DISPLAY_TYPES.includes(display)))- const { tabs: displayOptionTabs, count: advancedOptionsCount } = useInsightDisplayOptions()+ const { tabs: displayOptionTabs, count: advancedOptionsCount } = useDisplayOptions(insightDisplayOptions)return (<divdiff --git a/products/product_analytics/frontend/insights/editor/InsightDisplayOptionsPanel.tsx b/products/product_analytics/frontend/insights/editor/InsightDisplayOptionsPanel.tsxindex 63fd498896f3..08a8deaa1bd3 100644--- a/products/product_analytics/frontend/insights/editor/InsightDisplayOptionsPanel.tsx+++ b/products/product_analytics/frontend/insights/editor/InsightDisplayOptionsPanel.tsx@@ -1,10 +1,10 @@import { useState } from 'react'+import { DisplayOptionSection, DisplayOptionTab, DisplayOptionTabKey } from 'lib/components/ChartOptions/displayOptions'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { cn } from 'lib/utils/css-classes'-import { SectionHeader } from './DisplayOptions'-import { DisplayOptionSection, DisplayOptionTab, DisplayOptionTabKey } from './insightDisplayOptions'+import { SectionHeader } from './SectionHeader'function DisplayOptionSectionList({ sections }: { sections: DisplayOptionSection[] }): JSX.Element {return (@@ -17,11 +17,12 @@ function DisplayOptionSectionList({ sections }: { sections: DisplayOptionSection{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+ className="flex flex-col gap-2 px-2 pt-1 pb-2"+ data-attr={section.title ? undefined : section.dataAttr}+ >+ {section.items.map((item) => (+ <li key={item.name}>{item.element}</li>))}</ul></section>diff --git a/products/product_analytics/frontend/insights/editor/SectionHeader.tsx b/products/product_analytics/frontend/insights/editor/SectionHeader.tsxnew file mode 100644index 000000000000..676fbf54bb4d--- /dev/null+++ b/products/product_analytics/frontend/insights/editor/SectionHeader.tsx@@ -0,0 +1,28 @@+import { ReactNode } from 'react'++import { IconInfo } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++export function SectionHeader({+ children,+ tooltip,+ dataAttr,+}: {+ children: ReactNode+ tooltip?: string+ dataAttr?: string+}): JSX.Element {+ return (+ <h5 className="mx-2 my-1" data-attr={dataAttr}>+ {children}+ {tooltip && (+ <>+ {' '}+ <Tooltip title={tooltip}>+ <IconInfo className="relative top-0.5 text-lg text-secondary" />+ </Tooltip>+ </>+ )}+ </h5>+ )+}diff --git a/products/product_analytics/frontend/insights/editor/filters/AnnotationsPicker.tsx b/products/product_analytics/frontend/insights/editor/filters/AnnotationsPicker.tsxdeleted file mode 100644index 8013e471c9d3..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/AnnotationsPicker.tsx+++ /dev/null@@ -1,45 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSelect, LemonSelectOptions } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { AnnotationScope } from '~/types'--import { annotationScopeToName } from 'products/annotations/frontend/logics/annotationModalLogic'--type AnnotationsSelection = AnnotationScope | 'all' | 'none'--const OPTIONS: LemonSelectOptions<AnnotationsSelection> = [- { value: 'all', label: 'All' },- { value: 'none', label: 'None' },- ...Object.values(AnnotationScope).map((scope) => ({- value: scope,- label: annotationScopeToName[scope],- })),-]--export function AnnotationsPicker(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { showAnnotations, annotationsScope } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- return (- <div className="mb-2.5 mx-2">- <LemonSelect- size="small"- fullWidth- value={showAnnotations === false ? 'none' : (annotationsScope ?? 'all')}- options={OPTIONS}- onChange={(selection) =>- updateInsightFilter({- showAnnotations: selection === 'none' ? false : undefined,- annotationsScope: selection === 'all' || selection === 'none' ? undefined : selection,- })- }- data-attr="insight-annotations-picker"- />- </div>- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/AxisLabelFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/AxisLabelFilter.tsxdeleted file mode 100644index 855a69d20ddc..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/AxisLabelFilter.tsx+++ /dev/null@@ -1,41 +0,0 @@-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/products/product_analytics/frontend/insights/editor/filters/HideIncompleteConversionWindowPeriodsFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/HideIncompleteConversionWindowPeriodsFilter.tsxdeleted file mode 100644index e96fb3caeaae..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/HideIncompleteConversionWindowPeriodsFilter.tsx+++ /dev/null@@ -1,43 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconInfo } from '@posthog/icons'-import { LemonCheckbox, Tooltip } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { isFunnelsQuery } from '~/queries/schema/node-guards'--export function HideIncompleteConversionWindowPeriodsFilter(): JSX.Element | null {- const { insightProps } = useValues(insightLogic)- const { querySource } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- if (!isFunnelsQuery(querySource)) {- return null- }-- const hideIncompleteConversionWindowPeriods =- querySource.funnelsFilter?.hideIncompleteConversionWindowPeriods ?? false-- return (- <LemonCheckbox- className="p-1 px-2"- onChange={() =>- updateInsightFilter({- hideIncompleteConversionWindowPeriods: !hideIncompleteConversionWindowPeriods,- })- }- checked={hideIncompleteConversionWindowPeriods}- label={- <span className="font-normal inline-flex items-center gap-1">- Hide incomplete periods- <Tooltip title="Hides recent periods whose conversion window hasn't fully elapsed, so the trend isn't dragged down by entrants who still have time to convert.">- <IconInfo className="relative top-0.5 text-base text-secondary" />- </Tooltip>- </span>- }- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/LegendOptionsFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/LegendOptionsFilter.tsxdeleted file mode 100644index c45c5fc0b885..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/LegendOptionsFilter.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox, LemonSelect } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import type { TrendsFilter } from '~/queries/schema/schema-general'--type LegendPosition = NonNullable<TrendsFilter['legendPosition']>--const POSITION_OPTIONS: { value: LegendPosition; label: string }[] = [- { value: 'bottom', label: 'Bottom' },- { value: 'top', label: 'Top' },- { value: 'left', label: 'Left' },- { value: 'right', label: 'Right' },-]--export function LegendOptionsFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { showLegend, legendPosition } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- return (- <div className="flex items-center justify-between gap-2 p-1 px-2">- <LemonCheckbox- onChange={(checked) =>- updateInsightFilter({- showLegend: checked,- // Seed bottom on first enable — old insights without a saved position render right (chart-config fallback).- ...(checked && legendPosition == null ? { legendPosition: 'bottom' } : {}),- })- }- checked={!!showLegend}- label={<span className="font-normal">Show legend</span>}- size="small"- />- <LemonSelect- size="small"- value={(legendPosition ?? (showLegend ? 'right' : 'bottom')) as LegendPosition}- options={POSITION_OPTIONS}- disabledReason={!showLegend ? 'Enable the legend to set its position' : undefined}- onChange={(position) => updateInsightFilter({ legendPosition: position })}- />- </div>- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/LineStylePicker.tsx b/products/product_analytics/frontend/insights/editor/filters/LineStylePicker.tsxdeleted file mode 100644index 0d52497175be..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/LineStylePicker.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSegmentedButton } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import type { TrendsFilter } from '~/queries/schema/schema-general'--export function LineStylePicker(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { insightFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- // chartStyle exists on every filter kind this picker renders for (trends, stickiness,- // retention, funnels) — TrendsFilter stands in for the union member carrying it.- const chartStyle = (insightFilter as TrendsFilter | undefined)?.chartStyle-- return (- <LemonSegmentedButton- className="pb-2 px-2"- onChange={(value) =>- updateInsightFilter({- chartStyle: { ...chartStyle, curve: value as 'smooth' | 'linear' },- })- }- // Unset curve falls through to the app default, which is smooth.- value={chartStyle?.curve || 'smooth'}- options={[- { value: 'smooth', label: 'Smooth' },- { value: 'linear', label: 'Straight' },- ]}- size="small"- fullWidth- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/MetricFilters.tsx b/products/product_analytics/frontend/insights/editor/filters/MetricFilters.tsxdeleted file mode 100644index c231e0270dcb..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/MetricFilters.tsx+++ /dev/null@@ -1,101 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSelect } from '@posthog/lemon-ui'--import { MetricDirectionColorPickers } from 'lib/components/Metric/MetricDirectionColorPickers'-import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import {- METRIC_COLOR_BY_DIRECTION_DEFAULT,- METRIC_DEFAULT_DECREASE_COLOR,- METRIC_DEFAULT_INCREASE_COLOR,- METRIC_SHOW_CHANGE_DEFAULT,- METRIC_SUMMARY_DEFAULT,- type MetricSummary,-} from 'products/product_analytics/frontend/insights/trends/Metric/Metric.utils'--export function MetricSummaryFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const summary = trendsFilter?.metricSummary ?? METRIC_SUMMARY_DEFAULT-- return (- <div className="flex items-center justify-between gap-2 p-1 px-2">- <span className="font-normal">Headline value</span>- <LemonSelect<MetricSummary>- size="small"- value={summary}- onChange={(value) => updateInsightFilter({ metricSummary: value })}- options={[- { value: 'total', label: 'Total' },- { value: 'average', label: 'Average' },- { value: 'latest', label: 'Latest' },- ]}- />- </div>- )-}--export function MetricShowChangeFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const showChange = trendsFilter?.metricShowChange ?? METRIC_SHOW_CHANGE_DEFAULT-- return (- <div className="flex flex-col">- <LemonCheckbox- className="p-1 px-2"- checked={showChange}- onChange={() => updateInsightFilter({ metricShowChange: !showChange })}- label={<span className="font-normal">Show change</span>}- size="small"- />- {showChange && (- <MetricDirectionColorPickers- className="gap-1 pl-5"- rowClassName="p-1 px-2"- increaseColor={trendsFilter?.metricChangeIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR}- decreaseColor={trendsFilter?.metricChangeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR}- onIncrease={(color) => updateInsightFilter({ metricChangeIncreaseColor: color })}- onDecrease={(color) => updateInsightFilter({ metricChangeDecreaseColor: color })}- />- )}- </div>- )-}--export function MetricColorFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { trendsFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const colorByDirection = trendsFilter?.metricColorByDirection ?? METRIC_COLOR_BY_DIRECTION_DEFAULT-- return (- <div className="flex flex-col">- <LemonCheckbox- className="p-1 px-2"- checked={colorByDirection}- onChange={() => updateInsightFilter({ metricColorByDirection: !colorByDirection })}- label={<span className="font-normal">Color by trend</span>}- size="small"- />- {colorByDirection && (- <MetricDirectionColorPickers- className="gap-1 pl-5"- rowClassName="p-1 px-2"- increaseColor={trendsFilter?.metricLineIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR}- decreaseColor={trendsFilter?.metricLineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR}- onIncrease={(color) => updateInsightFilter({ metricLineIncreaseColor: color })}- onDecrease={(color) => updateInsightFilter({ metricLineDecreaseColor: color })}- />- )}- </div>- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/PercentStackViewFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/PercentStackViewFilter.tsxdeleted file mode 100644index 91da1b22221a..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/PercentStackViewFilter.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'--import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--export function PercentStackViewFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { showPercentStackView } = useValues(trendsDataLogic(insightProps))- const { updateInsightFilter } = useActions(trendsDataLogic(insightProps))-- return (- <LemonCheckbox- className="p-1 px-2"- checked={!!showPercentStackView}- onChange={(checked) => {- updateInsightFilter({ showPercentStackView: checked })- }}- label={<span className="font-normal">Show as % of total</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ResultCustomizationByPicker.tsx b/products/product_analytics/frontend/insights/editor/filters/ResultCustomizationByPicker.tsxdeleted file mode 100644index 4b60cfa919b4..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ResultCustomizationByPicker.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSegmentedButton } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'--import { ResultCustomizationBy } from '~/queries/schema/schema-general'--import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--export function ResultCustomizationByPicker(): JSX.Element | null {- const { insightProps } = useValues(insightLogic)- const { resultCustomizationBy } = useValues(trendsDataLogic(insightProps))- const { updateInsightFilter } = useActions(trendsDataLogic(insightProps))-- return (- <LemonSegmentedButton- className="pb-2 px-2"- onChange={(value) => updateInsightFilter({ resultCustomizationBy: value as ResultCustomizationBy })}- value={resultCustomizationBy}- options={[- { value: ResultCustomizationBy.Value, label: 'By name' },- { value: ResultCustomizationBy.Position, label: 'By rank' },- ]}- size="small"- fullWidth- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ScalePicker.tsx b/products/product_analytics/frontend/insights/editor/filters/ScalePicker.tsxdeleted file mode 100644index 5ec6ef173c24..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ScalePicker.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSegmentedButton } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function ScalePicker(): JSX.Element | null {- const { insightProps } = useValues(insightLogic)- const { yAxisScaleType } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- return (- <LemonSegmentedButton- className="pb-2 px-2"- onChange={(value) => updateInsightFilter({ yAxisScaleType: value as 'linear' | 'log10' })}- value={yAxisScaleType || 'linear'}- options={[- { value: 'linear', label: 'Linear' },- { value: 'log10', label: 'Logarithmic' },- ]}- size="small"- fullWidth- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ShowAlertAnomalyPointsFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ShowAlertAnomalyPointsFilter.tsxindex 862e1685d0f7..f04fd4cae303 100644--- a/products/product_analytics/frontend/insights/editor/filters/ShowAlertAnomalyPointsFilter.tsx+++ b/products/product_analytics/frontend/insights/editor/filters/ShowAlertAnomalyPointsFilter.tsx@@ -1,7 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonCheckbox } from '@posthog/lemon-ui'-+import { ChartOptionSwitch } from 'lib/components/ChartOptions/ChartOptionSwitch'import { insightLogic } from 'scenes/insights/insightLogic'import { insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'@@ -17,12 +16,10 @@ export function ShowAlertAnomalyPointsFilter(): JSX.Element | null {}return (- <LemonCheckbox- className="p-1 px-2"- onChange={() => setShowAlertAnomalyPoints(!showAlertAnomalyPointsFlag)}+ <ChartOptionSwitch+ label="Show alert anomaly points"checked={showAlertAnomalyPointsFlag}- label={<span className="font-normal">Show alert anomaly points</span>}- size="small"+ onChange={(checked) => setShowAlertAnomalyPoints(checked)}/>)}diff --git a/products/product_analytics/frontend/insights/editor/filters/ShowAlertThresholdLinesFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ShowAlertThresholdLinesFilter.tsxdeleted file mode 100644index 0ca62f7b099e..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ShowAlertThresholdLinesFilter.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function ShowAlertThresholdLinesFilter(): JSX.Element | null {- const { insightProps } = useValues(insightLogic)- const { showAlertThresholdLines } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const toggleShowAlertThresholdLines = (): void => {- updateInsightFilter({ showAlertThresholdLines: !showAlertThresholdLines })- }-- return (- <LemonCheckbox- className="p-1 px-2"- onChange={toggleShowAlertThresholdLines}- checked={!!showAlertThresholdLines}- label={<span className="font-normal">Show alert threshold lines</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ShowLegendFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ShowLegendFilter.tsxdeleted file mode 100644index 6bf11e214e3b..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ShowLegendFilter.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function ShowLegendFilter(): JSX.Element | null {- const { insightProps } = useValues(insightLogic)- const { showLegend } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const toggleShowLegend = (): void => {- updateInsightFilter({ showLegend: !showLegend })- }-- return (- <LemonCheckbox- className="p-1 px-2"- onChange={toggleShowLegend}- checked={!!showLegend}- label={<span className="font-normal">Show legend</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ShowMultipleYAxesFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ShowMultipleYAxesFilter.tsxdeleted file mode 100644index cbda10823d5c..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ShowMultipleYAxesFilter.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function ShowMultipleYAxesFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { showMultipleYAxes } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const toggleShowMultipleYAxes = (): void => {- updateInsightFilter({ showMultipleYAxes: !showMultipleYAxes })- }-- return (- <LemonCheckbox- className="p-1 px-2"- onChange={toggleShowMultipleYAxes}- checked={!!showMultipleYAxes}- label={<span className="font-normal">Show multiple Y-axes</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ShowPieTotalFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ShowPieTotalFilter.tsxdeleted file mode 100644index 66b67f9d6d42..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ShowPieTotalFilter.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { ChartDisplayType } from '~/types'--import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--export function ShowPieTotalFilter(): JSX.Element | null {- const { insightProps } = useValues(insightLogic)- const { display, pieChartVizOptions } = useValues(trendsDataLogic(insightProps))- const { updateVizSpecificOptions } = useActions(insightVizDataLogic(insightProps))-- const showTotal = !pieChartVizOptions?.hideAggregation-- const toggleShowTotal = (): void => {- updateVizSpecificOptions({- // Donut stores its options under the pie key too, so the setting survives switching between them.- [ChartDisplayType.ActionsPie]: {- ...pieChartVizOptions,- hideAggregation: showTotal,- },- })- }-- return (- <LemonCheckbox- className="p-1 px-2"- onChange={toggleShowTotal}- checked={showTotal}- label={- <span className="font-normal">- {display === ChartDisplayType.ActionsDonut ? 'Show total in center' : 'Show total below chart'}- </span>- }- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ShowTrendLinesFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ShowTrendLinesFilter.tsxdeleted file mode 100644index 64db5a114536..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ShowTrendLinesFilter.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { isFunnelsQuery, isRetentionQuery, isTrendsQuery } from '~/queries/schema/node-guards'-import { ChartDisplayType } from '~/types'--import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'--export function ShowTrendLinesFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { querySource, trendsFilter, yAxisScaleType } = useValues(insightVizDataLogic(insightProps))- const { isTrendsFunnel } = useValues(funnelDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))-- // Get the current state based on query type- const showTrendLines = isRetentionQuery(querySource)- ? querySource.retentionFilter.showTrendLines- : isTrendsQuery(querySource)- ? querySource.trendsFilter?.showTrendLines- : isFunnelsQuery(querySource)- ? querySource.funnelsFilter?.showTrendLines- : false-- // Determine if trend lines should be disabled based on chart type and scale- const isLinearScale = !yAxisScaleType || yAxisScaleType === 'linear'- const isLineGraph = isTrendsQuery(querySource)- ? (trendsFilter?.display || ChartDisplayType.ActionsLineGraph) === ChartDisplayType.ActionsLineGraph ||- (trendsFilter?.display || ChartDisplayType.ActionsLineGraph) === ChartDisplayType.ActionsLineGraphCumulative- : isFunnelsQuery(querySource)- ? isTrendsFunnel- : true // Retention graphs are always line graphs-- const disabledReason = !isLineGraph- ? 'Trend lines are only available for line graphs'- : !isLinearScale- ? 'Trend lines are only supported for linear scale.'- : undefined-- const toggleShowTrendLines = (): void => {- if (isRetentionQuery(querySource)) {- updateQuerySource({- retentionFilter: { ...querySource.retentionFilter, showTrendLines: !showTrendLines },- } as any)- } else if (isTrendsQuery(querySource)) {- updateQuerySource({ trendsFilter: { ...querySource.trendsFilter, showTrendLines: !showTrendLines } } as any)- } else if (isFunnelsQuery(querySource)) {- updateQuerySource({- funnelsFilter: { ...querySource.funnelsFilter, showTrendLines: !showTrendLines },- } as any)- }- }-- return (- <LemonCheckbox- className="p-1 px-2"- onChange={toggleShowTrendLines}- checked={!disabledReason && !!showTrendLines}- disabledReason={disabledReason}- label={<span className="font-normal">Show trend lines</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/SliceNamesFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/SliceNamesFilter.tsxdeleted file mode 100644index f59197572242..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/SliceNamesFilter.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--// Pie only — it's the one display that draws the series label on the chart itself.-export function SliceNamesFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))- const { showLabelOnSeries } = useValues(insightVizDataLogic(insightProps))-- return (- <LemonCheckbox- className="p-1 px-2"- checked={!!showLabelOnSeries}- onChange={() => {- updateInsightFilter({ showLabelsOnSeries: !showLabelOnSeries })- }}- label={<span className="font-normal">Show names on slices</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/StackBreakdownFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/StackBreakdownFilter.tsxdeleted file mode 100644index 417c264e0068..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/StackBreakdownFilter.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'--import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--export function StackBreakdownFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { trendsFilter } = useValues(trendsDataLogic(insightProps))- const { updateInsightFilter } = useActions(trendsDataLogic(insightProps))-- return (- <LemonCheckbox- className="p-1 px-2"- checked={!!trendsFilter?.stackBreakdownValues}- onChange={(checked) => {- updateInsightFilter({ stackBreakdownValues: checked })- }}- label={<span className="font-normal">Stack breakdown values</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/ValueOnSeriesFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/ValueOnSeriesFilter.tsxdeleted file mode 100644index 1db991877dfa..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/ValueOnSeriesFilter.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function ValueOnSeriesFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))- const { showValuesOnSeries } = useValues(insightVizDataLogic(insightProps))-- return (- <LemonCheckbox- className="p-1 px-2"- checked={!!showValuesOnSeries}- onChange={() => {- updateInsightFilter({ showValuesOnSeries: !showValuesOnSeries })- }}- label={<span className="font-normal">Show values on series</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter.tsx b/products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter.tsxdeleted file mode 100644index 8780b02f1dc6..000000000000--- a/products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect, useState } from 'react'--import { LemonInput, LemonSwitch } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function YAxisRangeFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { trendsFilter, yAxisScaleType, showPercentStackView } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const [minDraft, setMinDraft] = useState(trendsFilter?.yAxisMin)- const [maxDraft, setMaxDraft] = useState(trendsFilter?.yAxisMax)-- useEffect(() => {- setMinDraft(trendsFilter?.yAxisMin)- }, [trendsFilter?.yAxisMin])-- useEffect(() => {- setMaxDraft(trendsFilter?.yAxisMax)- }, [trendsFilter?.yAxisMax])-- const rangeDisabledReason =- yAxisScaleType === 'log10'- ? 'Not available on a logarithmic scale'- : showPercentStackView- ? 'Not available while showing percentages'- : undefined- // 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-- // An inverted pair sends the chart back to its automatic range, which otherwise just looks like- // the controls not responding. Nothing to warn about while the minimum is disabled.- const invalidRange =- !beginsAtZero &&- typeof trendsFilter?.yAxisMin === 'number' &&- typeof trendsFilter?.yAxisMax === 'number' &&- trendsFilter.yAxisMin >= trendsFilter.yAxisMax-- // Commit on blur, not on change: a number input reads as empty mid-entry, so every keystroke- // would clear the bound. An emptied input reports NaN, which must become `undefined` because- // the chart ignores NaN while the Options badge still counts it, leaving no way to clear it.- const asBound = (value: number | undefined): number | undefined =>- typeof value === 'number' && isFinite(value) ? value : undefined- const commitMin = (): void => updateInsightFilter({ yAxisMin: asBound(minDraft) })- const commitMax = (): void => updateInsightFilter({ yAxisMax: asBound(maxDraft) })-- return (- <div className="p-1 px-2 flex flex-col gap-2">- <LemonSwitch- className="flex-1 w-full"- label="Begin at zero"- tooltip="When off, the axis starts just below your lowest value instead of at zero, so small changes are easier to see."- data-attr="trends-y-axis-start-at-zero"- checked={beginsAtZero}- disabledReason={rangeDisabledReason}- onChange={(checked) => updateInsightFilter({ yAxisStartAtZero: checked ? undefined : false })}- />- {!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"- disabledReason={rangeDisabledReason}- onChange={setMaxDraft}- onBlur={commitMax}- onPressEnter={commitMax}- />- </label>- {invalidRange && <span className="text-xs text-danger">Maximum must be greater than minimum.</span>}- </div>- )-}diff --git a/products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter.test.tsx b/products/product_analytics/frontend/insights/editor/insightDisplayOptions.test.tsxsimilarity index 89%rename from products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter.test.tsxrename to products/product_analytics/frontend/insights/editor/insightDisplayOptions.test.tsxindex db20430e620a..d2cb0e9f1999 100644--- a/products/product_analytics/frontend/insights/editor/filters/YAxisRangeFilter.test.tsx+++ b/products/product_analytics/frontend/insights/editor/insightDisplayOptions.test.tsx@@ -2,7 +2,9 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'import { BindLogic, Provider } from 'kea'+import { Fragment } from 'react'+import { useDisplayOptions } from 'lib/components/ChartOptions/useDisplayOptions'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'@@ -13,7 +15,7 @@ import { NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-genimport { initKeaTests } from '~/test/init'import { BaseMathType, ChartDisplayType, InsightShortId } from '~/types'-import { YAxisRangeFilter } from './YAxisRangeFilter'+import { insightDisplayOptions } from './insightDisplayOptions'const insightProps = { dashboardItemId: '123' as InsightShortId }@@ -25,7 +27,19 @@ function makeQuery(trendsFilter: TrendsFilter, display = ChartDisplayType.Action}}-describe('YAxisRangeFilter', () => {+function YAxisOptions(): JSX.Element {+ const { tabs } = useDisplayOptions(insightDisplayOptions)+ const items = tabs.flatMap((tab) => tab.sections).find((section) => section.key === 'y-axis')?.items ?? []+ return (+ <>+ {items.map((item) => (+ <Fragment key={item.name}>{item.element}</Fragment>+ ))}+ </>+ )+}++describe('insight Y-axis range options', () => {beforeEach(() => {useMocks({get: {@@ -49,7 +63,7 @@ describe('YAxisRangeFilter', () => {return render(<Provider><BindLogic logic={insightLogic} props={insightProps}>- <YAxisRangeFilter />+ <YAxisOptions /></BindLogic></Provider>).containerdiff --git a/products/product_analytics/frontend/insights/editor/insightDisplayOptions.tsx b/products/product_analytics/frontend/insights/editor/insightDisplayOptions.tsxindex 6408cff98bbd..e2c23ed9938a 100644--- a/products/product_analytics/frontend/insights/editor/insightDisplayOptions.tsx+++ b/products/product_analytics/frontend/insights/editor/insightDisplayOptions.tsx@@ -1,47 +1,114 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'import { normalizeAxisLabel } from '@posthog/quill-charts'+import { DisplayOptionBindings, type DisplayOptionValue } 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,+ METRIC_SUMMARY_DEFAULT,+} from 'lib/components/Metric/metricSummary'import { smoothingOptions } from 'lib/components/SmoothingFilter/smoothings'+import { UnitPicker } from 'lib/components/UnitPicker/UnitPicker'import { PART_OF_WHOLE_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { insightLogic, type insightLogicType } from 'scenes/insights/insightLogic'+import { insightVizDataLogic, type insightVizDataLogicType } from 'scenes/insights/insightVizDataLogic'-import { hasBreakdownFilter } from '~/queries/schema/node-guards'+import { hasBreakdownFilter, isFunnelsQuery, isRetentionQuery, isTrendsQuery } from '~/queries/schema/node-guards'import type { RetentionFilter, TrendsFilter } from '~/queries/schema/schema-general'-import { ChartDisplayType } from '~/types'+import { ChartDisplayType, RetentionDashboardDisplayType } from '~/types'import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'-import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'+import {+ INTERVAL_TO_DEFAULT_MOVING_AVERAGE_PERIOD,+ trendsDataLogic,+ type trendsDataLogicType,+} from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'-import { DisplayOption, DisplayOptions } from './DisplayOptions'import { BAR_DISPLAYS, displayMatches, isDefaultTrendsLineDisplay, LINE_DISPLAYS } from './displayTypes'+import { ShowAlertAnomalyPointsFilter } from './filters/ShowAlertAnomalyPointsFilter'-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-}+type VizValues = insightVizDataLogicType['values']+type VizActions = insightVizDataLogicType['actions']+type TrendsValues = trendsDataLogicType['values']-function countTruthy(...flags: (boolean | null | undefined)[]): number {- return flags.filter(Boolean).length+interface InsightDisplayContext+ extends+ Pick<+ VizValues,+ | 'querySource'+ | 'isTrends'+ | 'isRetention'+ | 'isStickiness'+ | 'isLifecycle'+ | 'display'+ | 'interval'+ | 'breakdownFilter'+ | 'trendsFilter'+ | 'lifecycleFilter'+ | 'retentionFilter'+ | 'hasLegend'+ | 'showLegend'+ | 'legendPosition'+ | 'supportsValueOnSeries'+ | 'supportsPercentStackView'+ | 'supportsBarValueStacking'+ | 'supportsResultCustomizationBy'+ | 'showPercentStackView'+ | 'showLabelOnSeries'+ | 'showPercentagesOnSeries'+ | 'yAxisScaleType'+ | 'showMultipleYAxes'+ | 'showAlertThresholdLines'+ | 'showAnnotations'+ | 'annotationsScope'+ >,+ Pick<+ TrendsValues,+ | 'showValuesOnSeries'+ | 'mightContainFractionalNumbers'+ | 'showConfidenceIntervals'+ | 'showMovingAverage'+ | 'confidenceLevel'+ | 'movingAverageIntervals'+ | 'resultCustomizationBy'+ | 'pieChartVizOptions'+ >,+ Pick<insightLogicType['values'], 'canEditInsight' | 'editingDisabledReason'>,+ Pick<VizActions, 'updateInsightFilter' | 'updateQuerySource' | 'updateVizSpecificOptions'> {+ isTrendsFunnel: boolean+ isMetric: boolean+ isBoxPlot: boolean+ isPie: boolean+ isPartOfWhole: boolean+ isCalendarHeatmap: boolean+ isLineDisplay: boolean+ isBarDisplay: boolean+ isLineChartInsight: boolean+ isLinearScale: boolean+ isOverlayLineGraph: boolean+ isTrendLineGraph: boolean+ hideContinuousChartOptions: boolean+ lineFilter: TrendsFilter | undefined+ showDisplaySection: boolean+ showFullDisplayList: boolean+ showFunnelLegendConfig: boolean+ useQuillLegendOptions: boolean+ showYAxisScale: boolean+ showYAxisRange: boolean+ showStatisticalOverlays: boolean+ showAlertThresholdLinesConfig: boolean+ yAxisStartsAtZero: boolean+ yAxisRangeDisabledReason: string | undefined+ showTrendLines: boolean | undefined}-// 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)+function useInsightDisplayContext(): InsightDisplayContext {+ const { insightProps, canEditInsight, editingDisabledReason } = useValues(insightLogic)const {querySource,isTrends,@@ -51,13 +118,18 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: ndisplay,breakdownFilter,trendsFilter,+ lifecycleFilter,+ retentionFilter,hasLegend,showLegend,+ legendPosition,supportsValueOnSeries,showPercentStackView,supportsPercentStackView,supportsBarValueStacking,supportsResultCustomizationBy,+ showLabelOnSeries,+ showPercentagesOnSeries,yAxisScaleType,showMultipleYAxes,showAlertThresholdLines,@@ -68,13 +140,19 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: nusesInChartLegend,insightFilter,} = useValues(insightVizDataLogic(insightProps))- const { isTrendsFunnel } = useValues(funnelDataLogic(insightProps))+ const { updateInsightFilter, updateQuerySource, updateVizSpecificOptions } = useActions(+ insightVizDataLogic(insightProps)+ )+ const isTrendsFunnel = !!useValues(funnelDataLogic(insightProps)).isTrendsFunnelconst {showValuesOnSeries,- showPercentagesOnSeries,mightContainFractionalNumbers,showConfidenceIntervals,showMovingAverage,+ confidenceLevel,+ movingAverageIntervals,+ resultCustomizationBy,+ pieChartVizOptions,} = useValues(trendsDataLogic(insightProps))// The slope graph shows the first vs last interval, so it drops the options that need the points@@ -82,289 +160,495 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: nconst isSlopeGraph = display === ChartDisplayType.SlopeGraphconst isMetric = display === ChartDisplayType.Metricconst isBoxPlot = display === ChartDisplayType.BoxPlot+ const isCalendarHeatmap = display === ChartDisplayType.CalendarHeatmap+ const isPie = !!display && PIE_DISPLAY_TYPES.includes(display)+ const isPartOfWhole = !!display && PART_OF_WHOLE_DISPLAY_TYPES.includes(display)const hideContinuousChartOptions = isNonTimeSeriesDisplay || isMetric || isSlopeGraph- const showSmoothing =- isTrends &&- !hasBreakdownFilter(breakdownFilter) &&- (!display || display === ChartDisplayType.ActionsLineGraph || display === ChartDisplayType.ActionsAreaGraph) &&- !!interval &&- (smoothingOptions[interval]?.length ?? 0) > 0- const showMultipleYAxesConfig = (isTrends || isStickiness) && !hideContinuousChartOptions && !isBoxPlot- const showAlertThresholdLinesConfig = isTrends && !hideContinuousChartOptions- const showAnnotationsConfig = ((isTrends && !hideContinuousChartOptions) || isTrendsFunnel) && !isBoxPlot- 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 =isDefaultTrendsLineDisplay(display, querySource) ||displayMatches(display, LINE_DISPLAYS) ||(!display && isStickiness)- const isBarDisplay = displayMatches(display, BAR_DISPLAYS)- const showAxisLabelsConfig = isTrends && (isLineDisplay || isBarDisplay)- const showFunnelLegendConfig = isTrendsFunnel && hasBreakdownFilter(breakdownFilter)- const isCalendarHeatmap = display === ChartDisplayType.CalendarHeatmap- const isPie = !!display && PIE_DISPLAY_TYPES.includes(display)- const isPartOfWhole = !!display && PART_OF_WHOLE_DISPLAY_TYPES.includes(display)- // Percent stacking swaps the raw values out for percentages, so there is no unit left to pick.- // A pie is the exception: it can show the value and the percentage together.- const showsRawValues = !showPercentStackView || (isPie && !!showValuesOnSeries)- // When the chart draws its own positioned in-chart legend, show the position selector instead- // of the legacy show/hide checkbox. usesInChartLegend is the single source of truth (same- // selector used by InsightVizDisplay to suppress the side legend). Funnel trends with breakdown- // also get the position selector since they render the quill legend via config.legend.- const useQuillLegendOptions = usesInChartLegend || showFunnelLegendConfig+ // Only the quill line charts (trends/stickiness line and area, retention and funnel-trends+ // graphs) draw curves. Retention and funnel trends default to their line graph when display is unset.+ const isLineChartInsight = isLineDisplay || ((isRetention || isTrendsFunnel) && !display)+ const isLinearScale = !yAxisScaleType || yAxisScaleType === 'linear'const showDisplaySection =(isTrends && !isCalendarHeatmap) || isRetention || isTrendsFunnel || isStickiness || isLifecycle+ // The box plot and slope graph show only a legend (and the box plot its outliers toggle).+ const showFullDisplayList = showDisplaySection && !isBoxPlot && !isSlopeGraph+ const showFunnelLegendConfig = isTrendsFunnel && hasBreakdownFilter(breakdownFilter)const showYAxisScale = !hideContinuousChartOptions && isTrends && !isCalendarHeatmap- // Bars encode magnitude as length from zero, so a bounded baseline misreads them: 10 vs 11- // would draw as 1 vs 2.- const showYAxisRangeConfig = showYAxisScale && isLineDisplay- // Only the quill line charts (trends/stickiness line and area, retention and funnel-trends- // graphs) draw curves, so they're the only ones with curvature to straighten. Retention and- // funnel trends default to their line graph when display is unset.- 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 = (): DisplayOption[] => {- const displayItems: DisplayOption[] = []-- if (isBoxPlot) {- if (hasLegend) {- displayItems.push(DisplayOptions.Legend)- }- displayItems.push(DisplayOptions.ExcludeOutliers)- return displayItems- }+ const lineFilter = insightFilter as TrendsFilter | undefined+ const showTrendLines = isRetentionQuery(querySource)+ ? querySource.retentionFilter.showTrendLines+ : isTrendsQuery(querySource)+ ? querySource.trendsFilter?.showTrendLines+ : isFunnelsQuery(querySource)+ ? querySource.funnelsFilter?.showTrendLines+ : false+ const isTrendLineGraph = isTrendsQuery(querySource)+ ? [ChartDisplayType.ActionsLineGraph, ChartDisplayType.ActionsLineGraphCumulative].includes(+ trendsFilter?.display || ChartDisplayType.ActionsLineGraph+ )+ : isFunnelsQuery(querySource)+ ? isTrendsFunnel+ : true- if (isSlopeGraph) {- // A slope only shows the first vs last interval of each series — the legend (when there- // are multiple series) is the only display option that applies.- if (hasLegend) {- displayItems.push(DisplayOptions.Legend)- }- return displayItems- }-- if (isMetric) {- displayItems.push(DisplayOptions.MetricSummary, DisplayOptions.MetricShowChange, DisplayOptions.MetricColor)- }- if (isLifecycle) {- displayItems.push(DisplayOptions.LifecycleStacking)- }- if (supportsValueOnSeries) {- displayItems.push(DisplayOptions.ValueLabels)- }- if (isLifecycle) {- displayItems.push(DisplayOptions.LifecyclePercentages)- }- if (supportsPercentStackView) {- displayItems.push(DisplayOptions.PercentStack)- }- if (supportsBarValueStacking) {- displayItems.push(DisplayOptions.StackBreakdown)- }- if ((hasLegend || showFunnelLegendConfig) && !useQuillLegendOptions) {- displayItems.push(DisplayOptions.Legend)- }- if (isPie) {- displayItems.push(DisplayOptions.SliceNames)- }- if (isPartOfWhole) {- displayItems.push(DisplayOptions.PieTotal)- }- if (isTrendsFunnel && !hideContinuousChartOptions) {- displayItems.push(DisplayOptions.HideIncompleteFunnelPeriods)- }- if (showAlertThresholdLinesConfig) {- displayItems.push(DisplayOptions.AlertAnomalyPoints)- }- if (useQuillLegendOptions) {- displayItems.push(DisplayOptions.LegendOptions)- }- return displayItems+ return {+ querySource,+ canEditInsight,+ editingDisabledReason,+ isTrends,+ isRetention,+ isStickiness,+ isLifecycle,+ isTrendsFunnel,+ isMetric,+ isBoxPlot,+ isPie,+ isPartOfWhole,+ isCalendarHeatmap,+ isLineDisplay,+ isBarDisplay: displayMatches(display, BAR_DISPLAYS),+ isLineChartInsight,+ isLinearScale,+ // Every trends line except the cumulative one, which the statistical overlays can't follow.+ isOverlayLineGraph:+ (isDefaultTrendsLineDisplay(display, querySource) || displayMatches(display, LINE_DISPLAYS)) &&+ display !== ChartDisplayType.ActionsLineGraphCumulative,+ isTrendLineGraph,+ hideContinuousChartOptions,+ display,+ interval,+ breakdownFilter,+ trendsFilter,+ lifecycleFilter,+ retentionFilter,+ lineFilter,+ showDisplaySection,+ showFullDisplayList,+ showFunnelLegendConfig,+ // When the chart draws its own positioned in-chart legend, show the position selector instead+ // of the legacy show/hide checkbox. Funnel trends with breakdown also get the position selector+ // since they render the quill legend via config.legend.+ useQuillLegendOptions: showFullDisplayList && (usesInChartLegend || showFunnelLegendConfig),+ hasLegend,+ showLegend,+ legendPosition,+ showYAxisScale,+ // Bars encode magnitude as length from zero, so a bounded baseline misreads them: 10 vs 11+ // would draw as 1 vs 2.+ showYAxisRange: showYAxisScale && isLineDisplay,+ showStatisticalOverlays: showYAxisScale && !isBoxPlot,+ showAlertThresholdLinesConfig: isTrends && !hideContinuousChartOptions,+ yAxisStartsAtZero: trendsFilter?.yAxisStartAtZero !== false,+ yAxisRangeDisabledReason:+ yAxisScaleType === 'log10'+ ? 'Not available on a logarithmic scale'+ : showPercentStackView+ ? 'Not available while showing percentages'+ : undefined,+ supportsValueOnSeries,+ supportsPercentStackView,+ supportsBarValueStacking,+ supportsResultCustomizationBy,+ showValuesOnSeries,+ showPercentStackView,+ showLabelOnSeries,+ showPercentagesOnSeries,+ mightContainFractionalNumbers,+ yAxisScaleType,+ showMultipleYAxes,+ showAlertThresholdLines,+ showAnnotations,+ annotationsScope,+ showTrendLines,+ showConfidenceIntervals,+ showMovingAverage,+ confidenceLevel,+ movingAverageIntervals,+ resultCustomizationBy,+ pieChartVizOptions,+ updateInsightFilter,+ updateQuerySource,+ updateVizSpecificOptions,}+}- const displaySections: DisplayOptionSection[] = []- const displayItems = getDisplayItems()- if (showDisplaySection && displayItems.length > 0) {- displaySections.push({ key: 'display', dataAttr: 'options-display-section', items: displayItems })- }- if (showAnnotationsConfig) {- displaySections.push({- key: 'annotations',- title: 'Annotations',- tooltip:- 'Annotations are saved on an insight, a dashboard, the project, or the organization. Choose which of those to show here.',- items: [DisplayOptions.Annotations],- })- }- if (showUnit) {- displaySections.push({ key: 'unit', title: 'Unit', items: [DisplayOptions.Unit] })- }- if (supportsResultCustomizationBy) {- 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 (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],- })+function updateTrendsFilter(c: InsightDisplayContext, patch: Partial<TrendsFilter>): void {+ if (isTrendsQuery(c.querySource)) {+ c.updateQuerySource({ ...c.querySource, trendsFilter: { ...c.querySource.trendsFilter, ...patch } })}+}- // 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) {- yAxisItems.push(DisplayOptions.Scale)- }- if (showYAxisRangeConfig) {- yAxisItems.push(DisplayOptions.YAxisRange)- }- if (yAxisItems.length > 0) {- axesSections.push({ key: 'y-axis', title: 'Y-axis', items: yAxisItems })+function retentionMeanLineDisabledReason(c: InsightDisplayContext): string | undefined {+ if ((c.retentionFilter?.selectedInterval ?? null) !== null) {+ return 'Mean line is not available when viewing a single interval.'}+ return hasBreakdownFilter(c.breakdownFilter) ? 'Mean line is not available with a breakdown applied.' : undefined+}- const styleItems: DisplayOption[] = []- if (showLineStyleConfig) {- styleItems.push(DisplayOptions.LineStyle)- }- if (showSmoothing) {- styleItems.push(DisplayOptions.Smoothing)- }- const overlayItems: DisplayOption[] = []- if (showTrendLinesConfig && !isBoxPlot) {- overlayItems.push(DisplayOptions.TrendLines)- }- if (showStatisticalOverlays) {- overlayItems.push(DisplayOptions.MovingAverage)- if (showMovingAverage) {- overlayItems.push(DisplayOptions.MovingAverageIntervals)- }- overlayItems.push(DisplayOptions.ConfidenceInterval)- if (showConfidenceIntervals) {- overlayItems.push(DisplayOptions.ConfidenceLevel)- }- }- if (showAlertThresholdLinesConfig && !isBoxPlot) {- overlayItems.push(DisplayOptions.AlertThresholdLines)- }- if (isRetention && isLineChartInsight) {- overlayItems.push(DisplayOptions.RetentionMeanLine)- }- const linesSections: DisplayOptionSection[] = []- if (styleItems.length > 0) {- linesSections.push({ key: 'style', title: 'Style', items: styleItems })- }- if (isRetention && isLineChartInsight) {- linesSections.push({- key: 'retention-series-colors',- title: 'Cohort line colors',- tooltip: 'One shade draws every cohort in the same color, with the newest cohort the most solid.',- items: [DisplayOptions.RetentionSeriesColorMode],- })- }- if (overlayItems.length > 0) {- linesSections.push({- key: 'overlays',- title: 'Overlays',- dataAttr: 'options-overlays-section',- items: overlayItems,- })- }+function showsMetricChange(c: InsightDisplayContext): boolean {+ return c.trendsFilter?.metricShowChange ?? METRIC_SHOW_CHANGE_DEFAULT+}- const unitIsSet =- showUnit && !!trendsFilter?.aggregationAxisFormat && trendsFilter.aggregationAxisFormat !== 'numeric'- // A proportion bar shows its legend by default, so only the user's own choice counts as a change.- const legendIsChanged =- display === ChartDisplayType.ActionsProportionBar ? trendsFilter?.showLegend !== undefined : showLegend- const displayCount = countTruthy(- supportsValueOnSeries && showValuesOnSeries,- isLifecycle && showPercentagesOnSeries,- showPercentStackView,- isPie && trendsFilter?.showLabelsOnSeries,- unitIsSet,- (hasLegend || showFunnelLegendConfig) && legendIsChanged,- showAnnotationsConfig && (showAnnotations === false || !!annotationsScope),- 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,- isRetention &&- isLineChartInsight &&- (insightFilter as TrendsFilter | undefined)?.chartStyle?.seriesColorMode === 'opacity',- isRetention && isLineChartInsight && (insightFilter as RetentionFilter | undefined)?.showMeanLine- )+function colorsMetricByDirection(c: InsightDisplayContext): boolean {+ return c.trendsFilter?.metricColorByDirection ?? METRIC_COLOR_BY_DIRECTION_DEFAULT+}- 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)+const INSIGHT_BINDINGS: DisplayOptionBindings<InsightDisplayContext> = {+ metricSummary: {+ showCondition: (c) => c.showFullDisplayList && c.isMetric,+ value: (c) => c.trendsFilter?.metricSummary ?? METRIC_SUMMARY_DEFAULT,+ onChange: (metricSummary, c) => c.updateInsightFilter({ metricSummary }),+ changedCount: (c) => !!c.trendsFilter?.metricSummary && c.trendsFilter.metricSummary !== 'total',+ },+ metricShowChange: {+ showCondition: (c) => c.showFullDisplayList && c.isMetric,+ value: showsMetricChange,+ onChange: (metricShowChange, c) => c.updateInsightFilter({ metricShowChange }),+ changedCount: (c) => c.trendsFilter?.metricShowChange === false,+ },+ metricChangeColors: {+ showCondition: (c) => c.showFullDisplayList && c.isMetric && showsMetricChange(c),+ value: (c) => ({+ increase: c.trendsFilter?.metricChangeIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR,+ decrease: c.trendsFilter?.metricChangeDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR,+ }),+ onChange: ({ increase, decrease }, c) =>+ c.updateInsightFilter({ metricChangeIncreaseColor: increase, metricChangeDecreaseColor: decrease }),+ },+ metricColorByDirection: {+ showCondition: (c) => c.showFullDisplayList && c.isMetric,+ value: colorsMetricByDirection,+ onChange: (metricColorByDirection, c) => c.updateInsightFilter({ metricColorByDirection }),+ changedCount: (c) => c.trendsFilter?.metricColorByDirection,+ },+ metricTrendColors: {+ showCondition: (c) => c.showFullDisplayList && c.isMetric && colorsMetricByDirection(c),+ value: (c) => ({+ increase: c.trendsFilter?.metricLineIncreaseColor ?? METRIC_DEFAULT_INCREASE_COLOR,+ decrease: c.trendsFilter?.metricLineDecreaseColor ?? METRIC_DEFAULT_DECREASE_COLOR,+ }),+ onChange: ({ increase, decrease }, c) =>+ c.updateInsightFilter({ metricLineIncreaseColor: increase, metricLineDecreaseColor: decrease }),+ },+ lifecycleStacking: {+ showCondition: (c) => c.showFullDisplayList && c.isLifecycle,+ value: (c) => c.lifecycleFilter?.stacked ?? true,+ onChange: (stacked, c) => c.updateInsightFilter({ stacked }),+ },+ valuesOnSeries: {+ showCondition: (c) => c.showFullDisplayList && c.supportsValueOnSeries,+ value: (c) => !!c.showValuesOnSeries,+ onChange: (showValuesOnSeries, c) => c.updateInsightFilter({ showValuesOnSeries }),+ changedCount: (c) => c.showValuesOnSeries,+ },+ lifecyclePercentages: {+ showCondition: (c) => c.showFullDisplayList && c.isLifecycle,+ value: (c) => !!c.showPercentagesOnSeries,+ onChange: (showPercentagesOnSeries, c) => c.updateInsightFilter({ showPercentagesOnSeries }),+ changedCount: (c) => c.showPercentagesOnSeries,+ },+ percentStack: {+ showCondition: (c) => c.showFullDisplayList && c.supportsPercentStackView,+ value: (c) => !!c.showPercentStackView,+ onChange: (showPercentStackView, c) => c.updateInsightFilter({ showPercentStackView }),+ changedCount: (c) => c.showPercentStackView,+ },+ stackBreakdown: {+ showCondition: (c) => c.showFullDisplayList && c.supportsBarValueStacking,+ value: (c) => !!c.trendsFilter?.stackBreakdownValues,+ onChange: (stackBreakdownValues, c) => c.updateInsightFilter({ stackBreakdownValues }),+ },+ sliceNames: {+ showCondition: (c) => c.showFullDisplayList && c.isPie,+ value: (c) => !!c.showLabelOnSeries,+ onChange: (showLabelsOnSeries, c) => c.updateInsightFilter({ showLabelsOnSeries }),+ changedCount: (c) => c.trendsFilter?.showLabelsOnSeries,+ },+ pieTotal: {+ showCondition: (c) => c.showFullDisplayList && c.isPartOfWhole,+ value: (c) => !c.pieChartVizOptions?.hideAggregation,+ onChange: (showTotal, c) =>+ c.updateVizSpecificOptions({+ // Donut stores its options under the pie key too, so the setting survives switching between them.+ [ChartDisplayType.ActionsPie]: { ...c.pieChartVizOptions, hideAggregation: !showTotal },+ }),+ },+ hideIncompleteFunnelPeriods: {+ showCondition: (c) => c.showFullDisplayList && c.isTrendsFunnel && !c.hideContinuousChartOptions,+ value: (c) =>+ isFunnelsQuery(c.querySource) && !!c.querySource.funnelsFilter?.hideIncompleteConversionWindowPeriods,+ onChange: (hideIncompleteConversionWindowPeriods, c) =>+ c.updateInsightFilter({ hideIncompleteConversionWindowPeriods }),+ },+ alertAnomalyPoints: {+ showCondition: (c) => c.showFullDisplayList && c.showAlertThresholdLinesConfig,+ render: () => <ShowAlertAnomalyPointsFilter />,+ },+ legend: {+ showCondition: (c) =>+ c.showFullDisplayList+ ? c.useQuillLegendOptions || c.hasLegend || c.showFunnelLegendConfig+ : c.showDisplaySection && c.hasLegend,+ value: (c) => !!c.showLegend,+ onChange: (showLegend, c) =>+ c.updateInsightFilter({+ showLegend,+ // Old insights without a saved position draw the legend on the right, so turning it on seeds bottom.+ ...(c.useQuillLegendOptions && showLegend && c.legendPosition == null+ ? { legendPosition: 'bottom' }+ : {}),+ }),+ // A proportion bar shows its legend by default, so only the user's own choice counts as a change.+ changedCount: (c) =>+ (c.hasLegend || c.showFunnelLegendConfig) &&+ (c.display === ChartDisplayType.ActionsProportionBar+ ? c.trendsFilter?.showLegend !== undefined+ : c.showLegend),+ },+ legendPosition: {+ showCondition: (c) => c.useQuillLegendOptions,+ value: (c) => (c.legendPosition ?? (c.showLegend ? 'right' : 'bottom')) as DisplayOptionValue<'legendPosition'>,+ onChange: (legendPosition, c) => c.updateInsightFilter({ legendPosition }),+ disabledReason: (c) => (c.showLegend ? undefined : 'Turn the legend on to set its position'),+ },+ excludeOutliers: {+ showCondition: (c) => c.showDisplaySection && c.isBoxPlot,+ value: (c) => c.trendsFilter?.excludeBoxPlotOutliers !== false,+ onChange: (excludeBoxPlotOutliers, c) => updateTrendsFilter(c, { excludeBoxPlotOutliers }),+ },++ annotations: {+ showCondition: (c) => ((c.isTrends && !c.hideContinuousChartOptions) || c.isTrendsFunnel) && !c.isBoxPlot,+ value: (c) => (c.showAnnotations === false ? 'none' : (c.annotationsScope ?? 'all')),+ onChange: (selection, c) =>+ c.updateInsightFilter({+ showAnnotations: selection === 'none' ? false : undefined,+ annotationsScope: selection === 'all' || selection === 'none' ? undefined : selection,+ }),+ dataAttr: 'insight-annotations-picker',+ changedCount: (c) => c.showAnnotations === false || !!c.annotationsScope,+ },+ unit: {+ // Percent stacking swaps the raw values out for percentages, so there is no unit left to pick.+ // A pie is the exception: it can show the value and the percentage together.+ showCondition: (c) =>+ (!c.showPercentStackView || (c.isPie && !!c.showValuesOnSeries)) && c.isTrends && !c.isCalendarHeatmap,+ render: () => <UnitPicker />,+ changedCount: (c) =>+ !!c.trendsFilter?.aggregationAxisFormat && c.trendsFilter.aggregationAxisFormat !== 'numeric',+ },+ resultCustomizationBy: {+ showCondition: (c) => c.supportsResultCustomizationBy,+ value: (c) => c.resultCustomizationBy,+ onChange: (resultCustomizationBy, c) => c.updateInsightFilter({ resultCustomizationBy }),+ },+ decimalPlaces: {+ showCondition: (c) => c.mightContainFractionalNumbers && c.isTrends && !c.isCalendarHeatmap,+ value: (c) => c.trendsFilter?.decimalPlaces,+ onChange: (decimalPlaces, c) => {+ c.updateInsightFilter({ decimalPlaces })+ posthog.capture('decimal places changed', { decimal_places: decimalPlaces })+ },+ },+ retentionDashboardDisplay: {+ showCondition: (c) => c.isRetention && c.canEditInsight,+ value: (c) => c.retentionFilter?.dashboardDisplay || RetentionDashboardDisplayType.TableOnly,+ onChange: (dashboardDisplay, c) => c.updateInsightFilter({ dashboardDisplay }),+ },+ retentionCohortLabelStart: {+ showCondition: (c) => c.isRetention && c.canEditInsight,+ value: (c) => c.retentionFilter?.cohortLabelStartIndex ?? 0,+ options: (c) => {+ const period = c.retentionFilter?.period || 'Day'+ return [+ { value: 0, label: `${period} 0` },+ { value: 1, label: `${period} 1` },+ ]+ },+ onChange: (cohortLabelStartIndex, c) =>+ c.updateInsightFilter({ cohortLabelStartIndex: cohortLabelStartIndex as number }),+ },- return { tabs, count: tabs.reduce((sum, tab) => sum + tab.count, 0) }+ xAxisLabel: {+ showCondition: (c) => c.isTrends && (c.isLineDisplay || c.isBarDisplay),+ value: (c) => c.trendsFilter?.xAxisLabel,+ onChange: (xAxisLabel, c) => c.updateInsightFilter({ xAxisLabel }),+ changedCount: (c) => !!normalizeAxisLabel(c.trendsFilter?.xAxisLabel),+ dataAttr: 'trends-x-axis-label-input',+ },+ yAxisLabel: {+ showCondition: (c) => c.isTrends && (c.isLineDisplay || c.isBarDisplay),+ value: (c) => c.trendsFilter?.yAxisLabel,+ onChange: (yAxisLabel, c) => c.updateInsightFilter({ yAxisLabel }),+ changedCount: (c) => !!normalizeAxisLabel(c.trendsFilter?.yAxisLabel),+ dataAttr: 'trends-y-axis-label-input',+ },+ // The minimum is hidden rather than cleared while the axis begins at zero, so the typed value+ // applies again when the toggle goes off.+ yAxisMin: {+ showCondition: (c) => c.showYAxisRange && !c.yAxisStartsAtZero,+ value: (c) => c.trendsFilter?.yAxisMin,+ onChange: (yAxisMin, c) => c.updateInsightFilter({ yAxisMin }),+ disabledReason: (c) => c.yAxisRangeDisabledReason,+ changedCount: (c) => typeof c.trendsFilter?.yAxisMin === 'number',+ dataAttr: 'trends-y-axis-min-input',+ },+ yAxisMax: {+ showCondition: (c) => c.showYAxisRange,+ value: (c) => c.trendsFilter?.yAxisMax,+ onChange: (yAxisMax, c) => c.updateInsightFilter({ yAxisMax }),+ disabledReason: (c) => c.yAxisRangeDisabledReason,+ // An inverted pair sends the chart back to its automatic range, which otherwise just looks like+ // the controls not responding.+ warning: (c) =>+ !c.yAxisStartsAtZero &&+ typeof c.trendsFilter?.yAxisMin === 'number' &&+ typeof c.trendsFilter?.yAxisMax === 'number' &&+ c.trendsFilter.yAxisMin >= c.trendsFilter.yAxisMax+ ? 'Maximum must be greater than minimum.'+ : null,+ changedCount: (c) => typeof c.trendsFilter?.yAxisMax === 'number',+ dataAttr: 'trends-y-axis-max-input',+ },+ yAxisBeginAtZero: {+ showCondition: (c) => c.showYAxisRange,+ value: (c) => c.yAxisStartsAtZero,+ onChange: (startsAtZero, c) => c.updateInsightFilter({ yAxisStartAtZero: startsAtZero ? undefined : false }),+ disabledReason: (c) => c.yAxisRangeDisabledReason,+ changedCount: (c) => !c.yAxisStartsAtZero,+ dataAttr: 'trends-y-axis-start-at-zero',+ },+ multipleYAxes: {+ showCondition: (c) => (c.isTrends || c.isStickiness) && !c.hideContinuousChartOptions && !c.isBoxPlot,+ value: (c) => !!c.showMultipleYAxes,+ onChange: (showMultipleYAxes, c) => c.updateInsightFilter({ showMultipleYAxes }),+ changedCount: (c) => c.showMultipleYAxes,+ },+ yAxisScale: {+ showCondition: (c) => c.showYAxisScale,+ value: (c) => (c.yAxisScaleType === 'log10' ? 'log' : 'linear'),+ onChange: (scale, c) => c.updateInsightFilter({ yAxisScaleType: scale === 'log' ? 'log10' : 'linear' }),+ changedCount: (c) => !!c.yAxisScaleType && c.yAxisScaleType !== 'linear',+ },++ lineStyle: {+ showCondition: (c) =>+ (c.isTrends || c.isStickiness || c.isRetention || c.isTrendsFunnel) && c.isLineChartInsight,+ value: (c) => c.lineFilter?.chartStyle?.curve || 'smooth',+ onChange: (curve, c) => c.updateInsightFilter({ chartStyle: { ...c.lineFilter?.chartStyle, curve } }),+ changedCount: (c) => c.lineFilter?.chartStyle?.curve === 'linear',+ },+ smoothing: {+ showCondition: (c) =>+ c.isTrends &&+ !hasBreakdownFilter(c.breakdownFilter) &&+ (!c.display ||+ c.display === ChartDisplayType.ActionsLineGraph ||+ c.display === ChartDisplayType.ActionsAreaGraph) &&+ !!c.interval &&+ (smoothingOptions[c.interval]?.length ?? 0) > 0,+ value: (c) => c.trendsFilter?.smoothingIntervals || 1,+ options: (c) => (c.interval ? smoothingOptions[c.interval] : []),+ onChange: (smoothingIntervals, c) =>+ c.updateInsightFilter({ smoothingIntervals: smoothingIntervals as number }),+ disabledReason: (c) => c.editingDisabledReason,+ changedCount: (c) => (c.trendsFilter?.smoothingIntervals ?? 1) !== 1,+ dataAttr: 'smoothing-filter',+ },+ retentionSeriesColorMode: {+ showCondition: (c) => c.isRetention && c.isLineChartInsight && c.canEditInsight,+ value: (c) => c.retentionFilter?.chartStyle?.seriesColorMode || 'palette',+ onChange: (seriesColorMode, c) =>+ c.updateInsightFilter({ chartStyle: { ...c.retentionFilter?.chartStyle, seriesColorMode } }),+ changedCount: (c) => c.lineFilter?.chartStyle?.seriesColorMode === 'opacity',+ },+ trendLines: {+ showCondition: (c) =>+ (c.isTrends || c.isRetention || c.isTrendsFunnel) && !c.hideContinuousChartOptions && !c.isBoxPlot,+ disabledReason: (c) =>+ !c.isTrendLineGraph+ ? 'Trend lines are only available for line graphs'+ : !c.isLinearScale+ ? 'Trend lines are only supported for linear scale.'+ : undefined,+ value: (c) => c.isTrendLineGraph && c.isLinearScale && !!c.showTrendLines,+ onChange: (showTrendLines, c) => {+ const source = c.querySource+ if (isRetentionQuery(source)) {+ c.updateQuerySource({ retentionFilter: { ...source.retentionFilter, showTrendLines } } as any)+ } else if (isTrendsQuery(source)) {+ c.updateQuerySource({ trendsFilter: { ...source.trendsFilter, showTrendLines } } as any)+ } else if (isFunnelsQuery(source)) {+ c.updateQuerySource({ funnelsFilter: { ...source.funnelsFilter, showTrendLines } } as any)+ }+ },+ changedCount: (c) => c.lineFilter?.showTrendLines,+ },+ movingAverage: {+ showCondition: (c) => c.showStatisticalOverlays,+ disabledReason: (c) =>+ !c.isOverlayLineGraph+ ? 'Moving average is only available for line and area graphs'+ : !c.isLinearScale+ ? 'Moving average is only supported for linear scale.'+ : undefined,+ value: (c) => c.showMovingAverage,+ onChange: (showMovingAverage, c) => updateTrendsFilter(c, { showMovingAverage }),+ changedCount: (c) => c.showMovingAverage,+ },+ movingAverageIntervals: {+ showCondition: (c) => c.showStatisticalOverlays && c.showMovingAverage,+ value: (c) => c.movingAverageIntervals,+ suffix: (c) => `${isTrendsQuery(c.querySource) ? c.querySource.interval || 'day' : 'day'}s`,+ onChange: (movingAverageIntervals, c) => {+ const interval = isTrendsQuery(c.querySource) ? c.querySource.interval || 'day' : 'day'+ updateTrendsFilter(c, {+ movingAverageIntervals: movingAverageIntervals ?? INTERVAL_TO_DEFAULT_MOVING_AVERAGE_PERIOD[interval],+ })+ },+ },+ confidenceInterval: {+ showCondition: (c) => c.showStatisticalOverlays,+ disabledReason: (c) =>+ !c.isOverlayLineGraph+ ? 'Confidence intervals are only available for line graphs'+ : !c.isLinearScale+ ? 'Confidence intervals are only supported for linear scale.'+ : undefined,+ value: (c) => c.showConfidenceIntervals,+ onChange: (showConfidenceIntervals, c) => updateTrendsFilter(c, { showConfidenceIntervals }),+ changedCount: (c) => c.showConfidenceIntervals,+ },+ confidenceLevel: {+ showCondition: (c) => c.showStatisticalOverlays && c.showConfidenceIntervals,+ value: (c) => c.confidenceLevel,+ onChange: (confidenceLevel, c) => updateTrendsFilter(c, { confidenceLevel: confidenceLevel ?? 95 }),+ },+ alertThresholdLines: {+ showCondition: (c) => c.showAlertThresholdLinesConfig && !c.isBoxPlot,+ value: (c) => !!c.showAlertThresholdLines,+ onChange: (showAlertThresholdLines, c) => c.updateInsightFilter({ showAlertThresholdLines }),+ changedCount: (c) => c.showAlertThresholdLines,+ },+ retentionMeanLine: {+ showCondition: (c) => c.isRetention && c.isLineChartInsight && c.canEditInsight,+ disabledReason: retentionMeanLineDisabledReason,+ value: (c) => !retentionMeanLineDisabledReason(c) && !!c.retentionFilter?.showMeanLine,+ onChange: (showMeanLine, c) => c.updateInsightFilter({ showMeanLine }),+ changedCount: (c) => (c.retentionFilter as RetentionFilter | undefined)?.showMeanLine,+ },+}++// The insight editor's "Options" panel and the options menu on a dashboard tile.+export const insightDisplayOptions: DisplayOptionsAdapter<InsightDisplayContext> = {+ useDisplayContext: useInsightDisplayContext,+ bindings: INSIGHT_BINDINGS,+ // Only trends has enough options to need tabs; the other insight types keep one flat list.+ settings: (c) => ({ singleTab: !c.isTrends }),}diff --git a/products/product_analytics/frontend/insights/lifecycle/filters/LifecyclePercentagesFilter.tsx b/products/product_analytics/frontend/insights/lifecycle/filters/LifecyclePercentagesFilter.tsxdeleted file mode 100644index 3f69ce3aa233..000000000000--- a/products/product_analytics/frontend/insights/lifecycle/filters/LifecyclePercentagesFilter.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function LifecyclePercentagesFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))- const { showPercentagesOnSeries } = useValues(insightVizDataLogic(insightProps))-- return (- <LemonCheckbox- className="p-1 px-2"- checked={!!showPercentagesOnSeries}- onChange={() => {- updateInsightFilter({ showPercentagesOnSeries: !showPercentagesOnSeries })- }}- label={<span className="font-normal">Show percentages on series</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/lifecycle/filters/LifecycleStackingFilter.tsx b/products/product_analytics/frontend/insights/lifecycle/filters/LifecycleStackingFilter.tsxdeleted file mode 100644index 2aa48a295ab0..000000000000--- a/products/product_analytics/frontend/insights/lifecycle/filters/LifecycleStackingFilter.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function LifecycleStackingFilter(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { lifecycleFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- return (- <LemonCheckbox- className="p-1 px-2"- checked={lifecycleFilter?.stacked ?? true}- onChange={(checked) => {- updateInsightFilter({ stacked: checked })- }}- label={<span className="font-normal">Stack bars</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionCohortLabelStartIndexPicker.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionCohortLabelStartIndexPicker.tsxdeleted file mode 100644index 2eb46cd4f981..000000000000--- a/products/product_analytics/frontend/insights/retention/filters/RetentionCohortLabelStartIndexPicker.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSegmentedButton } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function RetentionCohortLabelStartIndexPicker(): JSX.Element | null {- const { insightProps, canEditInsight } = useValues(insightLogic)-- const { retentionFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- if (!canEditInsight) {- return null- }-- const period = retentionFilter?.period || 'Day'-- return (- <LemonSegmentedButton- className="pb-2 px-2"- value={retentionFilter?.cohortLabelStartIndex ?? 0}- onChange={(value: number) => {- updateInsightFilter({ cohortLabelStartIndex: value })- }}- options={[- {- value: 0,- label: `${period} 0`,- },- {- value: 1,- label: `${period} 1`,- },- ]}- size="small"- fullWidth- />- )-}diff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionDashboardDisplayPicker.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionDashboardDisplayPicker.tsxdeleted file mode 100644index fd89183fa7d1..000000000000--- a/products/product_analytics/frontend/insights/retention/filters/RetentionDashboardDisplayPicker.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSelect } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { RetentionDashboardDisplayType } from '~/types'--export function RetentionDashboardDisplayPicker(): JSX.Element | null {- const { insightProps, canEditInsight } = useValues(insightLogic)- const { retentionFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- const displayType = retentionFilter?.dashboardDisplay || RetentionDashboardDisplayType.TableOnly-- if (!canEditInsight) {- return null- }-- return (- <LemonSelect- className="pb-2 px-2"- value={displayType}- onChange={(value) => {- updateInsightFilter({ dashboardDisplay: value })- }}- options={[- {- value: RetentionDashboardDisplayType.TableOnly,- label: 'Show table only',- },- {- value: RetentionDashboardDisplayType.GraphOnly,- label: 'Show graph only',- },- {- value: RetentionDashboardDisplayType.All,- label: 'Show both',- },- ]}- size="small"- fullWidth- />- )-}diff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle.tsxdeleted file mode 100644index 61db01df9244..000000000000--- a/products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle.tsx+++ /dev/null@@ -1,38 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonCheckbox } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { retentionGraphLogic } from '../retentionGraphLogic'--export function RetentionMeanLineToggle(): JSX.Element | null {- const { insightProps, canEditInsight } = useValues(insightLogic)- const { retentionFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))- const { hasValidBreakdown } = useValues(retentionGraphLogic(insightProps))-- if (!canEditInsight) {- return null- }-- const selectedInterval = retentionFilter?.selectedInterval ?? null- const disabledReason =- selectedInterval !== null- ? 'Mean line is not available when viewing a single interval.'- : hasValidBreakdown- ? 'Mean line is not available with a breakdown applied.'- : undefined-- return (- <LemonCheckbox- className="p-1 px-2"- checked={!disabledReason && !!retentionFilter?.showMeanLine}- onChange={(showMeanLine) => updateInsightFilter({ showMeanLine })}- disabledReason={disabledReason}- label={<span className="font-normal">Show mean line</span>}- size="small"- />- )-}diff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker.tsxdeleted file mode 100644index 89ffebc419df..000000000000--- a/products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker.tsx+++ /dev/null@@ -1,34 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonSegmentedButton } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--export function RetentionSeriesColorModePicker(): JSX.Element | null {- const { insightProps, canEditInsight } = useValues(insightLogic)- const { retentionFilter } = useValues(insightVizDataLogic(insightProps))- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))-- if (!canEditInsight) {- return null- }-- const chartStyle = retentionFilter?.chartStyle-- return (- <LemonSegmentedButton- className="pb-2 px-2"- value={chartStyle?.seriesColorMode || 'palette'}- onChange={(value) => {- updateInsightFilter({ chartStyle: { ...chartStyle, seriesColorMode: value } })- }}- options={[- { value: 'palette', label: 'One per cohort' },- { value: 'opacity', label: 'One shade' },- ]}- size="small"- fullWidth- />- )-}diff --git a/products/product_analytics/frontend/insights/trends/filters/ConfidenceLevelInput.tsx b/products/product_analytics/frontend/insights/trends/filters/ConfidenceLevelInput.tsxdeleted file mode 100644index 8bd6e05a1bf0..000000000000--- a/products/product_analytics/frontend/insights/trends/filters/ConfidenceLevelInput.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect, useState } from 'react'-import { useDebouncedCallback } from 'use-debounce'--import { LemonInput, Tooltip } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { isTrendsQuery } from '~/queries/schema/node-guards'--import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--export function ConfidenceLevelInput(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { confidenceLevel, showConfidenceIntervals } = useValues(trendsDataLogic(insightProps))- const { querySource } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))- const trendsFilter = isTrendsQuery(querySource) ? querySource.trendsFilter : undefined-- const [localValue, setLocalValue] = useState(confidenceLevel)-- useEffect(() => {- setLocalValue(confidenceLevel)- }, [confidenceLevel])-- const debouncedUpdate = useDebouncedCallback((value: number) => {- if (isTrendsQuery(querySource)) {- const newQuery = { ...querySource }- newQuery.trendsFilter = { ...trendsFilter, confidenceLevel: value }- updateQuerySource(newQuery)- }- }, 500)-- return (- <div className="flex items-center justify-between w-full px-2 pb-2 pl-4">- <Tooltip title="A 95% confidence level means that for each data point, we are 95% confident that the true value is within the confidence interval.">- <span>Confidence level</span>- </Tooltip>- <LemonInput- type="number"- className="w-20"- value={localValue}- onChange={(value) => {- const numValue = value ?? 95- setLocalValue(numValue)- debouncedUpdate(numValue)- }}- onBlur={() => debouncedUpdate.flush()}- min={0}- max={100}- step={1}- suffix={<span>%</span>}- disabledReason={- !showConfidenceIntervals ? 'Confidence intervals are only available for line graphs' : undefined- }- />- </div>- )-}diff --git a/products/product_analytics/frontend/insights/trends/filters/MovingAverageIntervalsInput.tsx b/products/product_analytics/frontend/insights/trends/filters/MovingAverageIntervalsInput.tsxdeleted file mode 100644index c6e02138299c..000000000000--- a/products/product_analytics/frontend/insights/trends/filters/MovingAverageIntervalsInput.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect, useState } from 'react'-import { useDebouncedCallback } from 'use-debounce'--import { LemonInput, Tooltip } from '@posthog/lemon-ui'--import { insightLogic } from 'scenes/insights/insightLogic'-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'--import { isTrendsQuery } from '~/queries/schema/node-guards'--import {- INTERVAL_TO_DEFAULT_MOVING_AVERAGE_PERIOD,- trendsDataLogic,-} from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'--export function MovingAverageIntervalsInput(): JSX.Element {- const { insightProps } = useValues(insightLogic)- const { movingAverageIntervals, showMovingAverage } = useValues(trendsDataLogic(insightProps))- const { querySource } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))- const trendsFilter = isTrendsQuery(querySource) ? querySource.trendsFilter : undefined-- const [localValue, setLocalValue] = useState(movingAverageIntervals)-- useEffect(() => {- setLocalValue(movingAverageIntervals)- }, [movingAverageIntervals])-- const debouncedUpdate = useDebouncedCallback((value: number) => {- if (isTrendsQuery(querySource)) {- const newQuery = { ...querySource }- newQuery.trendsFilter = { ...trendsFilter, movingAverageIntervals: value }- updateQuerySource(newQuery)- }- }, 500)-- const interval = isTrendsQuery(querySource) ? querySource.interval || 'day' : 'day'-- return (- <Tooltip title="The number of data points to use for calculating the moving average. A larger number will create a smoother line but with more lag. You can't use a number greater than the amount of intervals in your date range.">- <div className="flex items-center justify-between w-full px-2 pb-2 pl-4 gap-1">- <span>Intervals</span>-- <LemonInput- type="number"- className="w-30"- value={localValue}- onChange={(value) => {- const numValue = value ?? INTERVAL_TO_DEFAULT_MOVING_AVERAGE_PERIOD[interval]- setLocalValue(numValue)- debouncedUpdate(numValue)- }}- onBlur={() => debouncedUpdate.flush()}- min={2}- suffix={<span>{`${interval}s`}</span>}- step={1}- disabledReason={- !showMovingAverage ? 'Moving averages are only available for line and area graphs' : undefined- }- />- </div>- </Tooltip>- )-}