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): auto-assign consistent breakdown colors per dashboard (#73081)

Thomas Obermüller6f146ab2ab26
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index d81c00eb3033..f9c018df1925 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -291,8 +291,12 @@ function sanitizeDashboard(dashboard: DashboardType<QueryBasedInsightModel> | nu
return null
}
+ // Remove breakdown color entries, as they carry raw breakdown values (user data) — report only their count
+ const { breakdown_colors, ...sanitizedDashboard } = dashboard
+
return {
- ...dashboard,
+ ...sanitizedDashboard,
+ breakdown_colors_count: breakdown_colors?.length ?? 0,
tiles: dashboard.tiles?.map((tile) => sanitizeTile(tile)) || [],
}
}
@@ -568,6 +572,24 @@ export interface eventUsageLogicActions {
journeyName: string
stepCount: number
}
+ reportDashboardBreakdownColorsSaved: (
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ manualCount: number,
+ autoCount: number,
+ breakdownTypes: string[]
+ ) => {
+ autoCount: number
+ breakdownTypes: string[]
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
+ manualCount: number
+ }
+ reportDashboardColorThemeSet: (
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ themeId: number | null
+ ) => {
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
+ themeId: number | null
+ }
reportDashboardDateRangeChanged: (
dashboard: DashboardType<QueryBasedInsightModel> | null,
dateFrom?: string | Dayjs | null,
@@ -2089,6 +2111,16 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
dashboard: DashboardType<QueryBasedInsightModel> | null,
action: 'shown' | 'discarded' | 'kept_editing'
) => ({ dashboard, action }),
+ reportDashboardBreakdownColorsSaved: (
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ manualCount: number,
+ autoCount: number,
+ breakdownTypes: string[]
+ ) => ({ dashboard, manualCount, autoCount, breakdownTypes }),
+ reportDashboardColorThemeSet: (
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ themeId: number | null
+ ) => ({ dashboard, themeId }),
reportDashboardRefreshed: (
dashboardId: number,
dashboard: DashboardType<QueryBasedInsightModel> | null,
@@ -3001,6 +3033,22 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
layout_zoom: layoutZoom ?? undefined,
})
},
+ reportDashboardBreakdownColorsSaved: async ({ dashboard, manualCount, autoCount, breakdownTypes }) => {
+ posthog.capture('dashboard breakdown colors saved', {
+ dashboard_id: dashboard?.id,
+ dashboard: sanitizeDashboard(dashboard),
+ manual_count: manualCount,
+ auto_count: autoCount,
+ breakdown_types: breakdownTypes,
+ })
+ },
+ reportDashboardColorThemeSet: async ({ dashboard, themeId }) => {
+ posthog.capture('dashboard color theme set', {
+ dashboard_id: dashboard?.id,
+ dashboard: sanitizeDashboard(dashboard),
+ theme_id: themeId,
+ })
+ },
reportDashboardFiltersChanged: async ({ dashboard, changeType, properties }) => {
posthog.capture('dashboard filters changed', {
dashboard_id: dashboard?.id,
diff --git a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
index e4c1610597f4..0dd8e51ea394 100644
--- a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
+++ b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
@@ -1,9 +1,8 @@
import { useActions, useValues } from 'kea'
-import { LemonLabel, LemonModal, LemonSelect } from '@posthog/lemon-ui'
+import { LemonLabel, LemonModal, LemonSelect, LemonTag } from '@posthog/lemon-ui'
import { LemonButton, LemonColorPicker, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'
-import { DataColorToken } from 'lib/colors'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import stringWithWBR from 'lib/utils/stringWithWBR'
import { formatBreakdownLabel } from 'scenes/insights/utils'
@@ -14,14 +13,12 @@ import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { BreakdownFilter } from '~/queries/schema/schema-general'
import { DashboardMode } from '~/types'
+import { BreakdownColorConfig, denormalizeBreakdownValue, findBreakdownColorConfig } from './dashboardBreakdownColors'
import { dashboardInsightColorsModalLogic } from './dashboardInsightColorsModalLogic'
import { dashboardLogic } from './dashboardLogic'
-export type BreakdownColorConfig = {
- colorToken: DataColorToken | null
- breakdownValue: string
- breakdownType: BreakdownFilter['breakdown_type']
-}
+// Re-exported for back-compat; the type lives in dashboardBreakdownColors.ts
+export type { BreakdownColorConfig }
export function DashboardInsightColorsModal(): JSX.Element {
const { isOpen, insightTilesLoading, breakdownValues } = useValues(dashboardInsightColorsModalLogic)
@@ -29,11 +26,7 @@ export function DashboardInsightColorsModal(): JSX.Element {
const { themes: _themes, themesLoading } = useValues(dataColorThemesLogic)
- const {
- temporaryBreakdownColors: dashboardBreakdownColors,
- dataColorThemeId,
- dashboardMode,
- } = useValues(dashboardLogic)
+ const { effectiveBreakdownColors, dataColorThemeId, dashboardMode } = useValues(dashboardLogic)
const { setBreakdownColorConfig, setDataColorThemeId, setDashboardMode } = useActions(dashboardLogic)
const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
@@ -41,6 +34,12 @@ export function DashboardInsightColorsModal(): JSX.Element {
const themes = _themes || []
+ const ensureEditMode = (): void => {
+ if (dashboardMode !== DashboardMode.Edit) {
+ setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ }
+ }
+
const columns: LemonTableColumns<BreakdownColorConfig> = [
{
title: 'Breakdown',
@@ -48,7 +47,7 @@ export function DashboardInsightColorsModal(): JSX.Element {
render: (_, { breakdownValue, ...config }) => {
const breakdownFilter: BreakdownFilter = { breakdown_type: config.breakdownType }
const breakdownLabel = formatBreakdownLabel(
- breakdownValue,
+ denormalizeBreakdownValue(breakdownValue),
breakdownFilter,
allCohorts?.results,
formatPropertyValueForDisplay
@@ -62,32 +61,53 @@ export function DashboardInsightColorsModal(): JSX.Element {
title: 'Color',
key: 'color',
width: 400,
- render: (_, { colorToken, ...config }) => {
+ render: (_, { colorToken, source, ...config }) => {
return (
- <LemonColorPicker
- selectedColorToken={colorToken}
- onSelectColorToken={(colorToken) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ <div className="flex items-center gap-2">
+ <LemonColorPicker
+ selectedColorToken={colorToken}
+ onSelectColorToken={(colorToken) => {
+ ensureEditMode()
+ setBreakdownColorConfig({
+ ...config,
+ colorToken,
+ source: 'manual',
+ })
+ }}
+ customButton={
+ colorToken === null ? (
+ <LemonButton type="tertiary">Customize color</LemonButton>
+ ) : undefined
}
-
- setBreakdownColorConfig({
- ...config,
- colorToken,
- })
- }}
- customButton={
- colorToken === null ? <LemonButton type="tertiary">Customize color</LemonButton> : undefined
- }
- themeId={dataColorThemeId}
- />
+ themeId={dataColorThemeId}
+ />
+ {source === 'auto' ? (
+ <LemonTag type="muted">Auto</LemonTag>
+ ) : colorToken !== null ? (
+ <LemonButton
+ size="small"
+ type="tertiary"
+ tooltip="Reset to automatic color"
+ onClick={() => {
+ ensureEditMode()
+ setBreakdownColorConfig({
+ ...config,
+ colorToken: null,
+ source: 'manual',
+ })
+ }}
+ >
+ Reset
+ </LemonButton>
+ ) : null}
+ </div>
)
},
},
]
return (
- <LemonModal title="Customize Breakdown Colors" isOpen={isOpen} onClose={hideInsightColorsModal}>
+ <LemonModal title="Customize breakdown colors" isOpen={isOpen} onClose={hideInsightColorsModal}>
<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>
@@ -96,10 +116,7 @@ export function DashboardInsightColorsModal(): JSX.Element {
value={dataColorThemeId || null}
placeholder="Defined by insight"
onChange={(id) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
- }
-
+ ensureEditMode()
setDataColorThemeId(id)
}}
loading={themesLoading}
@@ -108,30 +125,28 @@ export function DashboardInsightColorsModal(): JSX.Element {
<LemonLabel className="mt-4">Breakdown colors</LemonLabel>
<p className="text-muted-alt mb-4">
- Assign custom colors to breakdown values that will be used consistently across all insights on this
- dashboard. <i>Note: This feature currently only works for trend and step-based funnel insights.</i>
+ Breakdown values get a consistent color across all insights on this dashboard. Pick a color to pin a
+ value to it. <i>Note: This feature currently only works for trend and step-based funnel 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}
+ />
{insightTilesLoading ? (
- <div className="flex flex-col items-center">
- <p className="text-primary">Waiting for dashboard tiles to load and refresh…</p>
- </div>
- ) : (
- <>
- <LemonTable
- columns={columns}
- dataSource={breakdownValues.map((breakdownValue) => ({
- ...breakdownValue,
- colorToken:
- dashboardBreakdownColors.find(
- (c) =>
- c.breakdownValue === breakdownValue.breakdownValue &&
- c.breakdownType === breakdownValue.breakdownType
- )?.colorToken || null,
- }))}
- loading={insightTilesLoading || undefined}
- />
- </>
- )}
+ <p className="text-muted-alt mt-2">Tiles are still loading. More breakdown values may appear.</p>
+ ) : null}
</LemonModal>
)
}
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 84e2b485103b..f6a492e9ff26 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -85,7 +85,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
dashboardStreaming,
effectiveEditBarFilters,
effectiveDashboardVariableOverrides,
- temporaryBreakdownColors,
+ effectiveBreakdownColors,
dataColorThemeId,
canEditDashboard,
dashboardWidgetsEnabled,
@@ -580,7 +580,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
filtersOverride={effectiveEditBarFilters}
variablesOverride={effectiveDashboardVariableOverrides}
// :HACKY: The two props below aren't actually used in the component, but are needed to trigger a re-render
- breakdownColorOverride={temporaryBreakdownColors}
+ breakdownColorOverride={effectiveBreakdownColors}
dataColorThemeId={dataColorThemeId}
surveyOpportunity={tile.id === bestSurveyOpportunityFunnel?.id}
showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts
new file mode 100644
index 000000000000..9016fd92d3ba
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts
@@ -0,0 +1,338 @@
+import { InsightQueryNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
+import { AccessControlLevel, DashboardTile, FunnelVizType, InsightShortId, QueryBasedInsightModel } from '~/types'
+
+import {
+ BreakdownColorConfig,
+ MULTI_BREAKDOWN_SEPARATOR,
+ computeAutoBreakdownColors,
+ extractBreakdownValues,
+ findBreakdownColorConfig,
+ mergeBreakdownColorConfigs,
+} from './dashboardBreakdownColors'
+
+describe('dashboardBreakdownColors', () => {
+ const createTestTile = (
+ overrides: Partial<QueryBasedInsightModel> = {}
+ ): DashboardTile<QueryBasedInsightModel> => ({
+ id: 1,
+ layouts: {},
+ color: null,
+ insight: {
+ short_id: 'abc123' as InsightShortId,
+ id: 1,
+ name: 'Test Insight',
+ order: null,
+ result: [],
+ deleted: false,
+ saved: true,
+ created_at: '2023-01-01T00:00:00Z',
+ created_by: null,
+ is_sample: false,
+ dashboards: null,
+ dashboard_tiles: null,
+ updated_at: '2023-01-01T00:00:00Z',
+ last_modified_at: '2023-01-01T00:00:00Z',
+ last_modified_by: null,
+ query: null,
+ last_refresh: null,
+ user_access_level: AccessControlLevel.None,
+ ...overrides,
+ },
+ })
+
+ const trendsTile = (result: any[]): DashboardTile<QueryBasedInsightModel> =>
+ createTestTile({
+ result,
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery },
+ } as InsightVizNode<InsightQueryNode>,
+ })
+
+ describe('extractBreakdownValues', () => {
+ it('returns empty array for null input', () => {
+ expect(extractBreakdownValues(null, null)).toEqual([])
+ })
+
+ it('handles funnel insights with steps visualization', () => {
+ const tiles = [
+ createTestTile({
+ result: [{ breakdown_value: ['Chrome'] }, { breakdown_value: ['Firefox'] }],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.FunnelsQuery,
+ funnelsFilter: {
+ funnelVizType: FunnelVizType.Steps,
+ },
+ },
+ } as InsightVizNode<InsightQueryNode>,
+ }),
+ createTestTile({
+ result: [{ breakdown_value: 'Safari' }],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.FunnelsQuery,
+ funnelsFilter: {
+ funnelVizType: FunnelVizType.Steps,
+ },
+ },
+ } as InsightVizNode<InsightQueryNode>,
+ }),
+ ]
+
+ expect(extractBreakdownValues(tiles, null)).toEqual([
+ { breakdownValue: 'Baseline', breakdownType: 'event' },
+ { breakdownValue: 'Chrome', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
+ { breakdownValue: 'Safari', breakdownType: 'event' },
+ ])
+ })
+
+ it('handles trends insights', () => {
+ const tiles = [
+ trendsTile([
+ { action: { order: 0 }, breakdown_value: ['Chrome'], compare_label: 'previous' },
+ { action: { order: 0 }, breakdown_value: ['Firefox'], compare_label: 'previous' },
+ ]),
+ trendsTile([{ action: { order: 0 }, breakdown_value: 'Safari' }]),
+ ]
+
+ expect(extractBreakdownValues(tiles, null)).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
+ { breakdownValue: 'Safari', breakdownType: 'event' },
+ ])
+ })
+
+ it('deduplicates repeated breakdown values across tiles', () => {
+ const tiles = [
+ trendsTile([
+ { action: { order: 0 }, breakdown_value: ['Chrome'] },
+ { action: { order: 1 }, breakdown_value: ['Firefox'] },
+ ]),
+ trendsTile([
+ { action: { order: 0 }, breakdown_value: ['Chrome'] },
+ { action: { order: 1 }, breakdown_value: ['Safari'] },
+ ]),
+ ]
+
+ expect(extractBreakdownValues(tiles, null)).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event' },
+ { breakdownValue: 'Firefox', breakdownType: 'event' },
+ { breakdownValue: 'Safari', breakdownType: 'event' },
+ ])
+ })
+
+ it('stringifies numeric values so trends and funnels tiles share one entry', () => {
+ const tiles = [
+ // trends keys wrap scalars in an array; funnels keep them bare
+ trendsTile([{ action: { order: 0 }, breakdown_value: [123] }]),
+ createTestTile({
+ result: [{ breakdown_value: 123 }],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.FunnelsQuery },
+ } as InsightVizNode<InsightQueryNode>,
+ }),
+ ]
+
+ expect(extractBreakdownValues(tiles, null)).toEqual([
+ { breakdownValue: '123', breakdownType: 'event' },
+ { breakdownValue: 'Baseline', breakdownType: 'event' },
+ ])
+ })
+
+ it('ignores non-matching insight types', () => {
+ const tiles = [
+ createTestTile({
+ result: [],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.RetentionQuery },
+ } as InsightVizNode<InsightQueryNode>,
+ }),
+ ]
+ expect(extractBreakdownValues(tiles, null)).toEqual([])
+ })
+
+ it('handles cohort breakdowns', () => {
+ const cohortTile = (values: number[][]): DashboardTile<QueryBasedInsightModel> =>
+ createTestTile({
+ result: values.map((breakdown_value) => ({ action: { order: 0 }, breakdown_value })),
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ breakdownFilter: { 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' },
+ ])
+ })
+ })
+
+ describe('computeAutoBreakdownColors', () => {
+ const value = (breakdownValue: string): { breakdownValue: string; breakdownType: 'event' } => ({
+ breakdownValue,
+ breakdownType: 'event',
+ })
+
+ it('fills free slots in sorted order without touching existing configs', () => {
+ const existing: BreakdownColorConfig[] = [
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-3', source: 'manual' },
+ ]
+
+ const assigned = computeAutoBreakdownColors([value('Google'), value('Alibaba'), value('Chrome')], existing)
+
+ expect(assigned).toEqual([
+ { breakdownValue: 'Alibaba', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
+ { breakdownValue: 'Google', breakdownType: 'event', colorToken: 'preset-2', source: 'auto' },
+ ])
+ expect(existing[0].colorToken).toBe('preset-3')
+ })
+
+ 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' },
+ ]
+
+ const assigned = computeAutoBreakdownColors(
+ [value('Alibaba'), value('Bing'), value('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' },
+ ])
+ })
+
+ it('skips sentinel values', () => {
+ const assigned = computeAutoBreakdownColors(
+ [
+ value('Baseline'),
+ value('$$_posthog_breakdown_other_$$'),
+ value('$$_posthog_breakdown_null_$$'),
+ value('Chrome'),
+ ],
+ []
+ )
+
+ expect(assigned).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1', source: 'auto' },
+ ])
+ })
+
+ 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' },
+ ])
+ })
+
+ it('sizes slots to the given palette instead of the default 15 colors', () => {
+ const existing: BreakdownColorConfig[] = [
+ { breakdownValue: 'Pinned', breakdownType: 'event', colorToken: 'preset-7', source: 'manual' },
+ ]
+
+ const assigned = computeAutoBreakdownColors(
+ [value('A'), value('B'), value('C'), value('D'), value('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-1',
+ 'preset-3',
+ 'preset-4',
+ 'preset-5',
+ 'preset-1',
+ ])
+ })
+
+ it('wraps deterministically once the palette is exhausted', () => {
+ const values = Array.from({ length: 17 }, (_, i) => value(`value-${String(i + 1).padStart(2, '0')}`))
+
+ const assigned = computeAutoBreakdownColors(values, [])
+
+ 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')
+ })
+ })
+
+ describe('mergeBreakdownColorConfigs', () => {
+ it('lets earlier lists win and deduplicates by value and type', () => {
+ const merged = mergeBreakdownColorConfigs(
+ [{ breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-5', source: 'manual' }],
+ [
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1' },
+ { breakdownValue: 'Firefox', breakdownType: 'event', colorToken: 'preset-2' },
+ ]
+ )
+
+ expect(merged).toEqual([
+ { breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-5', source: 'manual' },
+ { breakdownValue: 'Firefox', breakdownType: 'event', colorToken: 'preset-2' },
+ ])
+ })
+
+ it('normalizes legacy non-string values', () => {
+ const merged = mergeBreakdownColorConfigs([
+ { breakdownValue: 123 as any, breakdownType: 'event', colorToken: 'preset-1' },
+ ])
+
+ expect(merged).toEqual([{ breakdownValue: '123', breakdownType: 'event', colorToken: 'preset-1' }])
+ })
+ })
+
+ describe('findBreakdownColorConfig', () => {
+ const configs: BreakdownColorConfig[] = [
+ { breakdownValue: '123', breakdownType: 'event', colorToken: 'preset-1' },
+ { breakdownValue: 'a::b', breakdownType: 'event', colorToken: 'preset-2' },
+ { breakdownValue: 'Chrome', breakdownType: 'person', colorToken: 'preset-3' },
+ {
+ breakdownValue: ['a', 'b'].join(MULTI_BREAKDOWN_SEPARATOR),
+ breakdownType: 'event',
+ colorToken: 'preset-4',
+ },
+ ]
+
+ it.each([
+ ['numeric dataset value matches a stringified config', 123, 'event', 'preset-1'],
+ [
+ 'multi-breakdown array matches its own entry, not a scalar containing "::"',
+ ['a', 'b'],
+ 'event',
+ 'preset-4',
+ ],
+ ['scalar containing "::" matches its own entry, not a multi-breakdown array', 'a::b', 'event', 'preset-2'],
+ ['breakdown type must match', 'Chrome', 'event', undefined],
+ ['type defaults to event when not provided', '123', undefined, 'preset-1'],
+ ] as const)('%s', (_name, breakdownValue, breakdownType, expectedToken) => {
+ expect(findBreakdownColorConfig(configs, breakdownValue, breakdownType as any)?.colorToken).toEqual(
+ expectedToken
+ )
+ })
+
+ it('returns undefined for null or undefined dataset values', () => {
+ expect(findBreakdownColorConfig(configs, undefined, 'event')).toBeUndefined()
+ expect(findBreakdownColorConfig(configs, null, 'event')).toBeUndefined()
+ })
+ })
+})
diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
new file mode 100644
index 000000000000..039c776b480b
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
@@ -0,0 +1,217 @@
+import { DataColorToken, dataColorVars } from 'lib/colors'
+import {
+ getFunnelDatasetKey,
+ getTrendDatasetKey,
+ isNullBreakdown,
+ isOtherBreakdown,
+ sortCohorts,
+} from 'scenes/insights/utils'
+
+import { BreakdownFilter } from '~/queries/schema/schema-general'
+import { isFunnelsQuery, isInsightVizNode, isTrendsQuery } from '~/queries/utils'
+import { CohortType, DashboardTile, FunnelVizType, QueryBasedInsightModel } from '~/types'
+
+export type BreakdownColorSource = 'auto' | 'manual'
+
+export type BreakdownColorConfig = {
+ colorToken: DataColorToken | null
+ breakdownValue: string
+ breakdownType: BreakdownFilter['breakdown_type']
+ /** Entries without a source predate auto-assignment and are treated as manual pins. */
+ source?: BreakdownColorSource
+}
+
+export type BreakdownValueAndType = Pick<BreakdownColorConfig, 'breakdownValue' | 'breakdownType'>
+
+/** Label of the synthetic baseline row funnel insights contribute to the colors table. */
+export const FUNNEL_BASELINE_BREAKDOWN_LABEL = 'Baseline'
+
+/** Joins the parts of a multi-breakdown value in normalized form. A control character scalar
+ * values can't realistically contain, so an array like ["a", "b"] never collides with a scalar
+ * value like "a::b" (the display separator, which does occur in real property values). */
+export const MULTI_BREAKDOWN_SEPARATOR = '\u001f'
+
+/** 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. */
+export function normalizeBreakdownValue(value: unknown): string | null {
+ if (value == null) {
+ return null
+ }
+ return Array.isArray(value) ? value.join(MULTI_BREAKDOWN_SEPARATOR) : String(value)
+}
+
+/** Restores the array form of a normalized multi-breakdown value so labels format each part. */
+export function denormalizeBreakdownValue(value: string): string | string[] {
+ return value.includes(MULTI_BREAKDOWN_SEPARATOR) ? value.split(MULTI_BREAKDOWN_SEPARATOR) : value
+}
+
+export function breakdownConfigMatches(
+ config: BreakdownValueAndType,
+ breakdownValue: unknown,
+ breakdownType: BreakdownFilter['breakdown_type'] | null | undefined
+): boolean {
+ const normalized = normalizeBreakdownValue(breakdownValue)
+ return (
+ normalized != null &&
+ normalizeBreakdownValue(config.breakdownValue) === normalized &&
+ config.breakdownType === (breakdownType ?? 'event')
+ )
+}
+
+export function findBreakdownColorConfig(
+ configs: BreakdownColorConfig[] | undefined | null,
+ breakdownValue: unknown,
+ breakdownType: BreakdownFilter['breakdown_type'] | null | undefined
+): BreakdownColorConfig | undefined {
+ if (normalizeBreakdownValue(breakdownValue) == null) {
+ return undefined
+ }
+ return configs?.find((config) => breakdownConfigMatches(config, breakdownValue, breakdownType))
+}
+
+/** 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. */
+export function mergeBreakdownColorConfigs(...configLists: BreakdownColorConfig[][]): BreakdownColorConfig[] {
+ const merged: BreakdownColorConfig[] = []
+ for (const configs of configLists) {
+ for (const config of configs) {
+ const breakdownValue = normalizeBreakdownValue(config.breakdownValue)
+ if (breakdownValue == null) {
+ continue
+ }
+ if (!merged.some((c) => breakdownConfigMatches(c, breakdownValue, config.breakdownType))) {
+ merged.push({ ...config, breakdownValue })
+ }
+ }
+ }
+ return merged
+}
+
+export function extractBreakdownValues(
+ insightTiles: DashboardTile<QueryBasedInsightModel>[] | null,
+ cohorts: CohortType[] | null
+): BreakdownValueAndType[] {
+ if (insightTiles == null) {
+ return []
+ }
+
+ return insightTiles
+ .flatMap((tile) => {
+ if (isInsightVizNode(tile.insight?.query)) {
+ const querySource = tile.insight?.query.source
+ if (
+ isFunnelsQuery(querySource) &&
+ (querySource.funnelsFilter?.funnelVizType === undefined ||
+ querySource.funnelsFilter?.funnelVizType === FunnelVizType.Steps)
+ ) {
+ const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
+ const breakdownValues: (BreakdownValueAndType | null)[] = [
+ {
+ 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 }
+ }) || []
+ )
+ }
+ return []
+ }
+ return []
+ })
+ .filter((value): value is BreakdownValueAndType => value != null)
+ .reduce<BreakdownValueAndType[]>((acc, curr) => {
+ if (!acc.some((x) => x.breakdownValue === curr.breakdownValue && x.breakdownType === curr.breakdownType)) {
+ acc.push(curr)
+ }
+ 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
+ }
+
+ return String(a.breakdownValue).localeCompare(String(b.breakdownValue))
+ })
+}
+
+/** Sentinel rows keep their built-in muted/fixed treatment instead of an assigned palette color. */
+export function isAutoAssignableBreakdownValue(breakdownValue: string): boolean {
+ return (
+ breakdownValue !== FUNNEL_BASELINE_BREAKDOWN_LABEL &&
+ !isOtherBreakdown(breakdownValue) &&
+ !isNullBreakdown(breakdownValue)
+ )
+}
+
+const PRESET_TOKEN_REGEX = /^preset-(\d+)$/
+
+/** Assign palette slots to breakdown values that no existing config covers.
+ *
+ * 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.
+ */
+export function computeAutoBreakdownColors(
+ visibleValues: BreakdownValueAndType[],
+ existingConfigs: BreakdownColorConfig[],
+ paletteSize: number = dataColorVars.length
+): BreakdownColorConfig[] {
+ const usedSlots = new Set<number>()
+ for (const config of existingConfigs) {
+ const match = config.colorToken?.match(PRESET_TOKEN_REGEX)
+ if (match) {
+ usedSlots.add((Number(match[1]) - 1) % paletteSize)
+ }
+ }
+
+ const candidates = visibleValues
+ .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)
+ )
+
+ 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,
+ source: 'auto',
+ })
+ }
+ return assigned
+}
diff --git a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.test.ts b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.test.ts
deleted file mode 100644
index 783e3ca70be5..000000000000
--- a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.test.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-import { InsightQueryNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
-import { AccessControlLevel, DashboardTile, FunnelVizType, InsightShortId, QueryBasedInsightModel } from '~/types'
-
-import { extractBreakdownValues } from './dashboardInsightColorsModalLogic'
-
-describe('extractBreakdownValues', () => {
- const createTestTile = (
- overrides: Partial<QueryBasedInsightModel> = {}
- ): DashboardTile<QueryBasedInsightModel> => ({
- id: 1,
- layouts: {},
- color: null,
- insight: {
- short_id: 'abc123' as InsightShortId,
- id: 1,
- name: 'Test Insight',
- order: null,
- result: [],
- deleted: false,
- saved: true,
- created_at: '2023-01-01T00:00:00Z',
- created_by: null,
- is_sample: false,
- dashboards: null,
- dashboard_tiles: null,
- updated_at: '2023-01-01T00:00:00Z',
- last_modified_at: '2023-01-01T00:00:00Z',
- last_modified_by: null,
- query: null,
- last_refresh: null,
- user_access_level: AccessControlLevel.None,
- ...overrides,
- },
- })
-
- it('returns empty array for null input', () => {
- expect(extractBreakdownValues(null, null)).toEqual([])
- })
-
- it('handles funnel insights with steps visualization', () => {
- const tiles = [
- createTestTile({
- result: [{ breakdown_value: ['Chrome'] }, { breakdown_value: ['Firefox'] }],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.FunnelsQuery,
- funnelsFilter: {
- funnelVizType: FunnelVizType.Steps,
- },
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- createTestTile({
- result: [{ breakdown_value: 'Safari' }],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.FunnelsQuery,
- funnelsFilter: {
- funnelVizType: FunnelVizType.Steps,
- },
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- ]
-
- const result = extractBreakdownValues(tiles, null)
-
- expect(result).toEqual([
- { breakdownValue: 'Baseline', breakdownType: 'event' },
- { breakdownValue: 'Chrome', breakdownType: 'event' },
- { breakdownValue: 'Firefox', breakdownType: 'event' },
- { breakdownValue: 'Safari', breakdownType: 'event' },
- ])
- })
-
- it('handles trends insights', () => {
- const tiles = [
- createTestTile({
- result: [
- { action: { order: 0 }, breakdown_value: ['Chrome'], compare_label: 'previous' },
- { action: { order: 0 }, breakdown_value: ['Firefox'], compare_label: 'previous' },
- ],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- createTestTile({
- result: [{ action: { order: 0 }, breakdown_value: 'Safari' }],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- ]
-
- const result = extractBreakdownValues(tiles, null)
-
- expect(result).toEqual([
- { breakdownValue: 'Chrome', breakdownType: 'event' },
- { breakdownValue: 'Firefox', breakdownType: 'event' },
- { breakdownValue: 'Safari', breakdownType: 'event' },
- ])
- })
-
- it('deduplicates repeated breakdown values across tiles', () => {
- const tiles = [
- createTestTile({
- result: [
- { action: { order: 0 }, breakdown_value: ['Chrome'] },
- { action: { order: 1 }, breakdown_value: ['Firefox'] },
- ],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- createTestTile({
- result: [
- { action: { order: 0 }, breakdown_value: ['Chrome'] },
- { action: { order: 1 }, breakdown_value: ['Safari'] },
- ],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- ]
-
- const result = extractBreakdownValues(tiles, null)
-
- expect(result).toEqual([
- { breakdownValue: 'Chrome', breakdownType: 'event' },
- { breakdownValue: 'Firefox', breakdownType: 'event' },
- { breakdownValue: 'Safari', breakdownType: 'event' },
- ])
- })
-
- it('ignores non-matching insight types', () => {
- const tiles = [
- createTestTile({
- result: [],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.RetentionQuery,
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- ]
- expect(extractBreakdownValues(tiles, null)).toEqual([])
- })
-
- it('handles cohort breakdowns', () => {
- const tiles = [
- createTestTile({
- result: [
- { action: { order: 0 }, breakdown_value: [1] },
- { action: { order: 0 }, breakdown_value: [2] },
- ],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- breakdownFilter: {
- breakdown_type: 'cohort',
- },
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- createTestTile({
- result: [{ action: { order: 0 }, breakdown_value: [3] }],
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- breakdownFilter: {
- breakdown_type: 'cohort',
- },
- },
- } as InsightVizNode<InsightQueryNode>,
- }),
- ]
-
- const result = extractBreakdownValues(tiles, null)
-
- expect(result).toEqual([
- { breakdownValue: '1', breakdownType: 'cohort' },
- { breakdownValue: '2', breakdownType: 'cohort' },
- { breakdownValue: '3', breakdownType: 'cohort' },
- ])
- })
-})
diff --git a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
index 345ac255b9d6..b30be535079a 100644
--- a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
@@ -1,87 +1,15 @@
import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
-import { getFunnelDatasetKey, getTrendDatasetKey, sortCohorts } from 'scenes/insights/utils'
-
import { cohortsModel } from '~/models/cohortsModel'
-import { isFunnelsQuery, isInsightVizNode, isTrendsQuery } from '~/queries/utils'
-import { CohortType, DashboardTile, FunnelVizType, QueryBasedInsightModel } from '~/types'
+import { CohortType, DashboardTile, QueryBasedInsightModel } from '~/types'
import type { CountedPaginatedResponse } from '../../lib/api'
-import { BreakdownColorConfig } from './DashboardInsightColorsModal'
+import { BreakdownValueAndType, extractBreakdownValues } from './dashboardBreakdownColors'
import { dashboardLogic } from './dashboardLogic'
-export type BreakdownValueAndType = Omit<BreakdownColorConfig, 'colorToken'>
-
-export function extractBreakdownValues(
- insightTiles: DashboardTile<QueryBasedInsightModel>[] | null,
- cohorts: CohortType[] | null
-): BreakdownValueAndType[] {
- if (insightTiles == null) {
- return []
- }
-
- return insightTiles
- .flatMap((tile) => {
- if (isInsightVizNode(tile.insight?.query)) {
- const querySource = tile.insight?.query.source
- if (
- isFunnelsQuery(querySource) &&
- (querySource.funnelsFilter?.funnelVizType === undefined ||
- querySource.funnelsFilter?.funnelVizType === FunnelVizType.Steps)
- ) {
- const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
- const breakdownValues: BreakdownValueAndType[] = [
- {
- breakdownValue: 'Baseline',
- breakdownType,
- },
- ]
- tile.insight?.result?.forEach((result: any) => {
- const key = getFunnelDatasetKey(result)
- const keyParts = JSON.parse(key)
- const breakdownValue = keyParts['breakdown_value']
- breakdownValues.push({
- breakdownValue: Array.isArray(breakdownValue) ? breakdownValue.join('::') : breakdownValue,
- breakdownType,
- })
- })
- return breakdownValues
- } else if (isTrendsQuery(querySource)) {
- const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'
- return tile.insight?.result?.map((result: any) => {
- const key = getTrendDatasetKey(result)
- const keyParts = JSON.parse(key)
- const breakdownValue = keyParts['breakdown_value']
- return {
- breakdownValue: Array.isArray(breakdownValue) ? breakdownValue.join('::') : breakdownValue,
- breakdownType,
- }
- })
- }
- return []
- }
- return []
- })
- .filter((value) => value != null)
- .reduce<BreakdownValueAndType[]>((acc, curr) => {
- if (!acc.some((x) => x.breakdownValue === curr.breakdownValue && x.breakdownType === curr.breakdownType)) {
- acc.push(curr)
- }
- 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
- }
-
- return String(a.breakdownValue).localeCompare(String(b.breakdownValue))
- })
-}
+// Re-exported for back-compat; the implementation lives in dashboardBreakdownColors.ts
+export { extractBreakdownValues }
+export type { BreakdownValueAndType }
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardInsightColorsModalLogicValues {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index d72033288f54..e69f1ed6ac7f 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -199,6 +199,15 @@ describe('dashboardLogic', () => {
{ ...dashboards[10] },
],
},
+ '/api/environments/:team_id/data_color_themes/': [
+ {
+ id: 1,
+ name: 'Default theme',
+ colors: Array.from({ length: 15 }, (_, i) => `#0000${String(i).padStart(2, '0')}`),
+ is_global: true,
+ },
+ { id: 123, name: 'Two-color theme', colors: ['#ff0000', '#00ff00'], is_global: false },
+ ],
'/api/environments/:team_id/insights/1001/': () => [200, { ...insights['1001'] }],
'/api/environments/:team_id/insights/800/': () => [200, { ...insights['800'] }],
'/api/environments/:team_id/insights/:id/': ({ request, params }) => {
@@ -412,7 +421,11 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setBreakdownColorConfig({ breakdownValue: 'x', color: 'red' } as any)
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'x',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ })
}).toFinishAllListeners()
jest.spyOn(api, 'update')
@@ -425,7 +438,151 @@ describe('dashboardLogic', () => {
expect(api.update).toHaveBeenCalledWith(
`api/environments/${MOCK_TEAM_ID}/dashboards/5`,
expect.objectContaining({
- breakdown_colors: expect.any(Array),
+ breakdown_colors: expect.arrayContaining([
+ expect.objectContaining({ breakdownValue: 'x', colorToken: 'preset-1' }),
+ ]),
+ })
+ )
+ })
+
+ it('discarding edit mode reverts unsaved color edits', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'x',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ })
+ logic.actions.setDataColorThemeId(123)
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.effectiveBreakdownColors.some((c: { breakdownValue: string }) => c.breakdownValue === 'x')
+ ).toBe(true)
+ expect(logic.values.dataColorThemeId).toBe(123)
+ expect(logic.values.hasUnsavedColorChanges).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.effectiveBreakdownColors.some((c: { breakdownValue: string }) => c.breakdownValue === 'x')
+ ).toBe(false)
+ expect(logic.values.dataColorThemeId).toBe(logic.values.dashboard?.data_color_theme_id ?? null)
+ expect(logic.values.hasUnsavedColorChanges).toBe(false)
+ })
+
+ it('auto-assigns breakdown colors only behind the dashboard colors flag', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const tileInsight = logic.values.dashboard!.tiles.find((t) => !!t.insight)!.insight!
+ const insightWithBreakdowns = {
+ ...tileInsight,
+ dashboards: [5],
+ dashboard_tiles: [{ id: 1, dashboard_id: 5 }],
+ result: [
+ { action: { order: 0 }, breakdown_value: ['Chrome'] },
+ { action: { order: 0 }, breakdown_value: ['Firefox'] },
+ ],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [] },
+ } as InsightVizNode<TrendsQuery>,
+ }
+
+ await expectLogic(logic, () => {
+ dashboardsModel.actions.updateDashboardInsight(insightWithBreakdowns)
+ }).toFinishAllListeners()
+
+ expect(logic.values.effectiveBreakdownColors).toEqual([])
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]: true,
+ })
+
+ expect(logic.values.effectiveBreakdownColors).toEqual([
+ expect.objectContaining({ breakdownValue: 'Chrome', colorToken: 'preset-1', source: 'auto' }),
+ expect.objectContaining({ breakdownValue: 'Firefox', colorToken: 'preset-2', source: 'auto' }),
+ ])
+ })
+
+ it('wraps auto-assigned colors at the active theme palette size', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]: true,
+ })
+
+ const tileInsight = logic.values.dashboard!.tiles.find((t) => !!t.insight)!.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>,
+ })
+ logic.actions.setDataColorThemeId(123)
+ }).toFinishAllListeners()
+
+ expect(logic.values.effectiveBreakdownColors).toEqual([
+ expect.objectContaining({ breakdownValue: 'Chrome', colorToken: 'preset-1' }),
+ expect.objectContaining({ breakdownValue: 'Firefox', colorToken: 'preset-2' }),
+ // wraps at the two-color theme's palette size, not at the default 15
+ expect.objectContaining({ breakdownValue: 'Safari', colorToken: 'preset-1' }),
+ ])
+ })
+
+ it('saving while tiles load persists unsaved pins but neither materializes nor prunes auto colors', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]: true,
+ })
+
+ const tileInsight = logic.values.dashboard!.tiles.find((t) => !!t.insight)!.insight!
+ await expectLogic(logic, () => {
+ dashboardsModel.actions.updateDashboardInsight({
+ ...tileInsight,
+ dashboards: [5],
+ dashboard_tiles: [{ id: 1, dashboard_id: 5 }],
+ result: [{ action: { order: 0 }, breakdown_value: ['Chrome'] }],
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [] },
+ } as InsightVizNode<TrendsQuery>,
+ })
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'pinned',
+ breakdownType: 'event',
+ colorToken: 'preset-5',
+ })
+ }).toFinishAllListeners()
+
+ // hold a tile in a loading state, so the visible breakdown values are incomplete
+ logic.actions.setRefreshStatus(tileInsight.short_id, true)
+ expect(logic.values.itemsLoading).toBe(true)
+
+ jest.spyOn(api, 'update')
+
+ await expectLogic(logic, () => {
+ logic.actions.saveEditModeChanges()
+ }).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledWith(
+ `api/environments/${MOCK_TEAM_ID}/dashboards/5`,
+ expect.objectContaining({
+ // only the pin — no auto entry materialized from the partially loaded tiles
+ breakdown_colors: [expect.objectContaining({ breakdownValue: 'pinned', colorToken: 'preset-5' })],
})
)
})
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 08a6798b9197..0c481febc28f 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -115,8 +115,14 @@ import type { Node } from '../../queries/schema/schema-general'
import { getResponseBytes, sortDayJsDates } from '../insights/utils'
import { filterVariablesReferencedInQuery } from '../insights/utils/queryUtils'
import { teamLogic } from '../teamLogic'
+import {
+ BreakdownColorConfig,
+ computeAutoBreakdownColors,
+ extractBreakdownValues,
+ findBreakdownColorConfig,
+ mergeBreakdownColorConfigs,
+} from './dashboardBreakdownColors'
import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from './dashboardConstants'
-import { BreakdownColorConfig } from './DashboardInsightColorsModal'
import {
BREAKPOINT_COLUMN_COUNTS,
DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES,
@@ -269,6 +275,7 @@ export interface dashboardLogicValues {
dashboardWidgetsEnabled: boolean
dataColorTheme: DataColorTheme | null
dataColorThemeId: number | null
+ effectiveBreakdownColors: BreakdownColorConfig[]
effectiveDashboardVariableOverrides: {
[x: string]: HogQLVariable
}
@@ -283,6 +290,7 @@ export interface dashboardLogicValues {
externalFilters: DashboardFilter
filtersOverrideForLoad: DashboardFilter
hasIntermittentFilters: boolean
+ hasUnsavedColorChanges: boolean
hasUnsavedLayoutChanges: boolean
hasUrlFilters: boolean
hasVariables: boolean
@@ -331,6 +339,9 @@ export interface dashboardLogicValues {
sortedDates: Dayjs[]
subscriptionId: number | 'new' | null
temporaryBreakdownColors: BreakdownColorConfig[]
+ temporaryDataColorThemeId: {
+ themeId: number | null
+ } | null
terraformModalOpen: boolean
textTileId: number | 'new' | null
textTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[]
@@ -1079,10 +1090,31 @@ export interface dashboardLogicMeta {
sidePanelContext: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
) => SidePanelSceneContext | null
+ dataColorThemeId: (
+ temporaryDataColorThemeId: {
+ themeId: number | null
+ } | null,
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
+ ) => number | null
dataColorTheme: (
dataColorThemeId: number | null,
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null // dataThemeLogic
) => DataColorTheme | null
+ effectiveBreakdownColors: (
+ temporaryBreakdownColors: BreakdownColorConfig[],
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
+ insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[],
+ itemsLoading: boolean,
+ featureFlags: FeatureFlagsSet,
+ dataColorTheme: DataColorTheme | null
+ ) => BreakdownColorConfig[]
+ hasUnsavedColorChanges: (
+ temporaryBreakdownColors: BreakdownColorConfig[],
+ temporaryDataColorThemeId: {
+ themeId: number | null
+ } | null,
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
+ ) => boolean
maxContext: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
) => MaxContextInput[]
@@ -1406,10 +1438,17 @@ export const dashboardLogic = kea<dashboardLogicType>([
persistedVariables,
values.effectiveDashboardVariableOverrides || {}
)
- const breakdownColorsChanged = !equal(
- persistedBreakdownColors,
- values.temporaryBreakdownColors || []
- )
+ // 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
+ ? mergeBreakdownColorConfigs(
+ values.temporaryBreakdownColors,
+ persistedBreakdownColors
+ ).filter((config) => !!config.colorToken)
+ : values.effectiveBreakdownColors
+ const breakdownColorsChanged = !equal(persistedBreakdownColors, breakdownColorsToSave)
const themeChanged = (values.dataColorThemeId ?? null) !== persistedThemeId
const layoutsChanged = (currentDashboard.tiles || []).some((tile) => {
@@ -1441,11 +1480,25 @@ export const dashboardLogic = kea<dashboardLogicType>([
{
filters: values.effectiveEditBarFilters,
variables: values.effectiveDashboardVariableOverrides,
- breakdown_colors: values.temporaryBreakdownColors,
+ breakdown_colors: breakdownColorsToSave,
data_color_theme_id: values.dataColorThemeId,
tiles: layoutsToUpdate,
}
)
+ if (breakdownColorsChanged) {
+ eventUsageLogic.actions.reportDashboardBreakdownColorsSaved(
+ values.dashboard,
+ breakdownColorsToSave.filter((c) => c.source !== 'auto').length,
+ breakdownColorsToSave.filter((c) => c.source === 'auto').length,
+ Array.from(new Set(breakdownColorsToSave.map((c) => String(c.breakdownType))))
+ )
+ }
+ if (themeChanged) {
+ eventUsageLogic.actions.reportDashboardColorThemeSet(
+ values.dashboard,
+ values.dataColorThemeId
+ )
+ }
actions.resetUrlFilters()
actions.resetUrlVariables()
if (shouldRefreshTilesAfterSave) {
@@ -1731,26 +1784,34 @@ export const dashboardLogic = kea<dashboardLogicType>([
}),
},
],
+ // Unsaved color edits only — merged over dashboard.breakdown_colors in effectiveBreakdownColors
temporaryBreakdownColors: [
[] as BreakdownColorConfig[],
{
setBreakdownColorConfig: (state, { config }) => {
- const existingConfigIndex = state.findIndex((c) => c.breakdownValue === config.breakdownValue)
+ const existingConfigIndex = state.findIndex(
+ (c) =>
+ String(c.breakdownValue) === String(config.breakdownValue) &&
+ c.breakdownType === config.breakdownType
+ )
if (existingConfigIndex >= 0) {
return [...state.slice(0, existingConfigIndex), config, ...state.slice(existingConfigIndex + 1)]
}
return [...state, config]
},
- loadDashboardSuccess: (state, { dashboard }) => {
- return [...state, ...(dashboard?.breakdown_colors ?? [])]
- },
+ // Cleared on discard only. After a successful save the edits match what's persisted,
+ // and a failed save (which also fires saveEditModeChangesSuccess) must keep them.
+ setDashboardMode: (state, { source }) =>
+ source === DashboardEventSource.DashboardHeaderDiscardChanges ? [] : state,
},
],
- dataColorThemeId: [
- null as number | null,
+ // Unsaved theme edit; null means untouched, so clearing the theme is distinguishable
+ temporaryDataColorThemeId: [
+ null as { themeId: number | null } | null,
{
- setDataColorThemeId: (_, { dataColorThemeId }) => dataColorThemeId || null,
- loadDashboardSuccess: (_, { dashboard }) => dashboard?.data_color_theme_id || null,
+ setDataColorThemeId: (_, { dataColorThemeId }) => ({ themeId: dataColorThemeId || null }),
+ setDashboardMode: (state, { source }) =>
+ source === DashboardEventSource.DashboardHeaderDiscardChanges ? null : state,
},
],
layoutZoom: [
@@ -2835,6 +2896,16 @@ export const dashboardLogic = kea<dashboardLogicType>([
: null
},
],
+ dataColorThemeId: [
+ (s) => [s.temporaryDataColorThemeId, s.dashboard],
+ (
+ temporaryDataColorThemeId: { themeId: number | null } | null,
+ dashboard: DashboardType<QueryBasedInsightModel> | null
+ ): number | null =>
+ temporaryDataColorThemeId
+ ? temporaryDataColorThemeId.themeId
+ : (dashboard?.data_color_theme_id ?? null),
+ ],
dataColorTheme: [
(s) => [s.dataColorThemeId, s.getTheme],
(
@@ -2842,6 +2913,79 @@ export const dashboardLogic = kea<dashboardLogicType>([
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null
): DataColorTheme | null => getTheme(dataColorThemeId),
],
+ // 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.
+ effectiveBreakdownColors: [
+ (s) => [
+ s.temporaryBreakdownColors,
+ s.dashboard,
+ s.insightTiles,
+ s.itemsLoading,
+ s.featureFlags,
+ s.dataColorTheme,
+ ],
+ (
+ temporaryBreakdownColors: BreakdownColorConfig[],
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ insightTiles: DashboardTile<QueryBasedInsightModel>[] | null,
+ itemsLoading: boolean,
+ featureFlags: FeatureFlagsSet,
+ dataColorTheme: DataColorTheme | null
+ ): BreakdownColorConfig[] => {
+ const merged = mergeBreakdownColorConfigs(
+ temporaryBreakdownColors,
+ dashboard?.breakdown_colors ?? []
+ ).filter((config) => !!config.colorToken)
+
+ if (!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_DASHBOARD_COLORS]) {
+ 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
+ ? merged
+ : merged.filter(
+ (config) =>
+ config.source !== 'auto' ||
+ visibleValues.some(
+ (value) =>
+ value.breakdownValue === config.breakdownValue &&
+ value.breakdownType === config.breakdownType
+ )
+ )
+ // 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)]
+ },
+ ],
+ hasUnsavedColorChanges: [
+ (s) => [s.temporaryBreakdownColors, s.temporaryDataColorThemeId, s.dashboard],
+ (
+ temporaryBreakdownColors: BreakdownColorConfig[],
+ temporaryDataColorThemeId: { themeId: number | null } | null,
+ dashboard: DashboardType<QueryBasedInsightModel> | null
+ ): boolean => {
+ const persisted = dashboard?.breakdown_colors ?? []
+ const colorsChanged = temporaryBreakdownColors.some((config) => {
+ const persistedConfig = findBreakdownColorConfig(
+ persisted,
+ config.breakdownValue,
+ config.breakdownType
+ )
+ return config.colorToken
+ ? persistedConfig?.colorToken !== config.colorToken
+ : !!persistedConfig?.colorToken
+ })
+ const themeChanged =
+ temporaryDataColorThemeId !== null &&
+ (temporaryDataColorThemeId.themeId ?? null) !== (dashboard?.data_color_theme_id ?? null)
+ return colorsChanged || themeChanged
+ },
+ ],
maxContext: [
(s) => [s.dashboard],
(dashboard: DashboardType<QueryBasedInsightModel> | null): MaxContextInput[] => {
@@ -3760,15 +3904,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
const discard = (): void =>
actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
const promptEnabled = !!values.featureFlags[FEATURE_FLAGS.DASHBOARD_LAYOUT_DISCARD_PROMPT]
- if (!promptEnabled || !values.hasUnsavedLayoutChanges) {
+ if (!promptEnabled || !(values.hasUnsavedLayoutChanges || values.hasUnsavedColorChanges)) {
discard()
return
}
eventUsageLogic.actions.reportDashboardEditModeDiscardPrompt(values.dashboard, 'shown')
LemonDialog.open({
- title: 'Discard layout changes?',
+ title: 'Discard unsaved changes?',
description:
- 'You have moved tiles around but not saved. If you discard now, the layout will revert to its last saved state.',
+ 'You have unsaved layout or color changes. If you discard now, the dashboard will revert to its last saved state.',
primaryButton: {
children: 'Discard changes',
status: 'danger',
diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.ts
index c74a788a0be3..16739d4fa5f3 100644
--- a/frontend/src/scenes/funnels/funnelDataLogic.ts
+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts
@@ -5,6 +5,7 @@ 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 { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { AGGREGATION_LABEL_FOR_CUSTOM_DATA_WAREHOUSE } from 'scenes/insights/filters/aggregationTargetUtils'
@@ -1247,18 +1248,14 @@ export const funnelDataLogic = kea<funnelDataLogicType>([
return (
dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics
): [DataColorTheme | null, DataColorToken | null] => {
- // stringified breakdown value
- const key = getFunnelDatasetKey(dataset)
- let breakdownValue = JSON.parse(key)['breakdown_value']
- breakdownValue = Array.isArray(breakdownValue) ? breakdownValue.join('::') : breakdownValue
+ const breakdownValue = JSON.parse(getFunnelDatasetKey(dataset))['breakdown_value']
// dashboard color overrides
const logic = dashboardLogic.findMounted({ id: props.dashboardId })
- const dashboardBreakdownColors = logic?.values.temporaryBreakdownColors
- const colorOverride = dashboardBreakdownColors?.find(
- (config) =>
- config.breakdownValue === breakdownValue &&
- config.breakdownType === (breakdownFilter?.breakdown_type ?? 'event')
+ const colorOverride = findBreakdownColorConfig(
+ logic?.values.effectiveBreakdownColors,
+ breakdownValue,
+ breakdownFilter?.breakdown_type
)
if (colorOverride?.colorToken) {
diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.ts
index 5d1109bb310a..1d7c7263b049 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.ts
@@ -3,6 +3,7 @@ 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 { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { getColorFromToken } from 'scenes/dataThemeLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -873,18 +874,14 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
| import('~/queries/schema/schema-general').WebStatsTableQuery
) => {
return (dataset: IndexedTrendResult): [DataColorTheme | null, DataColorToken | null] => {
- // stringified breakdown value
- const key = getTrendDatasetKey(dataset)
- let breakdownValue = JSON.parse(key)['breakdown_value']
- breakdownValue = Array.isArray(breakdownValue) ? breakdownValue.join('::') : breakdownValue
+ const breakdownValue = JSON.parse(getTrendDatasetKey(dataset))['breakdown_value']
// dashboard color overrides
const logic = dashboardLogic.findMounted({ id: props.dashboardId })
- const dashboardBreakdownColors = logic?.values.temporaryBreakdownColors
- const colorOverride = dashboardBreakdownColors?.find(
- (config) =>
- config.breakdownValue === breakdownValue &&
- config.breakdownType === (breakdownFilter?.breakdown_type ?? 'event')
+ const colorOverride = findBreakdownColorConfig(
+ logic?.values.effectiveBreakdownColors,
+ breakdownValue,
+ breakdownFilter?.breakdown_type
)
if (colorOverride?.colorToken) {