Skip to content

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

feat(dashboards): scope breakdown colors to their breakdown property (#74545)

Thomas Obermüllera06fcaf67b33
diff --git a/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx b/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx
index d85bdd1d2cb1..2c43f773d432 100644
--- a/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx
+++ b/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx
@@ -34,15 +34,7 @@ const CHOICE_HINTS: Record<TestAccountFilterChoice, string> = {
* breakdown color override.
*/
export function DashboardEditBarAdvancedFilters(): JSX.Element {
- const {
- dashboard,
- dashboardMode,
- placement,
- canEditDashboard,
- effectiveEditBarFilters,
- effectiveBreakdownColors,
- dataColorThemeId,
- } = useValues(dashboardLogic)
+ const { dashboard, dashboardMode, placement, canEditDashboard, effectiveEditBarFilters } = useValues(dashboardLogic)
const { setFilterTestAccounts, setDashboardMode } = useActions(dashboardLogic)
const { showInsightColorsModal } = useActions(dashboardInsightColorsModalLogic)
const { currentTeam } = useValues(teamLogic)
@@ -56,10 +48,9 @@ export function DashboardEditBarAdvancedFilters(): JSX.Element {
// Only the full dashboard scene mounts DashboardInsightColorsModal, so elsewhere the button would no-op.
const showColors =
hasDashboardColors && canEditDashboard && !!dashboard && placement === DashboardPlacement.Dashboard
- // Auto-assigned colors aren't an override — only pinned values and a picked theme are.
- const hasColorOverrides =
- effectiveBreakdownColors.some((config) => config.source !== 'auto') || dataColorThemeId != null
- const overrideCount = (choice === 'inherit' ? 0 : 1) + (showColors && hasColorOverrides ? 1 : 0)
+ // Color customizations don't count towards the badge: they are visible on the charts
+ // themselves, while a forced test account filter changes the data with no other visible cue.
+ const overrideCount = choice === 'inherit' ? 0 : 1
return (
<Popover
diff --git a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
index c9bbc9046f44..c9a0f75e183b 100644
--- a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
+++ b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
@@ -5,6 +5,7 @@ import { LemonButton, LemonColorPicker, LemonTable, LemonTableColumns } from '@p
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import stringWithWBR from 'lib/utils/stringWithWBR'
+import { BreakdownTag } from 'scenes/insights/filters/BreakdownFilter/BreakdownTag'
import { formatBreakdownLabel } from 'scenes/insights/utils'
import { dataColorThemesLogic } from 'scenes/settings/environment/dataColorThemesLogic'
@@ -13,17 +14,50 @@ import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { BreakdownFilter } from '~/queries/schema/schema-general'
import { DashboardMode } from '~/types'
-import { BreakdownColorConfig, denormalizeBreakdownValue, findBreakdownColorConfig } from './dashboardBreakdownColors'
+import {
+ BreakdownColorConfig,
+ BreakdownValueAndType,
+ COHORT_BREAKDOWN_PROPERTY_KEY,
+ denormalizeBreakdownValue,
+ findBreakdownColorConfig,
+ parseBreakdownPropertyKey,
+} from './dashboardBreakdownColors'
import { dashboardInsightColorsModalLogic } from './dashboardInsightColorsModalLogic'
import { dashboardLogic } from './dashboardLogic'
+type BreakdownColorRow = BreakdownColorConfig & { pinnedConfig?: BreakdownColorConfig }
+
+function BreakdownPropertyGroupTitle({ breakdownProperty }: { breakdownProperty?: string }): JSX.Element {
+ if (breakdownProperty == null) {
+ // The property-less group holds entries that apply under every property, like the funnel baseline.
+ return <LemonTag type="muted">All properties</LemonTag>
+ }
+ if (breakdownProperty === COHORT_BREAKDOWN_PROPERTY_KEY) {
+ return <LemonTag type="muted">Cohorts</LemonTag>
+ }
+ return (
+ <div className="flex flex-wrap items-center gap-1">
+ {parseBreakdownPropertyKey(breakdownProperty).map((part, index) => (
+ <BreakdownTag key={index} breakdown={part.property} breakdownType={part.type} size="small" />
+ ))}
+ </div>
+ )
+}
+
export function DashboardInsightColorsModal(): JSX.Element {
- const { isOpen, insightTilesLoading, breakdownValues } = useValues(dashboardInsightColorsModalLogic)
- const { hideInsightColorsModal } = useActions(dashboardInsightColorsModalLogic)
+ const { isOpen, insightTilesLoading, breakdownValueGroups } = useValues(dashboardInsightColorsModalLogic)
+ const { hideInsightColorsModal, cancelColorChanges } = useActions(dashboardInsightColorsModalLogic)
const { themes: _themes, themesLoading } = useValues(dataColorThemesLogic)
- const { effectiveBreakdownColors, dataColorThemeId, dashboardMode } = useValues(dashboardLogic)
+ const {
+ effectiveBreakdownColors,
+ dataColorThemeId,
+ dashboardMode,
+ dashboardLoading,
+ canEditDashboard,
+ hasUnsavedColorChanges,
+ } = useValues(dashboardLogic)
const { setBreakdownColorConfig, setDataColorThemeId, setDashboardMode } = useActions(dashboardLogic)
const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
@@ -37,12 +71,27 @@ export function DashboardInsightColorsModal(): JSX.Element {
}
}
- const columns: LemonTableColumns<BreakdownColorConfig> = [
+ const toRow = (breakdownValue: BreakdownValueAndType): BreakdownColorRow => {
+ const config = findBreakdownColorConfig(
+ effectiveBreakdownColors,
+ breakdownValue.breakdownValue,
+ breakdownValue.breakdownType,
+ breakdownValue.breakdownProperty
+ )
+ return {
+ ...breakdownValue,
+ colorToken: config?.colorToken || null,
+ source: config?.source,
+ pinnedConfig: config,
+ }
+ }
+
+ const columns: LemonTableColumns<BreakdownColorRow> = [
{
title: 'Breakdown',
key: 'breakdown_value',
- render: (_, { breakdownValue, ...config }) => {
- const breakdownFilter: BreakdownFilter = { breakdown_type: config.breakdownType }
+ render: (_, { breakdownValue, breakdownType }) => {
+ const breakdownFilter: BreakdownFilter = { breakdown_type: breakdownType }
const breakdownLabel = formatBreakdownLabel(
denormalizeBreakdownValue(breakdownValue),
breakdownFilter,
@@ -57,8 +106,7 @@ export function DashboardInsightColorsModal(): JSX.Element {
{
title: 'Color',
key: 'color',
- width: 400,
- render: (_, { colorToken, source, ...config }) => {
+ render: (_, { colorToken, source, pinnedConfig, ...config }) => {
return (
<div className="flex items-center gap-2">
<LemonColorPicker
@@ -87,8 +135,11 @@ export function DashboardInsightColorsModal(): JSX.Element {
tooltip="Reset to automatic color"
onClick={() => {
ensureEditMode()
+ // Clearing must target the entry that provides the pin: a
+ // property-less legacy pin cleared from a scoped row would
+ // otherwise survive and keep coloring other properties.
setBreakdownColorConfig({
- ...config,
+ ...(pinnedConfig ?? config),
colorToken: null,
source: 'manual',
})
@@ -104,7 +155,43 @@ export function DashboardInsightColorsModal(): JSX.Element {
]
return (
- <LemonModal title="Customize breakdown colors" isOpen={isOpen} onClose={hideInsightColorsModal}>
+ <LemonModal
+ title="Customize breakdown colors"
+ isOpen={isOpen}
+ onClose={hideInsightColorsModal}
+ maxWidth="42rem"
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ data-attr="dashboard-colors-cancel"
+ onClick={cancelColorChanges}
+ tooltip="Revert the changes made in this dialog"
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ data-attr="dashboard-colors-save"
+ onClick={() => {
+ hideInsightColorsModal()
+ setDashboardMode(null, DashboardEventSource.DashboardInsightColorsModal)
+ }}
+ disabledReason={
+ dashboardLoading
+ ? 'Wait for dashboard to finish loading'
+ : !canEditDashboard
+ ? 'Not privileged to edit this dashboard'
+ : !hasUnsavedColorChanges
+ ? 'No color changes to save'
+ : undefined
+ }
+ >
+ Save
+ </LemonButton>
+ </>
+ }
+ >
<LemonLabel info="Select a color theme for all insights on this dashboard. If a theme is selected, it will be applied to all series and breakdowns.">
Color theme
</LemonLabel>
@@ -120,27 +207,38 @@ export function DashboardInsightColorsModal(): JSX.Element {
options={themes.map((theme) => ({ value: theme.id, label: theme.name }))}
/>
- <LemonLabel className="mt-4">Breakdown colors</LemonLabel>
- <p className="text-muted-alt mb-4">
- Breakdown values get a consistent color across all insights on this dashboard. Pick a color to pin a
- value to it. <i>Note: This works for trend, funnel, and retention insights.</i>
- </p>
- <LemonTable
- columns={columns}
- dataSource={breakdownValues.map((breakdownValue) => {
- const config = findBreakdownColorConfig(
- effectiveBreakdownColors,
- breakdownValue.breakdownValue,
- breakdownValue.breakdownType
- )
- return {
- ...breakdownValue,
- colorToken: config?.colorToken || null,
- source: config?.source,
- }
- })}
- loading={insightTilesLoading || undefined}
- />
+ <LemonLabel
+ className="mt-4 mb-2"
+ info={
+ <>
+ <p className="mb-1">
+ Colors are grouped by breakdown property, so each property picks its colors on its own.
+ </p>
+ <ul className="list-disc pl-4 space-y-1">
+ <li>
+ A value shown on two or more insights gets one color across the dashboard, and keeps it
+ under every property it appears in, as far as the palette allows.
+ </li>
+ <li>Values on a single insight keep their own colors.</li>
+ <li>Pick a color to pin a value to it.</li>
+ </ul>
+ </>
+ }
+ >
+ Breakdown colors
+ </LemonLabel>
+ {breakdownValueGroups.length === 0 ? (
+ <LemonTable columns={columns} dataSource={[]} loading={insightTilesLoading || undefined} />
+ ) : (
+ breakdownValueGroups.map((group) => (
+ <div key={group.breakdownProperty ?? ''} className="mb-4">
+ <LemonLabel className="mb-1">
+ <BreakdownPropertyGroupTitle breakdownProperty={group.breakdownProperty} />
+ </LemonLabel>
+ <LemonTable columns={columns} dataSource={group.values.map(toRow)} showHeader={false} />
+ </div>
+ ))
+ )}
{insightTilesLoading ? (
<p className="text-muted-alt mt-2">Tiles are still loading. More breakdown values may appear.</p>
) : null}
diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts
index 2f51f58ace21..7feb008b6965 100644
--- a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts
@@ -3,10 +3,17 @@ import { AccessControlLevel, DashboardTile, FunnelVizType, InsightShortId, Query
import {
BreakdownColorConfig,
+ BreakdownValueAndType,
MULTI_BREAKDOWN_SEPARATOR,
- computeAutoBreakdownColors,
+ applyAutoBreakdownColors,
+ buildSharedBreakdownValueLookup,
+ computeTileFallbackTokens,
extractBreakdownValues,
+ extractBreakdownValuesByTile,
findBreakdownColorConfig,
+ getBreakdownPropertyKey,
+ groupBreakdownValuesByProperty,
+ hasUnresolvedBreakdownTiles,
mergeBreakdownColorConfigs,
} from './dashboardBreakdownColors'
@@ -40,18 +47,71 @@ describe('dashboardBreakdownColors', () => {
},
})
- const trendsTile = (result: any[]): DashboardTile<QueryBasedInsightModel> =>
+ const trendsTile = (result: any[], breakdownFilter?: Record<string, any>): DashboardTile<QueryBasedInsightModel> =>
createTestTile({
result,
query: {
kind: NodeKind.InsightVizNode,
- source: { kind: NodeKind.TrendsQuery },
+ source: { kind: NodeKind.TrendsQuery, ...(breakdownFilter ? { breakdownFilter } : {}) },
} as InsightVizNode<InsightQueryNode>,
})
+ describe('getBreakdownPropertyKey', () => {
+ it.each([
+ ['no filter', undefined, null],
+ ['a filter without a breakdown', { breakdown_type: 'event' }, null],
+ ['a single event breakdown', { breakdown: '$browser', breakdown_type: 'event' }, 'event::$browser'],
+ ['a single breakdown with the type defaulted', { breakdown: '$browser' }, 'event::$browser'],
+ [
+ 'a one-entry multi breakdown',
+ { breakdowns: [{ property: '$browser', type: 'event' }] },
+ 'event::$browser',
+ ],
+ [
+ 'a one-entry multi breakdown with the type defaulted',
+ { breakdowns: [{ property: '$browser' }] },
+ 'event::$browser',
+ ],
+ ['a person property', { breakdown: '$browser', breakdown_type: 'person' }, 'person::$browser'],
+ [
+ 'a group property, keyed by its group type index',
+ { breakdown: 'industry', breakdown_type: 'group', breakdown_group_type_index: 2 },
+ 'group:2:industry',
+ ],
+ [
+ 'a stale group type index on a non-group breakdown',
+ { breakdown: '$browser', breakdown_type: 'event', breakdown_group_type_index: 2 },
+ 'event::$browser',
+ ],
+ [
+ 'a cohort breakdown, regardless of its cohort ids',
+ { breakdown: [1, 2], breakdown_type: 'cohort' },
+ 'cohort',
+ ],
+ [
+ 'display options, which stay out of the key',
+ {
+ breakdown: '$current_url',
+ breakdown_type: 'event',
+ breakdown_normalize_url: true,
+ breakdown_histogram_bin_count: 10,
+ breakdown_limit: 25,
+ },
+ 'event::$current_url',
+ ],
+ [
+ 'a multi breakdown, joining parts in order',
+ { breakdowns: [{ property: '$browser' }, { property: '$os', type: 'person' }] },
+ `event::$browser${MULTI_BREAKDOWN_SEPARATOR}person::$os`,
+ ],
+ ] as const)('normalizes %s', (_name, breakdownFilter, expected) => {
+ expect(getBreakdownPropertyKey(breakdownFilter as any)).toEqual(expected)
+ })
+ })
+
describe('extractBreakdownValues', () => {
it('returns empty array for null input', () => {
- expect(extractBreakdownValues(null, null)).toEqual([])
+ expect(extractBreakdownValues(null)).toEqual([])
})
it('handles funnel insights with steps visualization', () => {
@@ -82,11 +142,13 @@ describe('dashboardBreakdownColors', () => {
}),
]
- expect(extractBreakdownValues(tiles, null)).toEqual([
+ // Baseline is on both tiles, so it outranks the single-tile values; Chrome and
+ // Safari tie on chart position and fall back to value order
+ expect(extractBreakdownValues(tiles)).toEqual([
{ breakdownValue: 'Baseline', breakdownType: 'event' },
{ breakdownValue: 'Chrome', breakdownType: 'event' },
- { breakdownValue: 'Firefox', breakdownType: 'event' },
{ breakdownValue: 'Safari', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
])
})
@@ -99,10 +161,27 @@ describe('dashboardBreakdownColors', () => {
trendsTile([{ action: { order: 0 }, breakdown_value: 'Safari' }]),
]
- expect(extractBreakdownValues(tiles, null)).toEqual([
+ expect(extractBreakdownValues(tiles)).toEqual([
{ breakdownValue: 'Chrome', breakdownType: 'event' },
- { breakdownValue: 'Firefox', breakdownType: 'event' },
{ breakdownValue: 'Safari', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
+ ])
+ })
+
+ it('orders values by assignment rank, most re-used first', () => {
+ const tiles = [
+ trendsTile([
+ { action: { order: 0 }, breakdown_value: ['Apple'] },
+ { action: { order: 0 }, breakdown_value: ['Zebra'] },
+ ]),
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Zebra'] }]),
+ ]
+
+ // Zebra is on two charts vs Apple's one, so the modal lists it first even
+ // though it trails the first chart and sorts later as a value
+ expect(extractBreakdownValues(tiles)).toEqual([
+ { breakdownValue: 'Zebra', breakdownType: 'event' },
+ { breakdownValue: 'Apple', breakdownType: 'event' },
])
})
@@ -118,7 +197,7 @@ describe('dashboardBreakdownColors', () => {
]),
]
- expect(extractBreakdownValues(tiles, null)).toEqual([
+ expect(extractBreakdownValues(tiles)).toEqual([
{ breakdownValue: 'Chrome', breakdownType: 'event' },
{ breakdownValue: 'Firefox', breakdownType: 'event' },
{ breakdownValue: 'Safari', breakdownType: 'event' },
@@ -138,7 +217,7 @@ describe('dashboardBreakdownColors', () => {
}),
]
- expect(extractBreakdownValues(tiles, null)).toEqual([
+ expect(extractBreakdownValues(tiles)).toEqual([
{ breakdownValue: '123', breakdownType: 'event' },
{ breakdownValue: 'Baseline', breakdownType: 'event' },
])
@@ -160,7 +239,7 @@ describe('dashboardBreakdownColors', () => {
}),
]
- expect(extractBreakdownValues(tiles, null)).toEqual([
+ expect(extractBreakdownValues(tiles)).toEqual([
{ breakdownValue: 'Chrome', breakdownType: 'event' },
{ breakdownValue: 'Firefox', breakdownType: 'event' },
])
@@ -189,10 +268,14 @@ describe('dashboardBreakdownColors', () => {
retentionTile([{ breakdown_value: 'Firefox' }]),
]
- expect(extractBreakdownValues(tiles, null)).toEqual([
- { breakdownValue: '$$_posthog_breakdown_other_$$', breakdownType: 'event' },
- { breakdownValue: 'Chrome', breakdownType: 'event' },
- { breakdownValue: 'Firefox', breakdownType: 'event' },
+ expect(extractBreakdownValues(tiles)).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ { breakdownValue: 'Firefox', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ {
+ breakdownValue: '$$_posthog_breakdown_other_$$',
+ breakdownType: 'event',
+ breakdownProperty: 'event::$browser',
+ },
])
})
@@ -231,10 +314,10 @@ describe('dashboardBreakdownColors', () => {
}),
],
])('ignores %s', (_name, tile) => {
- expect(extractBreakdownValues([tile], null)).toEqual([])
+ expect(extractBreakdownValues([tile])).toEqual([])
})
- it('handles cohort breakdowns', () => {
+ it('handles cohort breakdowns, keying them all to the shared cohort property', () => {
const cohortTile = (values: number[][]): DashboardTile<QueryBasedInsightModel> =>
createTestTile({
result: values.map((breakdown_value) => ({ action: { order: 0 }, breakdown_value })),
@@ -242,81 +325,300 @@ describe('dashboardBreakdownColors', () => {
kind: NodeKind.InsightVizNode,
source: {
kind: NodeKind.TrendsQuery,
- breakdownFilter: { breakdown_type: 'cohort' },
+ breakdownFilter: {
+ breakdown: values.flat(),
+ breakdown_type: 'cohort',
+ },
},
} as InsightVizNode<InsightQueryNode>,
})
- expect(extractBreakdownValues([cohortTile([[1], [2]]), cohortTile([[3]])], null)).toEqual([
- { breakdownValue: '1', breakdownType: 'cohort' },
- { breakdownValue: '2', breakdownType: 'cohort' },
- { breakdownValue: '3', breakdownType: 'cohort' },
+ // cohorts 1 and 3 lead their charts and tie, so value order decides; 2 trails its chart
+ expect(extractBreakdownValues([cohortTile([[1], [2]]), cohortTile([[3]])])).toEqual([
+ { breakdownValue: '1', breakdownType: 'cohort', breakdownProperty: 'cohort' },
+ { breakdownValue: '3', breakdownType: 'cohort', breakdownProperty: 'cohort' },
+ { breakdownValue: '2', breakdownType: 'cohort', breakdownProperty: 'cohort' },
+ ])
+ })
+
+ it('unifies single and multi form of one property into one scoped entry', () => {
+ const tiles = [
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Chrome'] }], {
+ breakdown: '$browser',
+ breakdown_type: 'event',
+ }),
+ trendsTile(
+ [
+ { action: { order: 0 }, breakdown_value: ['Chrome'] },
+ { action: { order: 0 }, breakdown_value: ['Firefox'] },
+ ],
+ { breakdowns: [{ property: '$browser' }] }
+ ),
+ ]
+
+ expect(extractBreakdownValues(tiles)).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ { breakdownValue: 'Firefox', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ ])
+ })
+
+ it('clusters values by property in tile order before ranking within each property', () => {
+ const tiles = [
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Mac OS X'] }], { breakdown: '$os' }),
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Mac OS X'] }], { breakdown: '$os' }),
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Chrome'] }], { breakdown: '$browser' }),
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Chrome'] }], { breakdown: '$browser' }),
+ trendsTile([{ action: { order: 0 }, breakdown_value: ['Chrome'] }], { breakdown: '$browser' }),
+ ]
+
+ // Chrome is on more tiles, but $os tiles come first on the dashboard
+ expect(extractBreakdownValues(tiles)).toEqual([
+ { breakdownValue: 'Mac OS X', breakdownType: 'event', breakdownProperty: 'event::$os' },
+ { breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ ])
+ })
+ })
+
+ describe('extractBreakdownValuesByTile', () => {
+ it('keeps values grouped by tile and deduplicates within a tile', () => {
+ const tiles = [
+ trendsTile([
+ { action: { order: 0 }, breakdown_value: ['Chrome'] },
+ // second series over the same breakdown repeats the value within the tile
+ { action: { order: 1 }, breakdown_value: ['Chrome'] },
+ { action: { order: 0 }, breakdown_value: ['Firefox'] },
+ ]),
+ trendsTile([{ action: { order: 0 }, breakdown_value: 'Chrome' }]),
+ trendsTile([]),
+ ]
+
+ expect(extractBreakdownValuesByTile(tiles)).toEqual([
+ [
+ { breakdownValue: 'Chrome', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
+ ],
+ [{ breakdownValue: 'Chrome', breakdownType: 'event' }],
+ ])
+ })
+
+ it('keeps the funnel baseline property-less while the funnel values are scoped', () => {
+ const tile = createTestTile({
+ result: [{ breakdown_value: ['Chrome'] }],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.FunnelsQuery,
+ funnelsFilter: { funnelVizType: FunnelVizType.Steps },
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ },
+ } as InsightVizNode<InsightQueryNode>,
+ })
+
+ // one baseline pin must keep covering every funnel tile, whatever it breaks down by
+ expect(extractBreakdownValuesByTile([tile])).toEqual([
+ [
+ { breakdownValue: 'Baseline', breakdownType: 'event' },
+ { breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ ],
])
})
})
- describe('computeAutoBreakdownColors', () => {
+ describe('groupBreakdownValuesByProperty', () => {
+ it('clusters values into property groups, with property-less values last', () => {
+ const baseline = { breakdownValue: 'Baseline', breakdownType: 'event' as const }
+ const macOs = {
+ breakdownValue: 'Mac OS X',
+ breakdownType: 'event' as const,
+ breakdownProperty: 'event::$os',
+ }
+ const chrome = {
+ breakdownValue: 'Chrome',
+ breakdownType: 'event' as const,
+ breakdownProperty: 'event::$browser',
+ }
+ const firefox = {
+ breakdownValue: 'Firefox',
+ breakdownType: 'event' as const,
+ breakdownProperty: 'event::$browser',
+ }
+
+ // extractBreakdownValues emits property-less rows first; the modal shows them
+ // as the closing section instead, after the property groups in dashboard order
+ expect(groupBreakdownValuesByProperty([baseline, macOs, chrome, firefox])).toEqual([
+ { breakdownProperty: 'event::$os', values: [macOs] },
+ { breakdownProperty: 'event::$browser', values: [chrome, firefox] },
+ { values: [baseline] },
+ ])
+ })
+ })
+
+ describe('hasUnresolvedBreakdownTiles', () => {
+ const breakdownFilter = { breakdown: '$browser', breakdown_type: 'event' }
+ const vizQuery = (source: Record<string, any>): InsightVizNode<InsightQueryNode> =>
+ ({ kind: NodeKind.InsightVizNode, source }) as InsightVizNode<InsightQueryNode>
+
+ it.each([
+ [
+ 'trends tile with a breakdown and no results',
+ createTestTile({ result: null, query: vizQuery({ kind: NodeKind.TrendsQuery, breakdownFilter }) }),
+ true,
+ ],
+ [
+ 'trends tile with a breakdown and empty results',
+ createTestTile({ result: [], query: vizQuery({ kind: NodeKind.TrendsQuery, breakdownFilter }) }),
+ false,
+ ],
+ [
+ 'trends tile without a breakdown and no results',
+ createTestTile({ result: null, query: vizQuery({ kind: NodeKind.TrendsQuery }) }),
+ false,
+ ],
+ [
+ 'funnel steps tile with a breakdown and no results',
+ createTestTile({
+ result: null,
+ query: vizQuery({
+ kind: NodeKind.FunnelsQuery,
+ funnelsFilter: { funnelVizType: FunnelVizType.Steps },
+ breakdownFilter,
+ }),
+ }),
+ true,
+ ],
+ [
+ 'time-to-convert funnel tile with a breakdown and no results',
+ createTestTile({
+ result: null,
+ query: vizQuery({
+ kind: NodeKind.FunnelsQuery,
+ funnelsFilter: { funnelVizType: FunnelVizType.TimeToConvert },
+ breakdownFilter,
+ }),
+ }),
+ false,
+ ],
+ [
+ 'retention tile with a breakdown and no results',
+ createTestTile({ result: null, query: vizQuery({ kind: NodeKind.RetentionQuery, breakdownFilter }) }),
+ true,
+ ],
+ [
+ 'non insight-viz tile with no results',
+ createTestTile({ result: null, query: { kind: NodeKind.DataTableNode } as any }),
+ false,
+ ],
+ ])('%s', (_name, tile, expected) => {
+ expect(hasUnresolvedBreakdownTiles([tile])).toBe(expected)
+ })
+ })
+
+ describe('applyAutoBreakdownColors', () => {
const value = (breakdownValue: string): { breakdownValue: string; breakdownType: 'event' } => ({
breakdownValue,
breakdownType: 'event',
})
+ // most cases want values shared by two tiles, since single-tile values are not assigned
+ const sharedTiles = (...breakdownValues: string[]): { breakdownValue: string; breakdownType: 'event' }[][] => [
+ breakdownValues.map(value),
+ breakdownValues.map(value),
+ ]
+ const autoConfig = (
+ breakdownValue: string,
+ colorToken: BreakdownColorConfig['colorToken']
+ ): BreakdownColorConfig => ({ breakdownValue, breakdownType: 'event', colorToken, source: 'auto' })
+
+ it('assigns only values that appear on two or more tiles', () => {
+ const result = applyAutoBreakdownColors([[value('Chrome'), value('Firefox')], [value('Chrome')]], [])
- it('fills free slots in sorted order without touching existing configs', () => {
+ // Firefox is unique to one tile, so it keeps position-based colors instead
+ expect(result).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
+ ])
+ })
+
+ it('fills free slots in chart order when re-use ties, appending after existing configs', () => {
const existing: BreakdownColorConfig[] = [
{ breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-3', source: 'manual' },
]
- const assigned = computeAutoBreakdownColors([value('Google'), value('Alibaba'), value('Chrome')], existing)
+ const result = applyAutoBreakdownColors(sharedTiles('Google', 'Alibaba', 'Chrome'), existing)
- expect(assigned).toEqual([
- { breakdownValue: 'Alibaba', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
- { breakdownValue: 'Google', breakdownType: 'event', colorToken: 'preset-2', source: 'auto' },
+ // both tiles list Google before Alibaba, so Google leads despite sorting later
+ expect(result).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-3', source: 'manual' },
+ { breakdownValue: 'Google', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
+ { breakdownValue: 'Alibaba', breakdownType: 'event', colorToken: 'preset-2', source: 'auto' },
])
- expect(existing[0].colorToken).toBe('preset-3')
+ })
+
+ it('gives the first slots to the values re-used across the most charts', () => {
+ const result = applyAutoBreakdownColors(
+ [[value('Apple'), value('Zebra')], [value('Apple'), value('Zebra')], [value('Zebra')]],
+ []
+ )
+
+ // Zebra is on three charts vs Apple's two, which outranks Apple leading the
+ // shared charts and sorting first as a value
+ expect(result).toEqual([autoConfig('Zebra', 'preset-1'), autoConfig('Apple', 'preset-2')])
+ })
+
+ it("breaks re-use ties by the values' ranking across their own charts", () => {
+ const result = applyAutoBreakdownColors(
+ [
+ [value('Apple'), value('Zebra')],
+ [value('Zebra'), value('Apple')],
+ [value('Zebra'), value('Apple')],
+ ],
+ []
+ )
+
+ // Zebra leads two of the three charts, so summed across charts it ranks ahead
+ // of Apple despite trailing on one chart and sorting first as a value
+ expect(result).toEqual([autoConfig('Zebra', 'preset-1'), autoConfig('Apple', 'preset-2')])
+ })
+
+ it('returns non-colliding configs unchanged, by reference, in their original order', () => {
+ const existing: BreakdownColorConfig[] = [
+ autoConfig('Google', 'preset-2'),
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-3', source: 'manual' },
+ autoConfig('Alibaba', 'preset-1'),
+ ]
+
+ const result = applyAutoBreakdownColors(sharedTiles('Google', 'Alibaba', 'Chrome'), existing)
+
+ // an unchanged dashboard must round-trip deep-equal, or every load looks like an edit to save
+ expect(result).toHaveLength(3)
+ result.forEach((config, index) => expect(config).toBe(existing[index]))
})
it('keeps covered values stable when a lexically-middle value appears', () => {
const persistedAuto: BreakdownColorConfig[] = [
- { breakdownValue: 'Alibaba', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
- { breakdownValue: 'Google', breakdownType: 'event', colorToken: 'preset-2', source: 'auto' },
+ autoConfig('Alibaba', 'preset-1'),
+ autoConfig('Google', 'preset-2'),
]
- const assigned = computeAutoBreakdownColors(
- [value('Alibaba'), value('Bing'), value('Google')],
- persistedAuto
- )
+ const result = applyAutoBreakdownColors(sharedTiles('Alibaba', 'Bing', 'Google'), persistedAuto)
// Bing sorts between the two covered values but only takes a free slot
- expect(assigned).toEqual([
- { breakdownValue: 'Bing', breakdownType: 'event', colorToken: 'preset-3', source: 'auto' },
- ])
+ expect(result).toEqual([...persistedAuto, autoConfig('Bing', 'preset-3')])
})
it('skips sentinel values', () => {
- const assigned = computeAutoBreakdownColors(
- [
- value('Baseline'),
- value('$$_posthog_breakdown_other_$$'),
- value('$$_posthog_breakdown_null_$$'),
- value('Chrome'),
- ],
+ const result = applyAutoBreakdownColors(
+ sharedTiles('Baseline', '$$_posthog_breakdown_other_$$', '$$_posthog_breakdown_null_$$', 'Chrome'),
[]
)
- expect(assigned).toEqual([
- { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
- ])
+ expect(result).toEqual([autoConfig('Chrome', 'preset-1')])
})
it('assigns a value again when its pin was cleared with a null token', () => {
- const assigned = computeAutoBreakdownColors(
- [value('Chrome')],
- [{ breakdownValue: 'Chrome', breakdownType: 'event', colorToken: null, source: 'manual' }]
- )
-
- expect(assigned).toEqual([
- { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
+ const result = applyAutoBreakdownColors(sharedTiles('Chrome'), [
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: null, source: 'manual' },
])
+
+ expect(result).toEqual([autoConfig('Chrome', 'preset-1')])
})
it('sizes slots to the given palette instead of the default 15 colors', () => {
@@ -324,32 +626,398 @@ describe('dashboardBreakdownColors', () => {
{ breakdownValue: 'Pinned', breakdownType: 'event', colorToken: 'preset-7', source: 'manual' },
]
- const assigned = computeAutoBreakdownColors(
- [value('A'), value('B'), value('C'), value('D'), value('E')],
- existing,
- 5
- )
+ const result = applyAutoBreakdownColors(sharedTiles('A', 'B', 'C', 'D', 'E'), existing, 5)
- // preset-7 renders as the second color of a five-color theme, so that slot is taken,
- // and the fifth value wraps at the palette size rather than taking preset-6
- expect(assigned.map((c) => c.colorToken)).toEqual([
+ // preset-7 renders as the second color of a five-color theme, so that slot is taken.
+ // E exhausts the palette, and since the pinned value is not on E's tiles, reusing the
+ // pin's slot is a cross-tile duplicate instead of a within-tile one.
+ expect(result.slice(1).map((c) => c.colorToken)).toEqual([
'preset-1',
'preset-3',
'preset-4',
'preset-5',
- 'preset-1',
+ 'preset-2',
+ ])
+ })
+
+ it('spreads within-tile duplicates evenly once every slot is on the tile', () => {
+ const breakdownValues = Array.from({ length: 17 }, (_, i) => `value-${String(i + 1).padStart(2, '0')}`)
+
+ const result = applyAutoBreakdownColors(sharedTiles(...breakdownValues), [])
+
+ expect(result).toHaveLength(17)
+ expect(result[14].colorToken).toBe('preset-15')
+ // values 16 and 17 must collide within the tile, but on the least-used slots
+ expect(result[15].colorToken).toBe('preset-1')
+ expect(result[16].colorToken).toBe('preset-2')
+ })
+
+ it('prefers a globally-used slot its own tiles do not show over a within-tile duplicate', () => {
+ const tiles = [...sharedTiles('A', 'B'), ...sharedTiles('Z')]
+
+ const result = applyAutoBreakdownColors(tiles, [], 2)
+
+ // A and Z both lead their charts, so they take the two slots and exhaust the
+ // palette; B's own tiles don't show Z's slot, so B reuses it rather than
+ // duplicating a color on its own charts
+ expect(result).toEqual([
+ autoConfig('A', 'preset-1'),
+ autoConfig('Z', 'preset-2'),
+ autoConfig('B', 'preset-2'),
])
})
- it('wraps deterministically once the palette is exhausted', () => {
- const values = Array.from({ length: 17 }, (_, i) => value(`value-${String(i + 1).padStart(2, '0')}`))
+ it('re-slots the lower-ranked persisted auto entry of a within-tile collision, in place', () => {
+ const existing: BreakdownColorConfig[] = [autoConfig('Bravo', 'preset-1'), autoConfig('Alpha', 'preset-1')]
- const assigned = computeAutoBreakdownColors(values, [])
+ const result = applyAutoBreakdownColors(sharedTiles('Alpha', 'Bravo'), existing)
- expect(assigned).toHaveLength(17)
- expect(assigned[14].colorToken).toBe('preset-15')
- expect(assigned[15].colorToken).toBe('preset-1')
- expect(assigned[16].colorToken).toBe('preset-2')
+ // both entries came out of the pre-collision-aware wrap; Alpha leads the charts and keeps the slot
+ expect(result).toEqual([autoConfig('Bravo', 'preset-2'), autoConfig('Alpha', 'preset-1')])
+ })
+
+ it('keeps the entry re-used across more charts when two persisted auto entries collide', () => {
+ const existing: BreakdownColorConfig[] = [autoConfig('Alpha', 'preset-1'), autoConfig('Zulu', 'preset-1')]
+
+ const result = applyAutoBreakdownColors(
+ [[value('Alpha'), value('Zulu')], [value('Alpha'), value('Zulu')], [value('Zulu')]],
+ existing
+ )
+
+ // Zulu is shared across more charts, so it keeps its color even though Alpha
+ // leads the shared charts and sorts first
+ expect(result).toEqual([autoConfig('Alpha', 'preset-2'), autoConfig('Zulu', 'preset-1')])
+ })
+
+ it('re-slots a persisted auto entry that collides with a manual pin', () => {
+ const existing: BreakdownColorConfig[] = [
+ autoConfig('Alpha', 'preset-3'),
+ { breakdownValue: 'Pinned', breakdownType: 'event', colorToken: 'preset-3', source: 'manual' },
+ ]
+
+ const result = applyAutoBreakdownColors(sharedTiles('Alpha', 'Pinned'), existing)
+
+ expect(result).toEqual([autoConfig('Alpha', 'preset-1'), existing[1]])
+ })
+
+ it('never moves manual pins, even when two of them collide on one tile', () => {
+ const pins: BreakdownColorConfig[] = [
+ { breakdownValue: 'One', breakdownType: 'event', colorToken: 'preset-5', source: 'manual' },
+ { breakdownValue: 'Two', breakdownType: 'event', colorToken: 'preset-5', source: 'manual' },
+ ]
+
+ const result = applyAutoBreakdownColors(sharedTiles('One', 'Two', 'Three'), pins)
+
+ expect(result).toEqual([...pins, autoConfig('Three', 'preset-1')])
+ })
+
+ const scopedValue = (breakdownValue: string, breakdownProperty: string): BreakdownValueAndType => ({
+ breakdownValue,
+ breakdownType: 'event',
+ breakdownProperty,
+ })
+ const scopedTiles = (breakdownProperty: string, ...breakdownValues: string[]): BreakdownValueAndType[][] => [
+ breakdownValues.map((v) => scopedValue(v, breakdownProperty)),
+ breakdownValues.map((v) => scopedValue(v, breakdownProperty)),
+ ]
+ const scopedAutoConfig = (
+ breakdownValue: string,
+ breakdownProperty: string,
+ colorToken: BreakdownColorConfig['colorToken']
+ ): BreakdownColorConfig => ({
+ breakdownValue,
+ breakdownType: 'event',
+ breakdownProperty,
+ colorToken,
+ source: 'auto',
+ })
+
+ it('starts each property over from the first palette slot', () => {
+ const result = applyAutoBreakdownColors(
+ [
+ ...scopedTiles('event::$browser', 'Chrome', 'Firefox'),
+ ...scopedTiles('event::$os', 'Mac OS X', 'Windows'),
+ ],
+ []
+ )
+
+ // properties are independent color worlds like standalone insights: their tiles
+ // never meet, so reusing slots across them is invisible and stretches the palette
+ expect(result).toEqual([
+ scopedAutoConfig('Chrome', 'event::$browser', 'preset-1'),
+ scopedAutoConfig('Mac OS X', 'event::$os', 'preset-1'),
+ scopedAutoConfig('Firefox', 'event::$browser', 'preset-2'),
+ scopedAutoConfig('Windows', 'event::$os', 'preset-2'),
+ ])
+ })
+
+ it('gives one value the same color under every property it appears under', () => {
+ const result = applyAutoBreakdownColors(
+ [...scopedTiles('event::is_admin', 'true'), ...scopedTiles('event::is_mobile', 'true')],
+ []
+ )
+
+ // "true" reads as one value wherever it shows up, so each property keeps its own
+ // entry, free to diverge via pinning, but both land on one color
+ expect(result).toEqual([
+ scopedAutoConfig('true', 'event::is_admin', 'preset-1'),
+ scopedAutoConfig('true', 'event::is_mobile', 'preset-1'),
+ ])
+ })
+
+ it('counts a value on single tiles of two different properties as shared', () => {
+ const result = applyAutoBreakdownColors(
+ [[scopedValue('true', 'event::is_admin')], [scopedValue('true', 'event::is_mobile')]],
+ []
+ )
+
+ // one tile each is a value the reader meets twice, and per-property counting is
+ // what used to leave it with no dashboard color and a position color that flips
+ expect(result).toEqual([
+ scopedAutoConfig('true', 'event::is_admin', 'preset-1'),
+ scopedAutoConfig('true', 'event::is_mobile', 'preset-1'),
+ ])
+ })
+
+ it('ranks a value by its charts across properties, so the wider one claims first', () => {
+ const result = applyAutoBreakdownColors(
+ [
+ [scopedValue('Chrome', 'event::$browser'), scopedValue('Firefox', 'event::$browser')],
+ [scopedValue('Chrome', 'event::$browser'), scopedValue('Firefox', 'event::$browser')],
+ [scopedValue('Firefox', 'event::browser_name')],
+ ],
+ []
+ )
+
+ // Firefox trails Chrome on both $browser charts, but it is on three charts against
+ // Chrome's two, so it claims the first slot and carries it into browser_name
+ expect(result).toEqual([
+ scopedAutoConfig('Firefox', 'event::$browser', 'preset-1'),
+ scopedAutoConfig('Firefox', 'event::browser_name', 'preset-1'),
+ scopedAutoConfig('Chrome', 'event::$browser', 'preset-2'),
+ ])
+ })
+
+ it('copies the color a value was pinned to under another property', () => {
+ const pin: BreakdownColorConfig = {
+ breakdownValue: 'Chrome',
+ breakdownType: 'event',
+ breakdownProperty: 'event::$browser',
+ colorToken: 'preset-6',
+ source: 'manual',
+ }
+
+ const result = applyAutoBreakdownColors(
+ [[scopedValue('Chrome', 'event::$browser')], [scopedValue('Chrome', 'event::browser_name')]],
+ [pin]
+ )
+
+ // pins claim before auto entries, so the pinned color is the one that spreads
+ // instead of the palette's first free slot
+ expect(result).toEqual([pin, scopedAutoConfig('Chrome', 'event::browser_name', 'preset-6')])
+ })
+
+ it('gives up copying a color when the slot is taken within the other property', () => {
+ const pin: BreakdownColorConfig = {
+ breakdownValue: 'Opera',
+ breakdownType: 'event',
+ breakdownProperty: 'event::browser_name',
+ colorToken: 'preset-1',
+ source: 'manual',
+ }
+
+ const result = applyAutoBreakdownColors(
+ [
+ [scopedValue('Chrome', 'event::$browser')],
+ [scopedValue('Chrome', 'event::browser_name'), scopedValue('Opera', 'event::browser_name')],
+ ],
+ [pin]
+ )
+
+ // Chrome takes the first slot under $browser, but Opera's pin holds it under
+ // browser_name, and sharing a chart with Opera is worse than a second color
+ expect(result).toEqual([
+ pin,
+ scopedAutoConfig('Chrome', 'event::$browser', 'preset-1'),
+ scopedAutoConfig('Chrome', 'event::browser_name', 'preset-2'),
+ ])
+ })
+
+ it('lets a property-less pin cover its value and claim its slot under every property', () => {
+ const pin: BreakdownColorConfig = {
+ breakdownValue: 'Chrome',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ source: 'manual',
+ }
+
+ const result = applyAutoBreakdownColors(
+ [
+ ...scopedTiles('event::$browser', 'Chrome', 'Firefox'),
+ ...scopedTiles('event::browser_name', 'Chrome', 'Opera'),
+ ],
+ [pin]
+ )
+
+ // the legacy pin matches Chrome under both properties, so neither property
+ // assigns Chrome again and both hand out slots around the pinned one
+ expect(result).toEqual([
+ pin,
+ scopedAutoConfig('Firefox', 'event::$browser', 'preset-2'),
+ scopedAutoConfig('Opera', 'event::browser_name', 'preset-2'),
+ ])
+ })
+
+ it('keeps a property-less auto entry covering its value, without a scoped duplicate', () => {
+ const legacy = autoConfig('Chrome', 'preset-2')
+
+ const result = applyAutoBreakdownColors(scopedTiles('event::$browser', 'Chrome'), [legacy])
+
+ // dashboards saved before property scoping keep their colors byte-for-byte
+ expect(result).toHaveLength(1)
+ expect(result[0]).toBe(legacy)
+ })
+
+ it('re-slots a displaced property-less auto entry off the slots its tiles already show', () => {
+ const existing: BreakdownColorConfig[] = [
+ scopedAutoConfig('Alpha', 'event::$browser', 'preset-1'),
+ autoConfig('Zulu', 'preset-1'),
+ ]
+
+ const result = applyAutoBreakdownColors(scopedTiles('event::$browser', 'Alpha', 'Zulu'), existing)
+
+ // the displaced legacy entry has no property of its own, but its tiles belong to
+ // $browser, whose used slots it must avoid to stay distinct on those charts
+ expect(result).toEqual([existing[0], autoConfig('Zulu', 'preset-2')])
+ })
+ })
+
+ describe('buildSharedBreakdownValueLookup', () => {
+ it('is true only for values appearing on two or more tiles', () => {
+ const isShared = buildSharedBreakdownValueLookup([
+ [
+ { breakdownValue: 'Chrome', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
+ ],
+ [{ breakdownValue: 'Chrome', breakdownType: 'event' }],
+ ])
+
+ expect(isShared({ breakdownValue: 'Chrome', breakdownType: 'event' })).toBe(true)
+ expect(isShared({ breakdownValue: 'Firefox', breakdownType: 'event' })).toBe(false)
+ expect(isShared({ breakdownValue: 'Chrome', breakdownType: 'person' })).toBe(false)
+ })
+
+ it('counts a value across the properties it appears under', () => {
+ const isShared = buildSharedBreakdownValueLookup([
+ [
+ { breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ { breakdownValue: 'true', breakdownType: 'event', breakdownProperty: 'event::$browser' },
+ ],
+ [{ breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' }],
+ [{ breakdownValue: 'true', breakdownType: 'event', breakdownProperty: 'event::is_admin' }],
+ ])
+
+ expect(
+ isShared({ breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::$browser' })
+ ).toBe(true)
+ // "true" is on one tile of each of two properties, which is still a value the
+ // reader meets twice, so both entries qualify and aim for one color
+ expect(
+ isShared({ breakdownValue: 'true', breakdownType: 'event', breakdownProperty: 'event::$browser' })
+ ).toBe(true)
+ expect(
+ isShared({ breakdownValue: 'true', breakdownType: 'event', breakdownProperty: 'event::is_admin' })
+ ).toBe(true)
+ // property-less legacy entries read the same count, wherever the value appears
+ expect(isShared({ breakdownValue: 'true', breakdownType: 'event' })).toBe(true)
+ expect(isShared({ breakdownValue: 'Chrome', breakdownType: 'event' })).toBe(true)
+ // a value on one tile only still keeps its insight's own colors
+ expect(
+ isShared({ breakdownValue: 'Chrome', breakdownType: 'event', breakdownProperty: 'event::is_admin' })
+ ).toBe(false)
+ })
+ })
+
+ describe('computeTileFallbackTokens', () => {
+ it('returns an empty map for a tile without overrides, keeping plain position colors', () => {
+ const tokens = computeTileFallbackTokens(
+ [
+ { position: 0, overrideToken: null },
+ { position: 1, overrideToken: null },
+ ],
+ 15
+ )
+
+ expect(tokens.size).toBe(0)
+ })
+
+ it('fills the slots the tile overrides do not use, in position order', () => {
+ const tokens = computeTileFallbackTokens(
+ [
+ { position: 0, overrideToken: null },
+ { position: 1, overrideToken: 'preset-1' },
+ { position: 2, overrideToken: null },
+ { position: 3, overrideToken: 'preset-4' },
+ { position: 4, overrideToken: null },
+ ],
+ 15
+ )
+
+ expect(tokens).toEqual(
+ new Map([
+ [0, 'preset-2'],
+ [2, 'preset-3'],
+ [4, 'preset-5'],
+ ])
+ )
+ })
+
+ it('assigns one slot per position when compare pairs repeat a position', () => {
+ const tokens = computeTileFallbackTokens(
+ [
+ { position: 0, overrideToken: null },
+ { position: 0, overrideToken: null },
+ { position: 1, overrideToken: 'preset-1' },
+ ],
+ 15
+ )
+
+ expect(tokens).toEqual(new Map([[0, 'preset-2']]))
+ })
+
+ it('cycles the free slots once exhausted instead of reusing an override slot', () => {
+ const tokens = computeTileFallbackTokens(
+ [
+ { position: 0, overrideToken: 'preset-1' },
+ { position: 1, overrideToken: null },
+ { position: 2, overrideToken: null },
+ { position: 3, overrideToken: null },
+ { position: 4, overrideToken: null },
+ ],
+ 3
+ )
+
+ expect(tokens).toEqual(
+ new Map([
+ [1, 'preset-2'],
+ [2, 'preset-3'],
+ [3, 'preset-2'],
+ [4, 'preset-3'],
+ ])
+ )
+ })
+
+ it('returns an empty map when overrides cover the whole palette', () => {
+ const tokens = computeTileFallbackTokens(
+ [
+ { position: 0, overrideToken: 'preset-1' },
+ { position: 1, overrideToken: 'preset-2' },
+ { position: 2, overrideToken: null },
+ ],
+ 2
+ )
+
+ expect(tokens.size).toBe(0)
})
})
@@ -376,6 +1044,31 @@ describe('dashboardBreakdownColors', () => {
expect(merged).toEqual([{ breakdownValue: '123', breakdownType: 'event', colorToken: 'preset-1' }])
})
+
+ it('keeps scoped and property-less entries for one value separate, deduplicating within each scope', () => {
+ const scopedPin: BreakdownColorConfig = {
+ breakdownValue: 'Chrome',
+ breakdownType: 'event',
+ breakdownProperty: 'event::$browser',
+ colorToken: 'preset-2',
+ source: 'manual',
+ }
+
+ const merged = mergeBreakdownColorConfigs(
+ [scopedPin],
+ [
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1' },
+ { ...scopedPin, colorToken: 'preset-3' },
+ ]
+ )
+
+ // the scoped pin shadows its persisted version but not the legacy one, which
+ // still colors Chrome under other properties
+ expect(merged).toEqual([
+ scopedPin,
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1' },
+ ])
+ })
})
describe('findBreakdownColorConfig', () => {
@@ -411,5 +1104,27 @@ describe('dashboardBreakdownColors', () => {
expect(findBreakdownColorConfig(configs, undefined, 'event')).toBeUndefined()
expect(findBreakdownColorConfig(configs, null, 'event')).toBeUndefined()
})
+
+ it('prefers a property-scoped entry and falls back to a property-less one', () => {
+ const scopedConfigs: BreakdownColorConfig[] = [
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1' },
+ {
+ breakdownValue: 'Chrome',
+ breakdownType: 'event',
+ breakdownProperty: 'event::$browser',
+ colorToken: 'preset-2',
+ },
+ ]
+
+ // the scoped entry wins for its own property even though the legacy one is listed first
+ expect(findBreakdownColorConfig(scopedConfigs, 'Chrome', 'event', 'event::$browser')?.colorToken).toBe(
+ 'preset-2'
+ )
+ // under any other property, and without property context, the legacy entry applies
+ expect(findBreakdownColorConfig(scopedConfigs, 'Chrome', 'event', 'event::browser_name')?.colorToken).toBe(
+ 'preset-1'
+ )
+ expect(findBreakdownColorConfig(scopedConfigs, 'Chrome', 'event')?.colorToken).toBe('preset-1')
+ })
})
})
diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
index f49b3b895cbd..7785797c1a37 100644
--- a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
@@ -1,15 +1,9 @@
import { DataColorToken, dataColorVars } from 'lib/colors'
-import {
- getFunnelDatasetKey,
- getTrendDatasetKey,
- isNullBreakdown,
- isOtherBreakdown,
- sortCohorts,
-} from 'scenes/insights/utils'
+import { getFunnelDatasetKey, getTrendDatasetKey, isNullBreakdown, isOtherBreakdown } from 'scenes/insights/utils'
import { BreakdownFilter } from '~/queries/schema/schema-general'
import { hasBreakdownFilter, isFunnelsQuery, isInsightVizNode, isRetentionQuery, isTrendsQuery } from '~/queries/utils'
-import { CohortType, DashboardTile, FunnelVizType, QueryBasedInsightModel } from '~/types'
+import { DashboardTile, FunnelVizType, QueryBasedInsightModel } from '~/types'
export type BreakdownColorSource = 'auto' | 'manual'
@@ -17,11 +11,15 @@ export type BreakdownColorConfig = {
colorToken: DataColorToken | null
breakdownValue: string
breakdownType: BreakdownFilter['breakdown_type']
+ /** Normalized breakdown property the value belongs to (see getBreakdownPropertyKey).
+ * Scopes the color to tiles breaking down by that property. Entries without one predate
+ * property scoping and match their value under any property. */
+ breakdownProperty?: string
/** Entries without a source predate auto-assignment and are treated as manual pins. */
source?: BreakdownColorSource
}
-export type BreakdownValueAndType = Pick<BreakdownColorConfig, 'breakdownValue' | 'breakdownType'>
+export type BreakdownValueAndType = Pick<BreakdownColorConfig, 'breakdownValue' | 'breakdownType' | 'breakdownProperty'>
/** Label of the synthetic baseline row funnel insights contribute to the colors table. */
export const FUNNEL_BASELINE_BREAKDOWN_LABEL = 'Baseline'
@@ -31,6 +29,11 @@ export const FUNNEL_BASELINE_BREAKDOWN_LABEL = 'Baseline'
* value like "a::b" (the display separator, which does occur in real property values). */
export const MULTI_BREAKDOWN_SEPARATOR = '\u001f'
+/** Property key of every cohort breakdown. Cohort ids identify globally rather than per
+ * property, so all cohort breakdowns form one color group, matching their pre-scoping
+ * behavior of one identity per cohort id. */
+export const COHORT_BREAKDOWN_PROPERTY_KEY = 'cohort'
+
/** Breakdown values arrive as string | number | boolean | array depending on insight type and
* persistence round-trips, while configs compare with strict equality. One canonical string form
* keeps a value matching its config across tiles, insight types, and saves. */
@@ -46,32 +49,121 @@ export function denormalizeBreakdownValue(value: string): string | string[] {
return value.includes(MULTI_BREAKDOWN_SEPARATOR) ? value.split(MULTI_BREAKDOWN_SEPARATOR) : value
}
+// The group type index only means something for group breakdowns; other types can carry a
+// stale one, which must not split a property into two groups.
+function breakdownPropertyPart(
+ type: string,
+ groupTypeIndex: number | null | undefined,
+ property: string | number
+): string {
+ return `${type}:${type === 'group' ? (groupTypeIndex ?? '') : ''}:${property}`
+}
+
+/** Normalized identity of what a query breaks down by: type, group index, and property of
+ * each part, multi parts joined in order. A single breakdown and a one-entry multi breakdown
+ * of the same property produce the same key, so their values share colors. Display options
+ * (URL normalization, histogram bins, limits) stay out of the key because they change how
+ * values render, not which property they come from. Returns null without a breakdown. */
+export function getBreakdownPropertyKey(breakdownFilter: BreakdownFilter | null | undefined): string | null {
+ if (breakdownFilter?.breakdowns?.length) {
+ return breakdownFilter.breakdowns
+ .map((breakdown) =>
+ breakdownPropertyPart(breakdown.type ?? 'event', breakdown.group_type_index, breakdown.property)
+ )
+ .join(MULTI_BREAKDOWN_SEPARATOR)
+ }
+ if (breakdownFilter?.breakdown == null) {
+ return null
+ }
+ const breakdownType = breakdownFilter.breakdown_type ?? 'event'
+ if (breakdownType === 'cohort') {
+ return COHORT_BREAKDOWN_PROPERTY_KEY
+ }
+ return breakdownPropertyPart(
+ breakdownType,
+ breakdownFilter.breakdown_group_type_index,
+ Array.isArray(breakdownFilter.breakdown)
+ ? breakdownFilter.breakdown.join(MULTI_BREAKDOWN_SEPARATOR)
+ : breakdownFilter.breakdown
+ )
+}
+
+export type BreakdownPropertyKeyPart = {
+ type: BreakdownFilter['breakdown_type']
+ property: string
+}
+
+/** Type and property name of a key's parts, for display. Not meaningful for the cohort key. */
+export function parseBreakdownPropertyKey(key: string): BreakdownPropertyKeyPart[] {
+ // The first two colon-separated fields are type and group index; the property itself may
+ // contain colons, so everything past the second one belongs to it.
+ return key.split(MULTI_BREAKDOWN_SEPARATOR).map((part) => {
+ const fields = part.split(':')
+ return { type: fields[0] as BreakdownFilter['breakdown_type'], property: fields.slice(2).join(':') }
+ })
+}
+
export function breakdownConfigMatches(
config: BreakdownValueAndType,
breakdownValue: unknown,
- breakdownType: BreakdownFilter['breakdown_type'] | null | undefined
+ breakdownType: BreakdownFilter['breakdown_type'] | null | undefined,
+ breakdownPropertyKey?: string | null
): boolean {
const normalized = normalizeBreakdownValue(breakdownValue)
+ if (normalized == null || normalizeBreakdownValue(config.breakdownValue) !== normalized) {
+ return false
+ }
+ // A property key already encodes each part's type, so scoped entries match on it alone;
+ // property-less entries keep the legacy value-and-type match under any property.
+ return config.breakdownProperty != null
+ ? config.breakdownProperty === breakdownPropertyKey
+ : config.breakdownType === (breakdownType ?? 'event')
+}
+
+/** True when two configs denote the same entry: same normalized value, type, and property
+ * scope. Unlike breakdownConfigMatches, a property-less entry only equals another
+ * property-less one, so scoped and legacy entries for one value can coexist. */
+export function breakdownConfigIdentityMatches(a: BreakdownValueAndType, b: BreakdownValueAndType): boolean {
return (
- normalized != null &&
- normalizeBreakdownValue(config.breakdownValue) === normalized &&
- config.breakdownType === (breakdownType ?? 'event')
+ normalizeBreakdownValue(a.breakdownValue) === normalizeBreakdownValue(b.breakdownValue) &&
+ (a.breakdownType ?? 'event') === (b.breakdownType ?? 'event') &&
+ (a.breakdownProperty ?? null) === (b.breakdownProperty ?? null)
)
}
export function findBreakdownColorConfig(
configs: BreakdownColorConfig[] | undefined | null,
breakdownValue: unknown,
- breakdownType: BreakdownFilter['breakdown_type'] | null | undefined
+ breakdownType: BreakdownFilter['breakdown_type'] | null | undefined,
+ breakdownPropertyKey?: string | null
): BreakdownColorConfig | undefined {
if (normalizeBreakdownValue(breakdownValue) == null) {
return undefined
}
- return configs?.find((config) => breakdownConfigMatches(config, breakdownValue, breakdownType))
+ // A property-scoped entry beats a property-less one, which acts as a fallback pin
+ // across all properties.
+ const scoped =
+ breakdownPropertyKey != null
+ ? configs?.find(
+ (config) =>
+ config.breakdownProperty != null &&
+ breakdownConfigMatches(config, breakdownValue, breakdownType, breakdownPropertyKey)
+ )
+ : undefined
+ return (
+ scoped ??
+ configs?.find(
+ (config) =>
+ config.breakdownProperty == null &&
+ breakdownConfigMatches(config, breakdownValue, breakdownType, breakdownPropertyKey)
+ )
+ )
}
-/** Merge configs by (breakdownValue, breakdownType), earlier lists winning over later ones.
- * Values are normalized on the way out, migrating legacy non-string entries on the next save. */
+/** Merge configs by (breakdownValue, breakdownType, breakdownProperty), earlier lists winning
+ * over later ones. Scoped and property-less entries for the same value stay separate, so a
+ * scoped pin can shadow a legacy one per property without erasing it elsewhere. Values are
+ * normalized on the way out, migrating legacy non-string entries on the next save. */
export function mergeBreakdownColorConfigs(...configLists: BreakdownColorConfig[][]): BreakdownColorConfig[] {
const merged: BreakdownColorConfig[] = []
for (const configs of configLists) {
@@ -80,7 +172,7 @@ export function mergeBreakdownColorConfigs(...configLists: BreakdownColorConfig[
if (breakdownValue == null) {
continue
}
- if (!merged.some((c) => breakdownConfigMatches(c, breakdownValue, config.breakdownType))) {
+ if (!merged.some((c) => breakdownConfigIdentityMatches(c, config))) {
merged.push({ ...config, breakdownValue })
}
}
@@ -88,66 +180,79 @@ export function mergeBreakdownColorConfigs(...configLists: BreakdownColorConfig[
return merged
}
-export function extractBreakdownValues(
- insightTiles: DashboardTile<QueryBasedInsightModel>[] | null,
- cohorts: CohortType[] | null
-): BreakdownValueAndType[] {
- if (insightTiles == null) {
+// Time-to-convert renders a single-color histogram, so it has nothing to contribute.
+function funnelVizRendersBreakdownSeries(funnelVizType: FunnelVizType | undefined): boolean {
+ return (
+ funnelVizType === undefined || funnelVizType === FunnelVizType.Steps || funnelVizType === FunnelVizType.Trends
+ )
+}
+
+function makeBreakdownValue(
+ breakdownValue: string,
+ breakdownType: BreakdownFilter['breakdown_type'],
+ breakdownPropertyKey: string | null
+): BreakdownValueAndType {
+ return breakdownPropertyKey == null
+ ? { breakdownValue, breakdownType }
+ : { breakdownValue, breakdownType, breakdownProperty: breakdownPropertyKey }
+}
+
+function extractTileBreakdownValues(tile: DashboardTile<QueryBasedInsightModel>): BreakdownValueAndType[] {
+ if (!isInsightVizNode(tile.insight?.query)) {
return []
}
- return insightTiles
- .flatMap((tile) => {
- if (isInsightVizNode(tile.insight?.query)) {
- const querySource = tile.insight?.query.source
- if (isFunnelsQuery(querySource)) {
- const funnelVizType = querySource.funnelsFilter?.funnelVizType
- const isStepsViz = funnelVizType === undefined || funnelVizType === FunnelVizType.Steps
- // Time-to-convert renders a single-color histogram, so it has nothing to contribute.
- if (!isStepsViz && funnelVizType !== FunnelVizType.Trends) {
- return []
- }
- const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
- // Only the steps visualization renders a baseline series.
- const breakdownValues: (BreakdownValueAndType | null)[] = isStepsViz
- ? [
- {
- breakdownValue: FUNNEL_BASELINE_BREAKDOWN_LABEL,
- breakdownType,
- },
- ]
- : []
- tile.insight?.result?.forEach((result: any) => {
- const key = getFunnelDatasetKey(result)
- const breakdownValue = normalizeBreakdownValue(JSON.parse(key)['breakdown_value'])
- breakdownValues.push(breakdownValue == null ? null : { breakdownValue, breakdownType })
- })
- return breakdownValues
- } else if (isTrendsQuery(querySource)) {
- const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
- return (
- tile.insight?.result?.map((result: any): BreakdownValueAndType | null => {
- const key = getTrendDatasetKey(result)
- const breakdownValue = normalizeBreakdownValue(JSON.parse(key)['breakdown_value'])
- return breakdownValue == null ? null : { breakdownValue, breakdownType }
- }) || []
- )
- } else if (isRetentionQuery(querySource) && hasBreakdownFilter(querySource.breakdownFilter)) {
- const breakdownType = querySource.breakdownFilter.breakdown_type || 'event'
- // Retention results carry breakdown_value directly. There is no dataset-key helper
- // like trends/funnels have, because retention has no resultCustomizations whose
- // persisted keys the extraction would need to stay in sync with.
- return (
- tile.insight?.result?.map((result: any): BreakdownValueAndType | null => {
- const breakdownValue = normalizeBreakdownValue(result.breakdown_value)
- return breakdownValue == null ? null : { breakdownValue, breakdownType }
- }) || []
- )
- }
- return []
- }
+ const querySource = tile.insight?.query.source
+ let breakdownValues: (BreakdownValueAndType | null)[] = []
+ if (isFunnelsQuery(querySource)) {
+ const funnelVizType = querySource.funnelsFilter?.funnelVizType
+ if (!funnelVizRendersBreakdownSeries(funnelVizType)) {
return []
+ }
+ const isStepsViz = funnelVizType === undefined || funnelVizType === FunnelVizType.Steps
+ const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
+ const propertyKey = getBreakdownPropertyKey(querySource.breakdownFilter)
+ // Only the steps visualization renders a baseline series. The baseline is a funnel
+ // sentinel rather than a value of the breakdown property, so it stays property-less
+ // and one pin covers it on every funnel tile.
+ breakdownValues = isStepsViz
+ ? [
+ {
+ breakdownValue: FUNNEL_BASELINE_BREAKDOWN_LABEL,
+ breakdownType,
+ },
+ ]
+ : []
+ tile.insight?.result?.forEach((result: any) => {
+ const key = getFunnelDatasetKey(result)
+ const breakdownValue = normalizeBreakdownValue(JSON.parse(key)['breakdown_value'])
+ breakdownValues.push(
+ breakdownValue == null ? null : makeBreakdownValue(breakdownValue, breakdownType, propertyKey)
+ )
})
+ } else if (isTrendsQuery(querySource)) {
+ const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
+ const propertyKey = getBreakdownPropertyKey(querySource.breakdownFilter)
+ breakdownValues =
+ tile.insight?.result?.map((result: any): BreakdownValueAndType | null => {
+ const key = getTrendDatasetKey(result)
+ const breakdownValue = normalizeBreakdownValue(JSON.parse(key)['breakdown_value'])
+ return breakdownValue == null ? null : makeBreakdownValue(breakdownValue, breakdownType, propertyKey)
+ }) || []
+ } else if (isRetentionQuery(querySource) && hasBreakdownFilter(querySource.breakdownFilter)) {
+ const breakdownType = querySource.breakdownFilter.breakdown_type || 'event'
+ const propertyKey = getBreakdownPropertyKey(querySource.breakdownFilter)
+ // Retention results carry breakdown_value directly. There is no dataset-key helper
+ // like trends/funnels have, because retention has no resultCustomizations whose
+ // persisted keys the extraction would need to stay in sync with.
+ breakdownValues =
+ tile.insight?.result?.map((result: any): BreakdownValueAndType | null => {
+ const breakdownValue = normalizeBreakdownValue(result.breakdown_value)
+ return breakdownValue == null ? null : makeBreakdownValue(breakdownValue, breakdownType, propertyKey)
+ }) || []
+ }
+
+ return breakdownValues
.filter((value): value is BreakdownValueAndType => value != null)
.reduce<BreakdownValueAndType[]>((acc, curr) => {
if (!acc.some((x) => x.breakdownValue === curr.breakdownValue && x.breakdownType === curr.breakdownType)) {
@@ -155,18 +260,96 @@ export function extractBreakdownValues(
}
return acc
}, [])
- .sort((a, b) => {
- if (a.breakdownType === 'cohort' && b.breakdownType === 'cohort') {
- return sortCohorts(a.breakdownValue, b.breakdownValue, cohorts)
- }
+}
- // put cohorts at the end
- if (a.breakdownType === 'cohort' || b.breakdownType === 'cohort') {
- return a.breakdownType === 'cohort' ? 1 : -1
+/** Breakdown values per tile, deduplicated within each tile; tiles without values are dropped.
+ * Tile identity matters for assignment: which values co-occur on one chart decides which
+ * colors may collide, and how many tiles share a value decides whether it gets one at all. */
+export function extractBreakdownValuesByTile(
+ insightTiles: DashboardTile<QueryBasedInsightModel>[] | null
+): BreakdownValueAndType[][] {
+ if (insightTiles == null) {
+ return []
+ }
+ return insightTiles.map(extractTileBreakdownValues).filter((values) => values.length > 0)
+}
+
+/** True when any tile's query would contribute breakdown values once loaded, but its results are
+ * unavailable (a refresh errored or was aborted before the insight ever got results). Such a
+ * tile's breakdown values are unknown rather than absent, so tile counts under-report sharing:
+ * pruning or persisting auto colors in this state would drop entries that are still valid. */
+export function hasUnresolvedBreakdownTiles(insightTiles: DashboardTile<QueryBasedInsightModel>[] | null): boolean {
+ return (insightTiles ?? []).some((tile) => {
+ if (tile.insight?.result != null || !isInsightVizNode(tile.insight?.query)) {
+ return false
+ }
+ const querySource = tile.insight?.query.source
+ if (isFunnelsQuery(querySource)) {
+ return (
+ funnelVizRendersBreakdownSeries(querySource.funnelsFilter?.funnelVizType) &&
+ hasBreakdownFilter(querySource.breakdownFilter)
+ )
+ }
+ if (isTrendsQuery(querySource) || isRetentionQuery(querySource)) {
+ return hasBreakdownFilter(querySource.breakdownFilter)
+ }
+ return false
+ })
+}
+
+/** Deduplicated breakdown values across all tiles, clustered by breakdown property in the
+ * order properties first appear on the dashboard, then ordered within each property the way
+ * auto-assignment ranks them, so the colors modal lists values the way colors are handed out. */
+export function extractBreakdownValues(
+ insightTiles: DashboardTile<QueryBasedInsightModel>[] | null
+): BreakdownValueAndType[] {
+ const tileBreakdownValues = extractBreakdownValuesByTile(insightTiles)
+ const stats = collectValueTileStats(tileBreakdownValues)
+ const compareAssignmentRank = buildAssignmentRankComparator(stats)
+ const propertyOrder = new Map<string | null, number>()
+ stats.tileProperties.forEach((property, tileIndex) => {
+ if (!propertyOrder.has(property)) {
+ propertyOrder.set(property, tileIndex)
+ }
+ })
+ return tileBreakdownValues
+ .flat()
+ .reduce<BreakdownValueAndType[]>((acc, curr) => {
+ if (!acc.some((x) => breakdownConfigIdentityMatches(x, curr))) {
+ acc.push(curr)
}
+ return acc
+ }, [])
+ .sort(
+ (a, b) =>
+ // Property-less rows (like the funnel baseline) sort ahead of the clusters.
+ (propertyOrder.get(a.breakdownProperty ?? null) ?? -1) -
+ (propertyOrder.get(b.breakdownProperty ?? null) ?? -1) || compareAssignmentRank(a, b)
+ )
+}
- return String(a.breakdownValue).localeCompare(String(b.breakdownValue))
- })
+export type BreakdownValueGroup = { breakdownProperty?: string; values: BreakdownValueAndType[] }
+
+/** Cluster an extractBreakdownValues list into per-property groups, keeping the list's order
+ * within and across groups. The property-less group (the funnel baseline, legacy values)
+ * moves to the end: its entries span every property, so it reads as an appendix to the
+ * property sections rather than the first one. */
+export function groupBreakdownValuesByProperty(values: BreakdownValueAndType[]): BreakdownValueGroup[] {
+ const grouped = new Map<string | null, BreakdownValueAndType[]>()
+ for (const value of values) {
+ const key = value.breakdownProperty ?? null
+ const group = grouped.get(key)
+ if (group) {
+ group.push(value)
+ } else {
+ grouped.set(key, [value])
+ }
+ }
+ const groups = [...grouped.entries()].map(
+ ([breakdownProperty, groupValues]): BreakdownValueGroup =>
+ breakdownProperty == null ? { values: groupValues } : { breakdownProperty, values: groupValues }
+ )
+ return [...groups.filter((g) => g.breakdownProperty != null), ...groups.filter((g) => g.breakdownProperty == null)]
}
/** Sentinel rows keep their built-in muted/fixed treatment instead of an assigned palette color. */
@@ -180,54 +363,344 @@ export function isAutoAssignableBreakdownValue(breakdownValue: string): boolean
const PRESET_TOKEN_REGEX = /^preset-(\d+)$/
-/** Assign palette slots to breakdown values that no existing config covers.
+function presetTokenToSlot(colorToken: DataColorToken | null | undefined, paletteSize: number): number | null {
+ const match = colorToken?.match(PRESET_TOKEN_REGEX)
+ return match ? (Number(match[1]) - 1) % paletteSize : null
+}
+
+function slotToPresetToken(slot: number): DataColorToken {
+ return `preset-${slot + 1}` as DataColorToken
+}
+
+// code-unit comparison, not localeCompare — assignment order must not depend on the client locale
+function compareAssignmentOrder(a: BreakdownValueAndType, b: BreakdownValueAndType): number {
+ const propertyA = a.breakdownProperty ?? ''
+ const propertyB = b.breakdownProperty ?? ''
+ return (
+ (a.breakdownType ?? 'event').localeCompare(b.breakdownType ?? 'event') ||
+ (propertyA < propertyB ? -1 : propertyA > propertyB ? 1 : 0) ||
+ (a.breakdownValue < b.breakdownValue ? -1 : a.breakdownValue > b.breakdownValue ? 1 : 0)
+ )
+}
+
+// NUL separators keep the fields from colliding: normalized values can't contain NUL, and
+// property keys join their parts with \u001f.
+function breakdownIdentityKey(value: BreakdownValueAndType): string {
+ return `${value.breakdownProperty ?? ''}\u0000${value.breakdownType ?? 'event'}\u0000${value.breakdownValue}`
+}
+
+function breakdownValueKey(value: BreakdownValueAndType): string {
+ return `${value.breakdownType ?? 'event'}\u0000${value.breakdownValue}`
+}
+
+type TileStats = { tiles: number[]; positionSum: number }
+
+type ValueTileStats = {
+ /** Keyed by property, type, and value: the unit colors are assigned to. */
+ byIdentity: Map<string, TileStats & { value: BreakdownValueAndType }>
+ /** Keyed by type and value across all properties. Decides sharing and rank for every
+ * value, so a value re-used under different properties counts as re-used, and covers
+ * property-less legacy configs, which match their value wherever it appears. */
+ byValue: Map<string, TileStats>
+ /** Property key of each tile, for per-property slot bookkeeping. */
+ tileProperties: (string | null)[]
+}
+
+function collectValueTileStats(tileBreakdownValues: BreakdownValueAndType[][]): ValueTileStats {
+ const byIdentity: ValueTileStats['byIdentity'] = new Map()
+ const byValue: ValueTileStats['byValue'] = new Map()
+ const tileProperties: (string | null)[] = []
+ tileBreakdownValues.forEach((values, tileIndex) => {
+ // All real values of a tile share the tile's breakdown property; only sentinel rows
+ // (the funnel baseline) are property-less.
+ tileProperties.push(values.find((value) => value.breakdownProperty != null)?.breakdownProperty ?? null)
+ values.forEach((value, position) => {
+ const identityEntry = byIdentity.get(breakdownIdentityKey(value))
+ if (identityEntry) {
+ identityEntry.tiles.push(tileIndex)
+ identityEntry.positionSum += position
+ } else {
+ byIdentity.set(breakdownIdentityKey(value), { value, tiles: [tileIndex], positionSum: position })
+ }
+ const valueEntry = byValue.get(breakdownValueKey(value))
+ if (valueEntry) {
+ valueEntry.tiles.push(tileIndex)
+ valueEntry.positionSum += position
+ } else {
+ byValue.set(breakdownValueKey(value), { tiles: [tileIndex], positionSum: position })
+ }
+ })
+ })
+ return { byIdentity, byValue, tileProperties }
+}
+
+// Which tiles an entry shows on, for collision checks: the tiles of its own scope. A scoped
+// entry only colors its property's tiles, while a property-less one colors the value everywhere.
+function statsOf(stats: ValueTileStats, value: BreakdownValueAndType): TileStats | undefined {
+ return value.breakdownProperty != null
+ ? stats.byIdentity.get(breakdownIdentityKey(value))
+ : stats.byValue.get(breakdownValueKey(value))
+}
+
+// How often a value is re-used, counted across every property it appears under. Sharing and
+// rank read this rather than the per-property count, so a value carried by several properties
+// is treated as one re-used value.
+function valueStatsOf(stats: ValueTileStats, value: BreakdownValueAndType): TileStats | undefined {
+ return stats.byValue.get(breakdownValueKey(value))
+}
+
+// Rank by re-use first, so the values shared by the most charts claim the earliest
+// slots. Ties break by the values' ranking within their own charts: each tile's value
+// list is in chart series order, and positions are summed across a value's tiles,
+// which compares like the average because tile counts are equal whenever the sum is
+// reached. Plain value order settles full ties (e.g. values leading disjoint tiles).
+// Both terms count the value across properties, so its entries rank next to each other
+// and the first one assigned sets the color the others copy.
+function buildAssignmentRankComparator(
+ stats: ValueTileStats
+): (a: BreakdownValueAndType, b: BreakdownValueAndType) => number {
+ return (a, b) => {
+ const entryA = valueStatsOf(stats, a)
+ const entryB = valueStatsOf(stats, b)
+ return (
+ (entryB?.tiles.length ?? 0) - (entryA?.tiles.length ?? 0) ||
+ (entryA?.positionSum ?? 0) - (entryB?.positionSum ?? 0) ||
+ compareAssignmentOrder(a, b)
+ )
+ }
+}
+
+/** Membership test for values that appear on two or more tiles, counted across every property
+ * they appear under. Only those receive a dashboard-wide auto color: cross-tile consistency is
+ * what the feature buys, and a value on a single insight has nothing to stay consistent with.
+ * The count ignores which property carried the value, so one tile of each of two properties is
+ * enough, those being the values whose color would otherwise be settled per property.
+ *
+ * An entry also has to still show somewhere in its own scope, so pruning drops an entry scoped
+ * to a property the dashboard no longer breaks down by, even while the value lives on
+ * elsewhere. */
+export function buildSharedBreakdownValueLookup(
+ tileBreakdownValues: BreakdownValueAndType[][]
+): (value: BreakdownValueAndType) => boolean {
+ const stats = collectValueTileStats(tileBreakdownValues)
+ return (value) =>
+ (statsOf(stats, value)?.tiles.length ?? 0) >= 1 && (valueStatsOf(stats, value)?.tiles.length ?? 0) >= 2
+}
+
+/** Complete existing configs with palette slots for breakdown values shared by 2+ tiles.
+ *
+ * Each property is its own color world: slot exclusivity is tracked per property, so a
+ * dashboard breaking down by several properties reuses the palette from the first slot for
+ * each of them, the way standalone insights do, instead of exhausting it across the union of
+ * all values. Unrelated values under different properties may therefore share a color; they
+ * never meet on one tile, since a tile breaks down by exactly one property.
+ *
+ * A value carried by several properties is one value to a reader, so its entries aim for one
+ * color: whichever is assigned first sets the slot, and the rest copy it unless that slot is
+ * taken within their own property. Ranking counts a value's tiles across properties, so those
+ * entries sort next to each other and copy before other values claim slots. Copying can still
+ * fail, which is visible as one value in two colors and is the honest outcome: within a
+ * property, two values sharing a color on one chart would be worse. Property-less legacy
+ * entries keep matching their value everywhere and claim their slot in every property they
+ * appear under.
*
- * Stability comes from persistence, not from the algorithm: existing configs (manual pins and
- * previously materialized auto entries) keep their slots untouched, and only uncovered values are
- * assigned here — sorted deterministically, filling free slots in ascending order. Once the
- * palette is exhausted further values wrap around it; getColorFromToken wraps the same way.
+ * Stability comes from persistence, not from the algorithm: manual pins never move, and
+ * persisted auto entries keep their slots unless two of them meet on one tile with the same
+ * slot (a new tile landed, or the entry predates collision-aware assignment); of such a
+ * pair, the lower-ranked entry moves. Uncovered shared values and displaced entries are
+ * ranked by how many charts re-use them, most first. Re-use ties break by the values'
+ * ranking within their own charts, then by a locale-independent value order. Each value
+ * takes the lowest slot unused within its property while slots last, then a slot its own
+ * tiles don't show yet, then the slot least used on those tiles: a duplicate color on two
+ * different charts is invisible, on one chart it isn't.
+ *
+ * Returns the full config list: existing entries in their original order (re-slotted ones
+ * replaced in place, so an unchanged dashboard round-trips deep-equal for the save diff),
+ * with new assignments appended.
*/
-export function computeAutoBreakdownColors(
- visibleValues: BreakdownValueAndType[],
+export function applyAutoBreakdownColors(
+ tileBreakdownValues: BreakdownValueAndType[][],
existingConfigs: BreakdownColorConfig[],
paletteSize: number = dataColorVars.length
): BreakdownColorConfig[] {
- const usedSlots = new Set<number>()
+ if (paletteSize <= 0) {
+ return [...existingConfigs]
+ }
+
+ const stats = collectValueTileStats(tileBreakdownValues)
+ const tilesOf = (value: BreakdownValueAndType): number[] => statsOf(stats, value)?.tiles ?? []
+ const compareAssignmentRank = buildAssignmentRankComparator(stats)
+
+ // Per-tile slot usage drives collision checks; per-property usage keeps distinct values
+ // of one property on distinct colors while slots last.
+ const tileSlotCounts: Map<number, number>[] = tileBreakdownValues.map(() => new Map())
+ const usedByProperty = new Map<string | null, Set<number>>()
+ const markUsed = (property: string | null, slot: number): void => {
+ let used = usedByProperty.get(property)
+ if (!used) {
+ used = new Set()
+ usedByProperty.set(property, used)
+ }
+ used.add(slot)
+ }
+ // The slot each value settled on, so its entries under other properties can copy it. First
+ // claim wins, and pins claim before auto entries, so a pinned color is the one copied.
+ const slotByValue = new Map<string, number>()
+ const claimSlot = (slot: number, value: BreakdownValueAndType, tiles: number[]): void => {
+ // Claiming for the entry's own property even without visible tiles keeps a
+ // temporarily hidden value's slot reserved within its property.
+ markUsed(value.breakdownProperty ?? null, slot)
+ if (!slotByValue.has(breakdownValueKey(value))) {
+ slotByValue.set(breakdownValueKey(value), slot)
+ }
+ for (const tile of tiles) {
+ markUsed(stats.tileProperties[tile] ?? null, slot)
+ tileSlotCounts[tile].set(slot, (tileSlotCounts[tile].get(slot) ?? 0) + 1)
+ }
+ }
+ // The slots an entry must treat as taken: its own property's plus, for property-less
+ // entries spanning several properties, those of every property its tiles belong to.
+ const usedFor = (value: BreakdownValueAndType): Set<number> => {
+ const used = new Set(usedByProperty.get(value.breakdownProperty ?? null) ?? [])
+ for (const tile of tilesOf(value)) {
+ usedByProperty.get(stats.tileProperties[tile] ?? null)?.forEach((slot) => used.add(slot))
+ }
+ return used
+ }
+
+ // Manual pins are user intent and never move; they claim their slots first.
+ const autoConfigs: BreakdownColorConfig[] = []
for (const config of existingConfigs) {
- const match = config.colorToken?.match(PRESET_TOKEN_REGEX)
- if (match) {
- usedSlots.add((Number(match[1]) - 1) % paletteSize)
+ const slot = presetTokenToSlot(config.colorToken, paletteSize)
+ if (slot == null) {
+ continue
+ }
+ if (config.source === 'auto') {
+ autoConfigs.push(config)
+ } else {
+ claimSlot(slot, config, tilesOf(config))
}
}
- const candidates = visibleValues
+ // Walking persisted auto entries in rank order means that of a colliding pair, the
+ // lower-ranked value (re-used by fewer charts, or trailing in chart order) moves.
+ const displaced: BreakdownValueAndType[] = []
+ for (const config of [...autoConfigs].sort(compareAssignmentRank)) {
+ const slot = presetTokenToSlot(config.colorToken, paletteSize)!
+ const tiles = tilesOf(config)
+ const collidesWithinTile = tiles.some((tile) => (tileSlotCounts[tile].get(slot) ?? 0) > 0)
+ if (collidesWithinTile) {
+ displaced.push(
+ makeBreakdownValue(config.breakdownValue, config.breakdownType, config.breakdownProperty ?? null)
+ )
+ } else {
+ claimSlot(slot, config, tiles)
+ }
+ }
+
+ const uncovered = [...stats.byIdentity.values()]
+ .map(({ value }) => value)
+ .filter((value) => (valueStatsOf(stats, value)?.tiles.length ?? 0) >= 2)
.filter(
(value) =>
isAutoAssignableBreakdownValue(value.breakdownValue) &&
- !findBreakdownColorConfig(existingConfigs, value.breakdownValue, value.breakdownType)?.colorToken
- )
- // code-unit comparison, not localeCompare — assignment order must not depend on the client locale
- .sort(
- (a, b) =>
- (a.breakdownType ?? 'event').localeCompare(b.breakdownType ?? 'event') ||
- (a.breakdownValue < b.breakdownValue ? -1 : a.breakdownValue > b.breakdownValue ? 1 : 0)
+ !findBreakdownColorConfig(
+ existingConfigs,
+ value.breakdownValue,
+ value.breakdownType,
+ value.breakdownProperty
+ )?.colorToken
)
- const freeSlots = Array.from({ length: paletteSize }, (_, slot) => slot).filter((slot) => !usedSlots.has(slot))
- let wrapCursor = 0
-
- const assigned: BreakdownColorConfig[] = []
- for (const candidate of candidates) {
- if (assigned.some((c) => breakdownConfigMatches(c, candidate.breakdownValue, candidate.breakdownType))) {
- continue
- }
- const slot = freeSlots.length > 0 ? freeSlots.shift()! : wrapCursor++ % paletteSize
- assigned.push({
- breakdownValue: candidate.breakdownValue,
- breakdownType: candidate.breakdownType,
- colorToken: `preset-${slot + 1}` as DataColorToken,
+ const allSlots = Array.from({ length: paletteSize }, (_, slot) => slot)
+ const assignments = new Map<string, BreakdownColorConfig>()
+ for (const candidate of [...uncovered, ...displaced].sort(compareAssignmentRank)) {
+ const tiles = tilesOf(candidate)
+ const used = usedFor(candidate)
+ const usedOnOwnTiles = (slot: number): number =>
+ tiles.reduce((sum, tile) => sum + (tileSlotCounts[tile].get(slot) ?? 0), 0)
+ // The slot this value took under another property comes first, even when a lower one is
+ // free: one color per value reads better than the palette's earliest colors.
+ const sharedSlot = slotByValue.get(breakdownValueKey(candidate))
+ const slot =
+ (sharedSlot != null && !used.has(sharedSlot) ? sharedSlot : undefined) ??
+ allSlots.find((slot) => !used.has(slot)) ??
+ allSlots.find((slot) => usedOnOwnTiles(slot) === 0) ??
+ allSlots.reduce((best, slot) => (usedOnOwnTiles(slot) < usedOnOwnTiles(best) ? slot : best))
+ claimSlot(slot, candidate, tiles)
+ assignments.set(breakdownIdentityKey(candidate), {
+ ...makeBreakdownValue(
+ candidate.breakdownValue,
+ candidate.breakdownType,
+ candidate.breakdownProperty ?? null
+ ),
+ colorToken: slotToPresetToken(slot),
source: 'auto',
})
}
- return assigned
+
+ const result = existingConfigs.map((config) => {
+ const replacement = assignments.get(breakdownIdentityKey(config))
+ if (replacement) {
+ assignments.delete(breakdownIdentityKey(config))
+ return replacement
+ }
+ return config
+ })
+ return [...result, ...assignments.values()]
+}
+
+/** One series of a tile, as input to position-based fallback completion. */
+export type TileFallbackSeries = {
+ /** Palette position of the series; current/previous compare pairs share one position. */
+ position: number
+ /** Token the series resolves to via a value override (dashboard breakdown color or
+ * explicit insight result customization), or null when it falls back to its position. */
+ overrideToken: DataColorToken | null
+}
+
+/** Position-based fallback tokens for the series of one tile that have no value override.
+ *
+ * Without dashboard colors, series get `preset-(position + 1)`: consecutive palette slots,
+ * which are designed to look distinct next to each other. Value overrides break that
+ * sequence, since they occupy slots scattered across the whole dashboard, so a
+ * position-colored neighbor can land on the same slot as an override on the same chart.
+ * Instead, non-overridden series fill the slots the tile's overrides do not use, in
+ * position order, cycling through those free slots once they run out (a duplicate among
+ * far-apart positions beats duplicating an override's color).
+ *
+ * Returns an empty map when the tile has no overrides, so override-free tiles keep plain
+ * position colors and render exactly as a standalone insight, and when overrides cover the
+ * whole palette, where no free slot exists to complete with.
+ */
+export function computeTileFallbackTokens(
+ series: TileFallbackSeries[],
+ paletteSize: number
+): Map<number, DataColorToken> {
+ const fallbackTokens = new Map<number, DataColorToken>()
+ if (paletteSize <= 0) {
+ return fallbackTokens
+ }
+
+ const overriddenPositions = new Set<number>()
+ const usedSlots = new Set<number>()
+ for (const { position, overrideToken } of series) {
+ const slot = presetTokenToSlot(overrideToken, paletteSize)
+ if (slot != null) {
+ overriddenPositions.add(position)
+ usedSlots.add(slot)
+ }
+ }
+ if (usedSlots.size === 0 || usedSlots.size >= paletteSize) {
+ return fallbackTokens
+ }
+
+ const freeSlots = Array.from({ length: paletteSize }, (_, slot) => slot).filter((slot) => !usedSlots.has(slot))
+ const positions = [...new Set(series.map((s) => s.position))]
+ .filter((position) => !overriddenPositions.has(position))
+ .sort((a, b) => a - b)
+ positions.forEach((position, index) => {
+ fallbackTokens.set(position, slotToPresetToken(freeSlots[index % freeSlots.length]))
+ })
+ return fallbackTokens
}
diff --git a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
index a76a7526d627..eedbd7636f14 100644
--- a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
@@ -1,16 +1,30 @@
-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'
-import { cohortsModel } from '~/models/cohortsModel'
-import { CohortType, DashboardTile, QueryBasedInsightModel } from '~/types'
+import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
-import type { CountedPaginatedResponse } from '../../lib/api'
-import { BreakdownValueAndType, extractBreakdownValues } from './dashboardBreakdownColors'
+import { DashboardMode, DashboardTile, QueryBasedInsightModel } from '~/types'
+
+import {
+ BreakdownColorConfig,
+ BreakdownValueAndType,
+ BreakdownValueGroup,
+ extractBreakdownValues,
+ groupBreakdownValuesByProperty,
+} from './dashboardBreakdownColors'
import { dashboardLogic } from './dashboardLogic'
+/** Unsaved color state captured when the modal opens, so Cancel can put it back. */
+interface ColorStateAtOpen {
+ colors: BreakdownColorConfig[]
+ themeId: { themeId: number | null } | null
+ wasInEditMode: boolean
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardInsightColorsModalLogicValues {
- allCohorts: CountedPaginatedResponse<CohortType> // cohortsModel
+ breakdownValueGroups: BreakdownValueGroup[]
breakdownValues: BreakdownValueAndType[]
+ colorStateAtOpen: ColorStateAtOpen | null
dashboardId: number | null
insightTiles: DashboardTile<QueryBasedInsightModel>[] | null
insightTilesLoading: boolean | null
@@ -19,9 +33,15 @@ export interface dashboardInsightColorsModalLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardInsightColorsModalLogicActions {
+ cancelColorChanges: () => {
+ value: true
+ }
hideInsightColorsModal: () => {
value: true
}
+ setColorStateAtOpen: (stateAtOpen: ColorStateAtOpen | null) => {
+ stateAtOpen: ColorStateAtOpen | null
+ }
showInsightColorsModal: (id: number) => {
id: number
}
@@ -40,9 +60,9 @@ export interface dashboardInsightColorsModalLogicMeta {
breakdownValues: (
insightTiles:
| DashboardTile<QueryBasedInsightModel<import('../../queries/schema').Node<Record<string, any>>>>[]
- | null,
- allCohorts: CountedPaginatedResponse<CohortType>
+ | null
) => BreakdownValueAndType[]
+ breakdownValueGroups: (breakdownValues: BreakdownValueAndType[]) => BreakdownValueGroup[]
}
}
@@ -55,12 +75,11 @@ export type dashboardInsightColorsModalLogicType = MakeLogicType<
export const dashboardInsightColorsModalLogic = kea<dashboardInsightColorsModalLogicType>([
path(['scenes', 'dashboard', 'dashboardInsightColorsModalLogic']),
- connect(() => ({
- values: [cohortsModel, ['allCohorts']],
- })),
actions({
showInsightColorsModal: (id: number) => ({ id }),
hideInsightColorsModal: true,
+ cancelColorChanges: true,
+ setColorStateAtOpen: (stateAtOpen: ColorStateAtOpen | null) => ({ stateAtOpen }),
}),
reducers({
dashboardId: [
@@ -70,7 +89,48 @@ export const dashboardInsightColorsModalLogic = kea<dashboardInsightColorsModalL
hideInsightColorsModal: () => null,
},
],
+ colorStateAtOpen: [
+ null as ColorStateAtOpen | null,
+ {
+ setColorStateAtOpen: (_, { stateAtOpen }) => stateAtOpen,
+ hideInsightColorsModal: () => null,
+ },
+ ],
}),
+ listeners(({ actions, values }) => ({
+ showInsightColorsModal: ({ id }) => {
+ const mountedDashboardLogic = dashboardLogic.findMounted({ id })
+ actions.setColorStateAtOpen(
+ mountedDashboardLogic
+ ? {
+ colors: mountedDashboardLogic.values.temporaryBreakdownColors,
+ themeId: mountedDashboardLogic.values.temporaryDataColorThemeId,
+ wasInEditMode: mountedDashboardLogic.values.dashboardMode === DashboardMode.Edit,
+ }
+ : null
+ )
+ },
+ cancelColorChanges: () => {
+ const stateAtOpen = values.colorStateAtOpen
+ const mountedDashboardLogic =
+ values.dashboardId != null ? dashboardLogic.findMounted({ id: values.dashboardId }) : null
+ if (mountedDashboardLogic && stateAtOpen) {
+ if (stateAtOpen.wasInEditMode) {
+ // Edit mode predates the modal, so filter or layout edits may be pending.
+ // Revert only the color state and leave the rest of the edit session alone.
+ mountedDashboardLogic.actions.restoreTemporaryColorState(stateAtOpen.colors, stateAtOpen.themeId)
+ } else if (mountedDashboardLogic.values.dashboardMode === DashboardMode.Edit) {
+ // The modal entered edit mode itself, so the color edits are the only unsaved
+ // changes and a full discard both reverts them and exits edit mode.
+ mountedDashboardLogic.actions.setDashboardMode(
+ null,
+ DashboardEventSource.DashboardHeaderDiscardChanges
+ )
+ }
+ }
+ actions.hideInsightColorsModal()
+ },
+ })),
selectors({
isOpen: [(s) => [s.dashboardId], (dashboardId: number | null) => dashboardId != null],
insightTiles: [
@@ -87,11 +147,12 @@ export const dashboardInsightColorsModalLogic = kea<dashboardInsightColorsModalL
{ resultEqualityCheck: () => false },
],
breakdownValues: [
- (s) => [s.insightTiles, s.allCohorts],
- (
- insightTiles: DashboardTile<QueryBasedInsightModel>[] | null,
- allCohorts: import('../../lib/api').CountedPaginatedResponse<CohortType>
- ) => extractBreakdownValues(insightTiles, allCohorts?.results),
+ (s) => [s.insightTiles],
+ (insightTiles: DashboardTile<QueryBasedInsightModel>[] | null) => extractBreakdownValues(insightTiles),
+ ],
+ breakdownValueGroups: [
+ (s) => [s.breakdownValues],
+ (breakdownValues: BreakdownValueAndType[]) => groupBreakdownValuesByProperty(breakdownValues),
],
}),
])
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 9dd5507750e3..8dde4795c647 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -15,6 +15,7 @@ import * as featureFlagLib from 'lib/logic/featureFlagLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'
+import { dashboardInsightColorsModalLogic } from 'scenes/dashboard/dashboardInsightColorsModalLogic'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import * as dashboardUtils from 'scenes/dashboard/dashboardUtils'
import * as widgetFetchUtils from 'scenes/dashboard/widgetFetchUtils'
@@ -485,26 +486,59 @@ describe('dashboardLogic', () => {
expect(logic.values.hasUnsavedColorChanges).toBe(false)
})
- it('auto-assigns breakdown colors only behind the dashboard colors flag', async () => {
+ it('exiting edit mode via the colors modal save source persists color changes', async () => {
await expectLogic(logic).toFinishAllListeners()
- const tileInsight = logic.values.dashboard!.tiles.find((t) => !!t.insight)!.insight!
- const insightWithBreakdowns = {
- ...tileInsight,
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'x',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ })
+ }).toFinishAllListeners()
+
+ jest.spyOn(api, 'update')
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardMode(null, DashboardEventSource.DashboardInsightColorsModal)
+ })
+ .toDispatchActions(['saveEditModeChanges', 'saveEditModeChangesSuccess'])
+ .toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledWith(
+ `api/environments/${MOCK_TEAM_ID}/dashboards/5`,
+ expect.objectContaining({
+ breakdown_colors: expect.arrayContaining([
+ expect.objectContaining({ breakdownValue: 'x', colorToken: 'preset-1' }),
+ ]),
+ })
+ )
+ })
+
+ it('auto-assigns colors to multi-tile breakdown values only behind the dashboard colors flag', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const [firstInsight, secondInsight] = logic.values
+ .dashboard!.tiles.filter((t) => !!t.insight)
+ .map((t) => t.insight!)
+ const withBreakdowns = (insight: typeof firstInsight, breakdownValues: string[]): typeof firstInsight => ({
+ ...insight,
dashboards: [5],
dashboard_tiles: [{ id: 1, dashboard_id: 5 }],
- result: [
- { action: { order: 0 }, breakdown_value: ['Chrome'] },
- { action: { order: 0 }, breakdown_value: ['Firefox'] },
- ],
+ result: breakdownValues.map((breakdown_value) => ({
+ action: { order: 0 },
+ breakdown_value: [breakdown_value],
+ })),
query: {
kind: NodeKind.InsightVizNode,
source: { kind: NodeKind.TrendsQuery, series: [] },
} as InsightVizNode<TrendsQuery>,
- }
+ })
await expectLogic(logic, () => {
- dashboardsModel.actions.updateDashboardInsight(insightWithBreakdowns)
+ dashboardsModel.actions.updateDashboardInsight(withBreakdowns(firstInsight, ['Chrome', 'Firefox']))
+ dashboardsModel.actions.updateDashboardInsight(withBreakdowns(secondInsight, ['Chrome']))
}).toFinishAllListeners()
expect(logic.values.effectiveBreakdownColors).toEqual([])
@@ -513,9 +547,10 @@ describe('dashboardLogic', () => {
[FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]: true,
})
+ // Chrome appears on both tiles; Firefox is unique to one tile and keeps
+ // position-based colors, so it gets no dashboard-wide entry
expect(logic.values.effectiveBreakdownColors).toEqual([
expect.objectContaining({ breakdownValue: 'Chrome', colorToken: 'preset-1', source: 'auto' }),
- expect.objectContaining({ breakdownValue: 'Firefox', colorToken: 'preset-2', source: 'auto' }),
])
})
@@ -526,22 +561,24 @@ describe('dashboardLogic', () => {
[FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]: true,
})
- const tileInsight = logic.values.dashboard!.tiles.find((t) => !!t.insight)!.insight!
+ const tileInsights = logic.values.dashboard!.tiles.filter((t) => !!t.insight).map((t) => t.insight!)
await expectLogic(logic, () => {
- dashboardsModel.actions.updateDashboardInsight({
- ...tileInsight,
- dashboards: [5],
- dashboard_tiles: [{ id: 1, dashboard_id: 5 }],
- result: [
- { action: { order: 0 }, breakdown_value: ['Chrome'] },
- { action: { order: 0 }, breakdown_value: ['Firefox'] },
- { action: { order: 0 }, breakdown_value: ['Safari'] },
- ],
- query: {
- kind: NodeKind.InsightVizNode,
- source: { kind: NodeKind.TrendsQuery, series: [] },
- } as InsightVizNode<TrendsQuery>,
- })
+ for (const tileInsight of tileInsights) {
+ dashboardsModel.actions.updateDashboardInsight({
+ ...tileInsight,
+ dashboards: [5],
+ dashboard_tiles: [{ id: 1, dashboard_id: 5 }],
+ result: [
+ { action: { order: 0 }, breakdown_value: ['Chrome'] },
+ { action: { order: 0 }, breakdown_value: ['Firefox'] },
+ { action: { order: 0 }, breakdown_value: ['Safari'] },
+ ],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [] },
+ } as InsightVizNode<TrendsQuery>,
+ })
+ }
logic.actions.setDataColorThemeId(123)
}).toFinishAllListeners()
@@ -598,6 +635,74 @@ describe('dashboardLogic', () => {
)
})
+ it('keeps shared auto colors when a failed refresh leaves a tile without results', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]: true,
+ })
+
+ const [firstInsight, secondInsight] = logic.values
+ .dashboard!.tiles.filter((t) => !!t.insight)
+ .map((t) => t.insight!)
+ const withBreakdownQuery = (
+ insight: typeof firstInsight,
+ breakdownValues: string[] | null
+ ): typeof firstInsight => ({
+ ...insight,
+ dashboards: [5],
+ dashboard_tiles: [{ id: 1, dashboard_id: 5 }],
+ result: breakdownValues
+ ? breakdownValues.map((breakdown_value) => ({ action: { order: 0 }, breakdown_value }))
+ : null,
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ },
+ } as InsightVizNode<TrendsQuery>,
+ })
+
+ await expectLogic(logic, () => {
+ // one loaded tile showing the value, one in the state a failed refresh leaves
+ // behind: a breakdown query whose insight never got results, while itemsLoading
+ // settles back to false
+ dashboardsModel.actions.updateDashboardInsight(withBreakdownQuery(firstInsight, ['Chrome', 'Firefox']))
+ dashboardsModel.actions.updateDashboardInsight(withBreakdownQuery(secondInsight, null))
+ // the auto entry an earlier save materialized while both tiles shared 'Chrome'
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'Chrome',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ source: 'auto',
+ })
+ }).toFinishAllListeners()
+
+ expect(logic.values.itemsLoading).toBe(false)
+ // Chrome only looks single-tile because the failed tile's values are unknown
+ expect(logic.values.effectiveBreakdownColors).toContainEqual(
+ expect.objectContaining({ breakdownValue: 'Chrome', colorToken: 'preset-1', source: 'auto' })
+ )
+
+ jest.spyOn(api, 'update')
+
+ await expectLogic(logic, () => {
+ logic.actions.saveEditModeChanges()
+ }).toFinishAllListeners()
+
+ // the entry survives the save instead of being pruned from the partial tile set
+ expect(api.update).toHaveBeenCalledWith(
+ `api/environments/${MOCK_TEAM_ID}/dashboards/5`,
+ expect.objectContaining({
+ breakdown_colors: [
+ expect.objectContaining({ breakdownValue: 'Chrome', colorToken: 'preset-1', source: 'auto' }),
+ ],
+ })
+ )
+ })
+
it('saving after theme change calls api', async () => {
await expectLogic(logic).toFinishAllListeners()
@@ -1124,6 +1229,72 @@ describe('dashboardLogic', () => {
}
)
})
+
+ describe('colors modal cancel', () => {
+ beforeEach(() => {
+ dashboardInsightColorsModalLogic.mount()
+ })
+
+ it('discards color edits and exits edit mode when the modal was opened from view mode', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ dashboardInsightColorsModalLogic.actions.showInsightColorsModal(5)
+ logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'x',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ })
+ logic.actions.setDataColorThemeId(123)
+ }).toFinishAllListeners()
+
+ expect(logic.values.hasUnsavedColorChanges).toBe(true)
+
+ await expectLogic(logic, () => {
+ dashboardInsightColorsModalLogic.actions.cancelColorChanges()
+ }).toFinishAllListeners()
+
+ expect(dashboardInsightColorsModalLogic.values.isOpen).toBe(false)
+ expect(logic.values.dashboardMode).toBeNull()
+ expect(logic.values.hasUnsavedColorChanges).toBe(false)
+ expect(logic.values.dataColorThemeId).toBe(logic.values.dashboard?.data_color_theme_id ?? null)
+ })
+
+ it('reverts only the modal color edits and stays in edit mode when edit mode predates the modal', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ logic.actions.setDates('-7d', null)
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'x',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ })
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ dashboardInsightColorsModalLogic.actions.showInsightColorsModal(5)
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'y',
+ breakdownType: 'event',
+ colorToken: 'preset-2',
+ })
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ dashboardInsightColorsModalLogic.actions.cancelColorChanges()
+ }).toFinishAllListeners()
+
+ expect(dashboardInsightColorsModalLogic.values.isOpen).toBe(false)
+ expect(logic.values.dashboardMode).toBe(DashboardMode.Edit)
+ expect(logic.values.effectiveEditBarFilters.date_from).toBe('-7d')
+ expect(logic.values.temporaryBreakdownColors).toEqual([
+ expect.objectContaining({ breakdownValue: 'x', colorToken: 'preset-1' }),
+ ])
+ })
+ })
})
describe('moving between dashboards', () => {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index a465450b7b71..e4975d9b11e8 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -117,9 +117,12 @@ import { filterVariablesReferencedInQuery } from '../insights/utils/queryUtils'
import { teamLogic } from '../teamLogic'
import {
BreakdownColorConfig,
- computeAutoBreakdownColors,
- extractBreakdownValues,
+ applyAutoBreakdownColors,
+ breakdownConfigIdentityMatches,
+ buildSharedBreakdownValueLookup,
+ extractBreakdownValuesByTile,
findBreakdownColorConfig,
+ hasUnresolvedBreakdownTiles,
mergeBreakdownColorConfigs,
} from './dashboardBreakdownColors'
import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from './dashboardConstants'
@@ -247,12 +250,14 @@ export interface dashboardLogicValues {
layoutSize?: 'sm' | 'xs' | undefined
) => string
asDashboardTemplate: DashboardTemplateEditorType | undefined
+ autoBreakdownColorsEnabled: boolean
autoRefresh: {
enabled: boolean
interval: number
}
blockRefresh: boolean
breadcrumbs: Breadcrumb[]
+ breakdownValuesIncomplete: boolean
buttonTileId: number | 'new' | null
canAutoPreview: boolean
canEditDashboard: boolean
@@ -639,6 +644,17 @@ export interface dashboardLogicActions {
resetUrlVariables: () => {
value: true
}
+ restoreTemporaryColorState: (
+ colors: BreakdownColorConfig[],
+ themeId: {
+ themeId: number | null
+ } | null
+ ) => {
+ colors: BreakdownColorConfig[]
+ themeId: {
+ themeId: number | null
+ } | null
+ }
restoreUrlStateAtEditModeEntry: (
snapshot: {
filters?: unknown
@@ -1103,12 +1119,17 @@ export interface dashboardLogicMeta {
dataColorThemeId: number | null,
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null // dataThemeLogic
) => DataColorTheme | null
+ autoBreakdownColorsEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ breakdownValuesIncomplete: (
+ itemsLoading: boolean,
+ insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[]
+ ) => boolean
effectiveBreakdownColors: (
temporaryBreakdownColors: BreakdownColorConfig[],
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[],
- itemsLoading: boolean,
- featureFlags: FeatureFlagsSet,
+ breakdownValuesIncomplete: boolean,
+ autoBreakdownColorsEnabled: boolean,
dataColorTheme: DataColorTheme | null
) => BreakdownColorConfig[]
hasUnsavedColorChanges: (
@@ -1348,6 +1369,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
*/
setBreakdownColorConfig: (config: BreakdownColorConfig) => ({ config }),
setDataColorThemeId: (dataColorThemeId: number | null) => ({ dataColorThemeId }),
+ restoreTemporaryColorState: (colors: BreakdownColorConfig[], themeId: { themeId: number | null } | null) => ({
+ colors,
+ themeId,
+ }),
setLoadLayoutFromServerOnPreview: (loadLayoutFromServerOnPreview: boolean) => ({
loadLayoutFromServerOnPreview,
@@ -1455,11 +1480,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
persistedVariables,
values.effectiveDashboardVariableOverrides || {}
)
- // With tiles still loading the visible breakdown values are incomplete, so
- // fresh auto assignments and stale-entry pruning would both act on partial
- // data — persist only the saved colors with unsaved edits merged over them,
- // and leave materializing auto entries to a save with every tile loaded.
- const breakdownColorsToSave = values.itemsLoading
+ // While tiles are still loading, or an errored/aborted tile is missing its
+ // results, the visible breakdown values are incomplete, so fresh auto
+ // assignments and stale-entry pruning would both act on partial data.
+ // Persist only the saved colors with unsaved edits merged over them, and
+ // leave materializing auto entries to a save with every tile's values known.
+ const breakdownColorsToSave = values.breakdownValuesIncomplete
? mergeBreakdownColorConfigs(
values.temporaryBreakdownColors,
persistedBreakdownColors
@@ -1821,11 +1847,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
[] as BreakdownColorConfig[],
{
setBreakdownColorConfig: (state, { config }) => {
- const existingConfigIndex = state.findIndex(
- (c) =>
- String(c.breakdownValue) === String(config.breakdownValue) &&
- c.breakdownType === config.breakdownType
- )
+ const existingConfigIndex = state.findIndex((c) => breakdownConfigIdentityMatches(c, config))
if (existingConfigIndex >= 0) {
return [...state.slice(0, existingConfigIndex), config, ...state.slice(existingConfigIndex + 1)]
}
@@ -1835,6 +1857,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
// and a failed save (which also fires saveEditModeChangesSuccess) must keep them.
setDashboardMode: (state, { source }) =>
source === DashboardEventSource.DashboardHeaderDiscardChanges ? [] : state,
+ restoreTemporaryColorState: (_, { colors }) => colors,
},
],
// Unsaved theme edit; null means untouched, so clearing the theme is distinguishable
@@ -1844,6 +1867,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
setDataColorThemeId: (_, { dataColorThemeId }) => ({ themeId: dataColorThemeId || null }),
setDashboardMode: (state, { source }) =>
source === DashboardEventSource.DashboardHeaderDiscardChanges ? null : state,
+ restoreTemporaryColorState: (_, { themeId }) => themeId,
},
],
layoutZoom: [
@@ -2944,23 +2968,38 @@ export const dashboardLogic = kea<dashboardLogicType>([
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null
): DataColorTheme | null => getTheme(dataColorThemeId),
],
+ autoBreakdownColorsEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS],
+ ],
+ // itemsLoading alone can't stand in for completeness: a refresh that errors or is
+ // aborted before the insight ever got results leaves the tile with result: null after
+ // loading settles, hiding its breakdown values from the sharing check.
+ breakdownValuesIncomplete: [
+ (s) => [s.itemsLoading, s.insightTiles],
+ (itemsLoading: boolean, insightTiles: DashboardTile<QueryBasedInsightModel>[] | null): boolean =>
+ itemsLoading || hasUnresolvedBreakdownTiles(insightTiles),
+ ],
// Persisted colors with unsaved edits merged over them, plus auto-assigned colors for
- // uncovered breakdown values. This is both what tiles render and what a save persists.
+ // breakdown values shared by multiple tiles. This is both what tiles render and what a
+ // save persists. Values unique to one tile keep position-based colors (see
+ // computeTileFallbackTokens), so they don't consume palette slots here.
effectiveBreakdownColors: [
(s) => [
s.temporaryBreakdownColors,
s.dashboard,
s.insightTiles,
- s.itemsLoading,
- s.featureFlags,
+ s.breakdownValuesIncomplete,
+ s.autoBreakdownColorsEnabled,
s.dataColorTheme,
],
(
temporaryBreakdownColors: BreakdownColorConfig[],
dashboard: DashboardType<QueryBasedInsightModel> | null,
insightTiles: DashboardTile<QueryBasedInsightModel>[] | null,
- itemsLoading: boolean,
- featureFlags: FeatureFlagsSet,
+ breakdownValuesIncomplete: boolean,
+ autoBreakdownColorsEnabled: boolean,
dataColorTheme: DataColorTheme | null
): BreakdownColorConfig[] => {
const merged = mergeBreakdownColorConfigs(
@@ -2968,29 +3007,24 @@ export const dashboardLogic = kea<dashboardLogicType>([
dashboard?.breakdown_colors ?? []
).filter((config) => !!config.colorToken)
- if (!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]) {
+ if (!autoBreakdownColorsEnabled) {
return merged
}
- const visibleValues = extractBreakdownValues(insightTiles, null)
- // Prune stale auto entries only once all tiles have loaded — a partial tile set
- // would drop colors for values that are merely still loading.
- const kept = itemsLoading
+ const tileBreakdownValues = extractBreakdownValuesByTile(insightTiles)
+ // Prune stale or no-longer-shared auto entries only when every tile's breakdown
+ // values are known: with a partial tile set (still loading, or errored/aborted
+ // without results) a genuinely shared value can look single-tile and would lose
+ // its color.
+ const isShared = buildSharedBreakdownValueLookup(tileBreakdownValues)
+ const kept = breakdownValuesIncomplete
? merged
- : merged.filter(
- (config) =>
- config.source !== 'auto' ||
- visibleValues.some(
- (value) =>
- value.breakdownValue === config.breakdownValue &&
- value.breakdownType === config.breakdownType
- )
- )
+ : merged.filter((config) => config.source !== 'auto' || isShared(config))
// Size assignment to the active theme — getColorFromToken wraps tokens past the
// theme's color count, so assuming the default 15 slots on a smaller theme would
// hand out visually duplicate colors while palette slots remain free.
const paletteSize = dataColorTheme ? Object.keys(dataColorTheme).length : undefined
- return [...kept, ...computeAutoBreakdownColors(visibleValues, kept, paletteSize)]
+ return applyAutoBreakdownColors(tileBreakdownValues, kept, paletteSize)
},
],
hasUnsavedColorChanges: [
@@ -3005,7 +3039,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
const persistedConfig = findBreakdownColorConfig(
persisted,
config.breakdownValue,
- config.breakdownType
+ config.breakdownType,
+ config.breakdownProperty
)
return config.colorToken
? persistedConfig?.colorToken !== config.colorToken
@@ -4039,9 +4074,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
} else if (
mode === null &&
(source === DashboardEventSource.DashboardHeaderSaveDashboard ||
- source === DashboardEventSource.SceneCommonButtons)
+ source === DashboardEventSource.SceneCommonButtons ||
+ source === DashboardEventSource.DashboardInsightColorsModal)
) {
- // save edit mode changes when exiting via Save button or E key/Edit layout button
+ // save edit mode changes when exiting via Save button, E key/Edit layout button,
+ // or the colors modal's Save button
// Pending name/description are included in the saveEditModeChanges PATCH
// to avoid a race between two concurrent PATCHes to the same endpoint.
actions.saveEditModeChanges()
diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.ts
index 6d95bd32bd98..0acfada1cbd6 100644
--- a/frontend/src/scenes/funnels/funnelDataLogic.ts
+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts
@@ -5,14 +5,24 @@ import { BIN_COUNT_AUTO } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { average, percentage, sum } from 'lib/utils/numbers'
-import { findBreakdownColorConfig } from 'scenes/dashboard/dashboardBreakdownColors'
+import {
+ BreakdownColorConfig,
+ computeTileFallbackTokens,
+ findBreakdownColorConfig,
+ getBreakdownPropertyKey,
+} from 'scenes/dashboard/dashboardBreakdownColors'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { AGGREGATION_LABEL_FOR_CUSTOM_DATA_WAREHOUSE } from 'scenes/insights/filters/aggregationTargetUtils'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
-import { getFunnelDatasetKey, getFunnelResultCustomizationColorToken } from 'scenes/insights/utils'
+import {
+ getFunnelDatasetKey,
+ getFunnelDatasetPosition,
+ getFunnelResultCustomization,
+ getFunnelResultCustomizationColorToken,
+} from 'scenes/insights/utils'
import { Noun, groupsModel } from '~/models/groupsModel'
import { seriesNodeToFilter } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
@@ -481,7 +491,9 @@ export interface funnelDataLogicMeta {
resultCustomizations: Record<string, ResultCustomizationByValue> | undefined,
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null,
breakdownFilter: BreakdownFilter | null | undefined,
- querySource: FunnelsQuery | null
+ querySource: FunnelsQuery | null,
+ flattenedBreakdowns: FlattenedFunnelStepByBreakdown[],
+ disableFunnelBreakdownBaseline: boolean
) => (
dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics
) => [DataColorTheme | null, DataColorToken | null]
@@ -1242,15 +1254,64 @@ export const funnelDataLogic = kea<funnelDataLogicType>([
},
],
getFunnelsColorToken: [
- (s) => [s.resultCustomizations, s.getTheme, s.breakdownFilter, s.querySource],
+ (s) => [
+ s.resultCustomizations,
+ s.getTheme,
+ s.breakdownFilter,
+ s.querySource,
+ s.flattenedBreakdowns,
+ s.disableFunnelBreakdownBaseline,
+ ],
(
resultCustomizations:
| Record<string, import('~/queries/schema/schema-general').ResultCustomizationByValue>
| undefined,
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null,
breakdownFilter: null | import('~/queries/schema/schema-general').BreakdownFilter | undefined,
- querySource: FunnelsQuery | null
+ querySource: FunnelsQuery | null,
+ flattenedBreakdowns: FlattenedFunnelStepByBreakdown[],
+ disableFunnelBreakdownBaseline: boolean
) => {
+ const breakdownPropertyKey = getBreakdownPropertyKey(breakdownFilter)
+ // The dashboard's colors live in another logic and are read at call time, so the
+ // per-tile fallback map is memoized here on the identity of what it derives from.
+ let fallbackSource: { overrides: BreakdownColorConfig[]; theme: DataColorTheme } | null = null
+ let fallbackTokens = new Map<number, DataColorToken>()
+ const tileFallbackToken = (
+ overrides: BreakdownColorConfig[],
+ theme: DataColorTheme,
+ dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics
+ ): DataColorToken | undefined => {
+ if (fallbackSource?.overrides !== overrides || fallbackSource?.theme !== theme) {
+ fallbackSource = { overrides, theme }
+ // Completion only activates when a dashboard override actually sits on this
+ // tile; a series customization alone must not shift its neighbors' colors.
+ // Once active, customized series claim their slots like overrides do.
+ let hasDashboardOverride = false
+ const series = flattenedBreakdowns.map((breakdown) => {
+ const overrideToken =
+ findBreakdownColorConfig(
+ overrides,
+ JSON.parse(getFunnelDatasetKey(breakdown))['breakdown_value'],
+ breakdownFilter?.breakdown_type,
+ breakdownPropertyKey
+ )?.colorToken ?? null
+ hasDashboardOverride = hasDashboardOverride || !!overrideToken
+ return {
+ position: getFunnelDatasetPosition(breakdown, disableFunnelBreakdownBaseline),
+ overrideToken:
+ overrideToken ??
+ getFunnelResultCustomization(breakdown, resultCustomizations)?.color ??
+ null,
+ }
+ })
+ fallbackTokens = hasDashboardOverride
+ ? computeTileFallbackTokens(series, Object.keys(theme).length)
+ : new Map<number, DataColorToken>()
+ }
+ return fallbackTokens.get(getFunnelDatasetPosition(dataset, disableFunnelBreakdownBaseline))
+ }
+
return (
dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics
): [DataColorTheme | null, DataColorToken | null] => {
@@ -1261,7 +1322,8 @@ export const funnelDataLogic = kea<funnelDataLogicType>([
const colorOverride = findBreakdownColorConfig(
logic?.values.effectiveBreakdownColors,
breakdownValue,
- breakdownFilter?.breakdown_type
+ breakdownFilter?.breakdown_type,
+ breakdownPropertyKey
)
if (colorOverride?.colorToken) {
@@ -1276,6 +1338,20 @@ export const funnelDataLogic = kea<funnelDataLogicType>([
return [null, null]
}
+ // On dashboards with auto colors, series without a value override fill the
+ // palette slots the tile's overrides don't use, because the plain
+ // position-based fallback can land on the same slot as an override shown on
+ // this very chart. An explicit per-series customization still wins below.
+ if (logic?.values.autoBreakdownColorsEnabled) {
+ const customizationColor = getFunnelResultCustomization(dataset, resultCustomizations)?.color
+ const fallbackToken = customizationColor
+ ? undefined
+ : tileFallbackToken(logic.values.effectiveBreakdownColors, theme, dataset)
+ if (fallbackToken) {
+ return [theme, fallbackToken]
+ }
+ }
+
return [
theme,
getFunnelResultCustomizationColorToken(
diff --git a/frontend/src/scenes/retention/retentionLogic.ts b/frontend/src/scenes/retention/retentionLogic.ts
index fa383b85008b..79eb81257e64 100644
--- a/frontend/src/scenes/retention/retentionLogic.ts
+++ b/frontend/src/scenes/retention/retentionLogic.ts
@@ -7,7 +7,12 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { formatDateRange } from 'lib/utils/datetime'
-import { BreakdownColorConfig, findBreakdownColorConfig } from 'scenes/dashboard/dashboardBreakdownColors'
+import {
+ BreakdownColorConfig,
+ computeTileFallbackTokens,
+ findBreakdownColorConfig,
+ getBreakdownPropertyKey,
+} from 'scenes/dashboard/dashboardBreakdownColors'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -186,8 +191,10 @@ export interface retentionLogicMeta {
| WebOverviewQuery
| WebStatsTableQuery
| null,
+ breakdownValues: (number | string | null | undefined)[],
arg: BreakdownColorConfig[] | null,
- arg2: DataColorTheme | null
+ arg2: DataColorTheme | null,
+ arg3: boolean
) => (
rawBreakdownValue: number | string | null | undefined,
seriesIndex: number
@@ -634,6 +641,7 @@ export const retentionLogic = kea<retentionLogicType>([
s.getTheme,
s.breakdownFilter,
s.querySource,
+ s.breakdownValues,
// The dashboard's colors live in a different logic, so they must be selector
// inputs rather than reads inside the returned function: the charts memoize
// series on this function's identity, which only changes when inputs do.
@@ -646,6 +654,11 @@ export const retentionLogic = kea<retentionLogicType>([
props.dashboardId != null
? (dashboardLogic.findMounted({ id: props.dashboardId })?.values.dataColorTheme ?? null)
: null,
+ () =>
+ props.dashboardId != null
+ ? (dashboardLogic.findMounted({ id: props.dashboardId })?.values.autoBreakdownColorsEnabled ??
+ false)
+ : false,
],
(
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null,
@@ -660,9 +673,37 @@ export const retentionLogic = kea<retentionLogicType>([
| WebOverviewQuery
| WebStatsTableQuery
| null,
+ breakdownValues: (number | string | null | undefined)[],
dashboardBreakdownColors: BreakdownColorConfig[] | null,
- dashboardDataColorTheme: DataColorTheme | null
+ dashboardDataColorTheme: DataColorTheme | null,
+ autoBreakdownColorsEnabled: boolean
) => {
+ const breakdownPropertyKey = getBreakdownPropertyKey(breakdownFilter)
+ // On dashboards with auto colors, series without a value override fill the
+ // palette slots the tile's overrides don't use, because the plain
+ // position-based fallback can land on the same slot as an override shown on
+ // this very chart. Retention has no resultCustomizations, so the series list
+ // is just the breakdown values in result order.
+ const fallbackTheme =
+ dashboardDataColorTheme ||
+ getTheme(querySource && 'dataColorTheme' in querySource ? querySource.dataColorTheme : undefined)
+ const fallbackTokens =
+ autoBreakdownColorsEnabled && dashboardBreakdownColors && fallbackTheme
+ ? computeTileFallbackTokens(
+ breakdownValues.map((breakdownValue, index) => ({
+ position: index,
+ overrideToken:
+ findBreakdownColorConfig(
+ dashboardBreakdownColors,
+ breakdownValue,
+ breakdownFilter?.breakdown_type,
+ breakdownPropertyKey
+ )?.colorToken ?? null,
+ })),
+ Object.keys(fallbackTheme).length
+ )
+ : new Map<number, DataColorToken>()
+
return (
rawBreakdownValue: string | number | null | undefined,
seriesIndex: number
@@ -671,7 +712,8 @@ export const retentionLogic = kea<retentionLogicType>([
const colorOverride = findBreakdownColorConfig(
dashboardBreakdownColors,
rawBreakdownValue,
- breakdownFilter?.breakdown_type
+ breakdownFilter?.breakdown_type,
+ breakdownPropertyKey
)
if (colorOverride?.colorToken) {
@@ -689,6 +731,16 @@ export const retentionLogic = kea<retentionLogicType>([
return [null, null]
}
+ if (fallbackTokens.size > 0) {
+ // Keyed by value rather than by the chart's series index, so a series
+ // keeps its color when a breakdown-value filter shifts the indexes.
+ const seriesPosition = breakdownValues.indexOf(rawBreakdownValue)
+ const fallbackToken = seriesPosition === -1 ? undefined : fallbackTokens.get(seriesPosition)
+ if (fallbackToken) {
+ return [theme, fallbackToken]
+ }
+ }
+
// retention has no resultCustomizations, so the fallback is purely positional
return [theme, `preset-${(seriesIndex % Object.keys(theme).length) + 1}` as DataColorToken]
}
diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.ts
index b63488391529..fc6aa0e2090a 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.ts
@@ -3,7 +3,12 @@ import { MakeLogicType, actions, connect, kea, key, listeners, path, props, redu
import { DataColorTheme, DataColorToken } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
import { isMultiSeriesFormula } from 'lib/utils/strings'
-import { findBreakdownColorConfig } from 'scenes/dashboard/dashboardBreakdownColors'
+import {
+ BreakdownColorConfig,
+ computeTileFallbackTokens,
+ findBreakdownColorConfig,
+ getBreakdownPropertyKey,
+} from 'scenes/dashboard/dashboardBreakdownColors'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -15,6 +20,7 @@ import {
BREAKDOWN_OTHER_NUMERIC_LABEL,
BREAKDOWN_OTHER_STRING_LABEL,
getTrendDatasetKey,
+ getTrendDatasetPosition,
getTrendResultCustomization,
getTrendResultCustomizationColorToken,
getTrendResultCustomizationKey,
@@ -393,7 +399,8 @@ export interface trendsDataLogicMeta {
| TrendsQuery
| WebOverviewQuery
| WebStatsTableQuery
- | null
+ | null,
+ indexedResults: IndexedTrendResult[]
) => (dataset: IndexedTrendResult) => [DataColorTheme | null, DataColorToken | null]
getTrendsColor: (
getTrendsColorToken: (dataset: IndexedTrendResult) => [DataColorTheme | null, DataColorToken | null]
@@ -860,7 +867,14 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
],
getTrendsColorToken: [
- (s) => [s.resultCustomizationBy, s.resultCustomizations, s.getTheme, s.breakdownFilter, s.querySource],
+ (s) => [
+ s.resultCustomizationBy,
+ s.resultCustomizations,
+ s.getTheme,
+ s.breakdownFilter,
+ s.querySource,
+ s.indexedResults,
+ ],
(
resultCustomizationBy: ResultCustomizationBy,
resultCustomizations:
@@ -878,8 +892,50 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
| import('~/queries/schema/schema-general').RetentionQuery
| import('~/queries/schema/schema-general').StickinessQuery
| import('~/queries/schema/schema-general').WebOverviewQuery
- | import('~/queries/schema/schema-general').WebStatsTableQuery
+ | import('~/queries/schema/schema-general').WebStatsTableQuery,
+ indexedResults: IndexedTrendResult[]
) => {
+ const breakdownPropertyKey = getBreakdownPropertyKey(breakdownFilter)
+ // The dashboard's colors live in another logic and are read at call time, so the
+ // per-tile fallback map is memoized here on the identity of what it derives from.
+ let fallbackSource: { overrides: BreakdownColorConfig[]; theme: DataColorTheme } | null = null
+ let fallbackTokens = new Map<number, DataColorToken>()
+ const tileFallbackToken = (
+ overrides: BreakdownColorConfig[],
+ theme: DataColorTheme,
+ dataset: IndexedTrendResult
+ ): DataColorToken | undefined => {
+ if (fallbackSource?.overrides !== overrides || fallbackSource?.theme !== theme) {
+ fallbackSource = { overrides, theme }
+ // Completion only activates when a dashboard override actually sits on this
+ // tile; a series customization alone must not shift its neighbors' colors.
+ // Once active, customized series claim their slots like overrides do.
+ let hasDashboardOverride = false
+ const series = indexedResults.map((result) => {
+ const overrideToken =
+ findBreakdownColorConfig(
+ overrides,
+ JSON.parse(getTrendDatasetKey(result))['breakdown_value'],
+ breakdownFilter?.breakdown_type,
+ breakdownPropertyKey
+ )?.colorToken ?? null
+ hasDashboardOverride = hasDashboardOverride || !!overrideToken
+ return {
+ position: getTrendDatasetPosition(result),
+ overrideToken:
+ overrideToken ??
+ getTrendResultCustomization(resultCustomizationBy, result, resultCustomizations)
+ ?.color ??
+ null,
+ }
+ })
+ fallbackTokens = hasDashboardOverride
+ ? computeTileFallbackTokens(series, Object.keys(theme).length)
+ : new Map<number, DataColorToken>()
+ }
+ return fallbackTokens.get(getTrendDatasetPosition(dataset))
+ }
+
return (dataset: IndexedTrendResult): [DataColorTheme | null, DataColorToken | null] => {
const breakdownValue = JSON.parse(getTrendDatasetKey(dataset))['breakdown_value']
@@ -888,7 +944,8 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
const colorOverride = findBreakdownColorConfig(
logic?.values.effectiveBreakdownColors,
breakdownValue,
- breakdownFilter?.breakdown_type
+ breakdownFilter?.breakdown_type,
+ breakdownPropertyKey
)
if (colorOverride?.colorToken) {
@@ -903,6 +960,24 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
return [null, null]
}
+ // On dashboards with auto colors, series without a value override fill the
+ // palette slots the tile's overrides don't use, because the plain
+ // position-based fallback can land on the same slot as an override shown on
+ // this very chart. An explicit per-series customization still wins below.
+ if (logic?.values.autoBreakdownColorsEnabled) {
+ const customizationColor = getTrendResultCustomization(
+ resultCustomizationBy,
+ dataset,
+ resultCustomizations
+ )?.color
+ const fallbackToken = customizationColor
+ ? undefined
+ : tileFallbackToken(logic.values.effectiveBreakdownColors, theme, dataset)
+ if (fallbackToken) {
+ return [theme, fallbackToken]
+ }
+ }
+
return [
theme,
getTrendResultCustomizationColorToken(