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(marketing): preserve dashboard navigation in URLs (#104756)

Javier Bahamondes88cc946e400e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d52a0e14ab7a..2448b45d08e1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5516,6 +5516,14 @@ snapshots:
hash: v1.k794b7964.892b971ab555f6d1ca2e0fa85f9a9866e3e5b8fd2843db239963ee69d0557810.JMoDrmwxxF3X_fUQL4s76kPCprGp3yU0oyOPqLf8Smw
marketing-analytics-dashboard-metric-cards--narrow--light:
hash: v1.k794b7964.19970bb1bed82447960aefd0360d530aacf7953ad0aed733f9e3cbb2136dd4c8.qWkLBIG4xUN4Qp39pJnDkjC8z0-DunhMLPxYC-o5KZA
+ marketing-analytics-dashboard-section-switcher--interactive-navigation--dark:
+ hash: v1.k794b7964.2fe3cc126cedcb557e16085f3ded5054e98c699e5f0ba98435273de51ddcf248.fDtABuH6P0Lp-EO3fMPs5xxxtU7g6kzS_eWIAlr4Yrw
+ marketing-analytics-dashboard-section-switcher--interactive-navigation--light:
+ hash: v1.k794b7964.39bc0a8e67496a7645071d8acebab20a6e52b70a8e111d087c57deac5e6804da.BxJIbgasGkapMR2rHPihKjiTEyYy77Y35tedIfazYvE
+ marketing-analytics-dashboard-section-switcher--narrow--dark:
+ hash: v1.k794b7964.7f9cf9b30f89933e7d0650da0414ee7001f9856d8717bd69af2f2880873b3c16.MX2GsV1y9zfHzEIAY20aKtFbaHkvUzKobcpjYb25bqI
+ marketing-analytics-dashboard-section-switcher--narrow--light:
+ hash: v1.k794b7964.c0d4b116a5afbe3e5b6b6159d519b54c08071f14cb9824596b1ce10304af6b69.7J099ANtsc1tVP_psTgnMCCvHgRV-YihqS_-YxpXs1o
marketing-analytics-failed-queries--attribution-query-failure--dark:
hash: v1.k794b7964.b84b7a281d0a4bf86c5d9e87d75e3a6e360b56afbc434addf7c5e32ac21b8803.lf_xTXYsVyVEYRWZlwoM7aaBgv6HpRrINhoriSoE0Us
marketing-analytics-failed-queries--attribution-query-failure--light:
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
index 82d01eb37fee..deda7964c927 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
@@ -1,5 +1,6 @@
import { MOCK_TEAM_ID } from 'lib/api.mock'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -7,6 +8,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import {
ConversionGoalFilter,
@@ -15,15 +17,22 @@ import {
TrendsQuery,
DataTableNode,
MarketingAnalyticsAggregatedQuery,
+ MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsTableQuery,
MarketingAnalyticsBaseColumns,
MarketingAnalyticsColumnsSchemaNames,
NodeKind,
+ WebAnalyticsPropertyFilters,
} from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { ExternalDataSource } from '~/types'
+import { ExternalDataSource, PropertyFilterType, PropertyOperator } from '~/types'
-import { MarketingAnalyticsTab, SetupSection, marketingAnalyticsLogic } from './marketingAnalyticsLogic'
+import {
+ MarketingAnalyticsTab,
+ MarketingDashboardView,
+ SetupSection,
+ marketingAnalyticsLogic,
+} from './marketingAnalyticsLogic'
import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'
import { marketingAnalyticsTableLogic } from './marketingAnalyticsTableLogic'
import { marketingAnalyticsTilesLogic } from './marketingAnalyticsTilesLogic'
@@ -284,4 +293,106 @@ describe('marketingAnalyticsLogic', () => {
unmountSettings()
}
)
+ it('carries dashboard view, breakdown and filters in the URL', async () => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD], {
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ })
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+
+ await expectLogic(logic, () => logic.actions.setDates('-30d', null)).toFinishAllListeners()
+ expect(router.values.searchParams).not.toHaveProperty('view')
+ expect(router.values.searchParams).not.toHaveProperty('breakdown')
+
+ const filters: WebAnalyticsPropertyFilters = [
+ {
+ type: PropertyFilterType.Session,
+ key: '$channel_type',
+ operator: PropertyOperator.Exact,
+ value: 'Direct',
+ },
+ ]
+ logic.actions.setDashboardView(MarketingDashboardView.ENGAGEMENT)
+ logic.actions.setDashboardBreakdown(MarketingAnalyticsAttributionBreakdown.Campaign)
+ logic.actions.setDashboardProperties(filters)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({
+ view: 'engagement',
+ breakdown: 'campaign',
+ filters,
+ })
+
+ await expectLogic(logic, () => logic.actions.setDates('-7d', null)).toFinishAllListeners()
+ expect(router.values.searchParams).toMatchObject({ view: 'engagement', breakdown: 'campaign', filters })
+
+ logic.actions.setDashboardView(MarketingDashboardView.OVERVIEW)
+ logic.actions.setDashboardBreakdown(MarketingAnalyticsAttributionBreakdown.Channel)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(router.values.searchParams).toMatchObject({ view: 'overview', breakdown: 'channel' })
+
+ await expectLogic(logic, () =>
+ router.actions.push(urls.marketingAnalyticsApp(), { view: 'retention', breakdown: 'source' })
+ ).toMatchValues({
+ dashboardView: MarketingDashboardView.RETENTION,
+ dashboardBreakdown: MarketingAnalyticsAttributionBreakdown.Source,
+ dashboardProperties: [],
+ })
+
+ await expectLogic(logic, () => router.actions.push(urls.marketingAnalyticsApp())).toMatchValues({
+ dashboardView: MarketingDashboardView.OVERVIEW,
+ dashboardBreakdown: MarketingAnalyticsAttributionBreakdown.Channel,
+ dashboardProperties: [],
+ })
+ })
+
+ it.each([
+ {
+ search: { view: 'retention' },
+ savedBreakdown: 'campaign',
+ expectedView: MarketingDashboardView.RETENTION,
+ expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Channel,
+ },
+ {
+ search: { breakdown: 'source' },
+ savedBreakdown: 'campaign',
+ expectedView: MarketingDashboardView.OVERVIEW,
+ expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Source,
+ },
+ {
+ search: {},
+ savedBreakdown: 'campaign',
+ expectedView: MarketingDashboardView.ENGAGEMENT,
+ expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Campaign,
+ },
+ {
+ search: { view: 'retention' },
+ savedBreakdown: 'retired_dimension',
+ expectedView: MarketingDashboardView.RETENTION,
+ expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Channel,
+ },
+ ])(
+ 'hydrates $search with persisted breakdown $savedBreakdown',
+ async ({ search, savedBreakdown, expectedView, expectedBreakdown }) => {
+ localStorage.setItem(
+ `${MOCK_TEAM_ID}__.scenes.webAnalytics.marketingAnalyticsLogic._dashboardView`,
+ JSON.stringify(MarketingDashboardView.ENGAGEMENT)
+ )
+ localStorage.setItem(
+ `${MOCK_TEAM_ID}__.scenes.webAnalytics.marketingAnalyticsLogic._dashboardBreakdown`,
+ JSON.stringify(savedBreakdown)
+ )
+ router.actions.push(urls.marketingAnalyticsApp(), search)
+
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({
+ dashboardView: expectedView,
+ dashboardBreakdown: expectedBreakdown,
+ dashboardProperties: [],
+ })
+ }
+ )
})
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index 713e8bd9303a..86edce15a0a0 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -10,7 +10,7 @@ import {
reducers,
selectors,
} from 'kea'
-import { actionToUrl, router } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -23,6 +23,7 @@ import { urls } from 'scenes/urls'
import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { isWebAnalyticsPropertyFilters } from '~/queries/schema-guards'
import {
CompareFilter,
ConversionGoalFilter,
@@ -32,6 +33,7 @@ import {
DateRange,
IntegrationFilter,
MarketingAnalyticsAggregatedQuery,
+ MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsColumnsSchemaNames,
MarketingAnalyticsDrillDownLevel,
NativeMarketingSource,
@@ -40,6 +42,7 @@ import {
ProductKey,
SourceMap,
VALID_NATIVE_MARKETING_SOURCES,
+ WebAnalyticsPropertyFilters,
} from '~/queries/schema/schema-general'
import { MARKETING_ANALYTICS_SCHEMA } from '~/queries/schema/schema-general'
import { DataWarehouseSettingsTab, ExternalDataSchemaStatus, ExternalDataSource, IntervalType } from '~/types'
@@ -53,6 +56,7 @@ import type { FeatureFlagsSet } from '../../../../../../lib/logic/featureFlagLog
import type { ProductIntentProperties } from '../../../../../../lib/utils/product-intents'
import { defaultConversionGoalFilter } from '../components/settings/constants'
import { SetupEntryPoint, marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'
+import { DASHBOARD_BREAKDOWNS, DEFAULT_DASHBOARD_BREAKDOWN } from './marketingBreakdown'
import { externalAdsCostTile } from './marketingCostTile'
import {
MarketingDashboardMapper,
@@ -112,6 +116,52 @@ export interface DashboardGoalsConfigured {
revenueGoal: boolean
}
+/** Sections of the redesigned dashboard. Declared here rather than in the scene so the logic that
+ * owns the URL doesn't have to import the component tree. */
+export enum MarketingDashboardView {
+ OVERVIEW = 'overview',
+ ACQUISITION = 'acquisition',
+ ENGAGEMENT = 'engagement',
+ RETENTION = 'retention',
+ CONVERSION = 'conversion',
+}
+
+export const DEFAULT_DASHBOARD_VIEW = MarketingDashboardView.OVERVIEW
+
+function hasDashboardParams(searchParams: URLSearchParams): boolean {
+ return ['view', 'breakdown', 'filters'].some((key) => searchParams.has(key))
+}
+
+function dashboardParamsFromSearch(searchParams: URLSearchParams): {
+ view?: MarketingDashboardView
+ breakdown?: MarketingAnalyticsAttributionBreakdown
+ properties?: WebAnalyticsPropertyFilters
+} {
+ const params: ReturnType<typeof dashboardParamsFromSearch> = hasDashboardParams(searchParams)
+ ? { view: DEFAULT_DASHBOARD_VIEW, breakdown: DEFAULT_DASHBOARD_BREAKDOWN, properties: [] }
+ : {}
+ const view = searchParams.get('view') as MarketingDashboardView | null
+ if (view && Object.values(MarketingDashboardView).includes(view)) {
+ params.view = view
+ }
+ const breakdown = searchParams.get('breakdown') as MarketingAnalyticsAttributionBreakdown | null
+ if (breakdown && DASHBOARD_BREAKDOWNS.includes(breakdown)) {
+ params.breakdown = breakdown
+ }
+ const filters = searchParams.get('filters')
+ if (filters) {
+ try {
+ const parsed = JSON.parse(filters)
+ if (isWebAnalyticsPropertyFilters(parsed)) {
+ params.properties = parsed
+ }
+ } catch {
+ // A hand-edited or truncated URL should load the dashboard unfiltered, not break it.
+ }
+ }
+ return params
+}
+
/** Where a tab key lands once Setup absorbs it. Applied by the scene, which is what
* knows whether Setup is rendering — with its flag off `integration-health` is still a
* real tab and resolves on its own. */
@@ -268,6 +318,8 @@ export interface marketingAnalyticsLogicValues {
dataWarehouseSourcesLoading: boolean // sourceManagementLogic
dataWarehouseTables: DatabaseSchemaDataWarehouseTable[] // sourceManagementLogic
baseCurrency: CurrencyCode // teamLogic
+ _dashboardBreakdown: MarketingAnalyticsAttributionBreakdown
+ _dashboardView: MarketingDashboardView
_drillDownLevel: MarketingAnalyticsDrillDownLevel
_integrationFilter: IntegrationFilter
activeTab: MarketingAnalyticsTab
@@ -314,6 +366,9 @@ export interface marketingAnalyticsLogicValues {
conversionGoalInput: ConversionGoalFilter
conversionGoalModalVisible: boolean
createMarketingDataWarehouseNodes: DataWarehouseNode[]
+ dashboardBreakdown: MarketingAnalyticsAttributionBreakdown
+ dashboardProperties: WebAnalyticsPropertyFilters
+ dashboardView: MarketingDashboardView
dateFilter: {
dateFrom: string | null
dateTo: string | null
@@ -462,6 +517,15 @@ export interface marketingAnalyticsLogicActions {
setConversionGoalInput: (goal: ConversionGoalFilter) => {
goal: ConversionGoalFilter
}
+ setDashboardBreakdown: (breakdown: MarketingAnalyticsAttributionBreakdown) => {
+ breakdown: MarketingAnalyticsAttributionBreakdown
+ }
+ setDashboardProperties: (properties: WebAnalyticsPropertyFilters) => {
+ properties: WebAnalyticsPropertyFilters
+ }
+ setDashboardView: (view: MarketingDashboardView) => {
+ view: MarketingDashboardView
+ }
setDateInterval: (interval: IntervalType) => {
interval: IntervalType
}
@@ -509,6 +573,7 @@ export interface marketingAnalyticsLogicActions {
value: true
}
syncFromUrl: (params: {
+ breakdown?: MarketingAnalyticsAttributionBreakdown
chartDisplayType?: ChartDisplayType
compare?: boolean
compare_to?: string
@@ -518,9 +583,12 @@ export interface marketingAnalyticsLogicActions {
includeNonIntegrated?: boolean
integrationSourceIds?: string[]
interval?: IntervalType
+ properties?: WebAnalyticsPropertyFilters
tileColumnSelection?: string
+ view?: MarketingDashboardView
}) => {
params: {
+ breakdown?: MarketingAnalyticsAttributionBreakdown | undefined
chartDisplayType?: ChartDisplayType | undefined
compare?: boolean | undefined
compare_to?: string | undefined
@@ -530,7 +598,9 @@ export interface marketingAnalyticsLogicActions {
includeNonIntegrated?: boolean | undefined
integrationSourceIds?: string[] | undefined
interval?: IntervalType | undefined
+ properties?: WebAnalyticsPropertyFilters | undefined
tileColumnSelection?: string | undefined
+ view?: MarketingDashboardView | undefined
}
}
}
@@ -549,6 +619,10 @@ export interface marketingAnalyticsLogicMeta {
_drillDownLevel: MarketingAnalyticsDrillDownLevel,
featureFlags: FeatureFlagsSet
) => MarketingAnalyticsDrillDownLevel
+ dashboardView: (_dashboardView: MarketingDashboardView) => MarketingDashboardView
+ dashboardBreakdown: (
+ _dashboardBreakdown: MarketingAnalyticsAttributionBreakdown
+ ) => MarketingAnalyticsAttributionBreakdown
validSourcesMap: (sources_map: Record<string, SourceMap>) => {
[x: string]: SourceMap
} | null
@@ -737,6 +811,9 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
chartDisplayType?: ChartDisplayType
tileColumnSelection?: string
drillDownLevel?: MarketingAnalyticsDrillDownLevel
+ view?: MarketingDashboardView
+ breakdown?: MarketingAnalyticsAttributionBreakdown
+ properties?: WebAnalyticsPropertyFilters
}) => ({ params }),
showColumnConfigModal: true,
hideColumnConfigModal: true,
@@ -745,6 +822,9 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
setChartDisplayType: (chartDisplayType: ChartDisplayType) => ({ chartDisplayType }),
setTileColumnSelection: (column: validColumnsForTiles) => ({ column }),
setDrillDownLevel: (level: MarketingAnalyticsDrillDownLevel) => ({ level }),
+ setDashboardView: (view: MarketingDashboardView) => ({ view }),
+ setDashboardBreakdown: (breakdown: MarketingAnalyticsAttributionBreakdown) => ({ breakdown }),
+ setDashboardProperties: (properties: WebAnalyticsPropertyFilters) => ({ properties }),
setInitialized: true,
}),
reducers(() => {
@@ -927,6 +1007,31 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
params.drillDownLevel !== undefined ? params.drillDownLevel : state,
},
],
+ _dashboardView: [
+ DEFAULT_DASHBOARD_VIEW as MarketingDashboardView,
+ persistConfig,
+ {
+ setDashboardView: (_, { view }) => view,
+ syncFromUrl: (state, { params }) => (params.view !== undefined ? params.view : state),
+ },
+ ],
+ _dashboardBreakdown: [
+ DEFAULT_DASHBOARD_BREAKDOWN as MarketingAnalyticsAttributionBreakdown,
+ persistConfig,
+ {
+ setDashboardBreakdown: (_, { breakdown }) => breakdown,
+ syncFromUrl: (state, { params }) => (params.breakdown !== undefined ? params.breakdown : state),
+ },
+ ],
+ // Not persisted: a filter is a per-visit refinement, so it travels in the URL for
+ // sharing but does not follow someone back to the dashboard tomorrow.
+ dashboardProperties: [
+ [] as WebAnalyticsPropertyFilters,
+ {
+ setDashboardProperties: (_, { properties }) => properties,
+ syncFromUrl: (state, { params }) => (params.properties !== undefined ? params.properties : state),
+ },
+ ],
}
}),
selectors({
@@ -957,6 +1062,16 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return level
},
],
+ dashboardView: [
+ (s) => [s._dashboardView],
+ (view: MarketingDashboardView): MarketingDashboardView =>
+ Object.values(MarketingDashboardView).includes(view) ? view : DEFAULT_DASHBOARD_VIEW,
+ ],
+ dashboardBreakdown: [
+ (s) => [s._dashboardBreakdown],
+ (breakdown: MarketingAnalyticsAttributionBreakdown): MarketingAnalyticsAttributionBreakdown =>
+ DASHBOARD_BREAKDOWNS.includes(breakdown) ? breakdown : DEFAULT_DASHBOARD_BREAKDOWN,
+ ],
validSourcesMap: [
(s) => [s.sources_map],
(sources_map: Record<string, SourceMap>) => {
@@ -1384,7 +1499,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
],
}),
actionToUrl(({ values }) => {
- const buildUrl = (): [string, string] => {
+ const buildUrl = (includeDashboardState: boolean): [string, string] => {
if (values.activeTab === MarketingAnalyticsTab.PAGE_VISIBILITY) {
const searchParams = new URLSearchParams(router.values.location.search)
searchParams.set('tab', MarketingAnalyticsTab.PAGE_VISIBILITY)
@@ -1431,6 +1546,20 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
searchParams.set('include_non_integrated', 'false')
}
+ // The current dashboard uses local section state. Only the new controls or an
+ // existing dashboard URL opt into shared navigation state.
+ if (
+ values.activeTab === MarketingAnalyticsTab.DASHBOARD &&
+ values.featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] &&
+ (includeDashboardState || hasDashboardParams(new URLSearchParams(router.values.location.search)))
+ ) {
+ searchParams.set('view', values.dashboardView)
+ searchParams.set('breakdown', values.dashboardBreakdown)
+ if (values.dashboardProperties.length > 0) {
+ searchParams.set('filters', JSON.stringify(values.dashboardProperties))
+ }
+ }
+
// Chart display type
if (values.chartDisplayType) {
searchParams.set('chart_display_type', values.chartDisplayType)
@@ -1449,22 +1578,39 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return [router.values.location.pathname, searchParams.toString()]
}
+ const buildCurrentUrl = (): [string, string] => buildUrl(false)
+ const buildDashboardUrl = (): [string, string] => buildUrl(true)
+
return {
- setActiveTab: buildUrl,
- setSetupSection: buildUrl,
- setDates: buildUrl,
- setDateInterval: buildUrl,
- setDatesAndInterval: buildUrl,
- setCompareFilter: buildUrl,
- setIntegrationFilter: buildUrl,
- setChartDisplayType: buildUrl,
- setTileColumnSelection: buildUrl,
- setDrillDownLevel: buildUrl,
+ setActiveTab: buildCurrentUrl,
+ setSetupSection: buildCurrentUrl,
+ setDates: buildCurrentUrl,
+ setDateInterval: buildCurrentUrl,
+ setDatesAndInterval: buildCurrentUrl,
+ setCompareFilter: buildCurrentUrl,
+ setIntegrationFilter: buildCurrentUrl,
+ setChartDisplayType: buildCurrentUrl,
+ setTileColumnSelection: buildCurrentUrl,
+ setDrillDownLevel: buildCurrentUrl,
+ setDashboardView: buildDashboardUrl,
+ setDashboardBreakdown: buildDashboardUrl,
+ setDashboardProperties: buildDashboardUrl,
// Note: syncFromUrl is NOT mapped here - it's only for receiving URL changes
}
}),
- // Note: We don't use urlToAction here to avoid sync loops.
- // URL params are read once on mount in afterMount instead.
+ urlToAction(({ actions }) => ({
+ [urls.marketingAnalyticsApp()]: (_, searchParams, __, { initial, search }) => {
+ if (initial || (searchParams.tab && searchParams.tab !== MarketingAnalyticsTab.DASHBOARD)) {
+ return
+ }
+ actions.syncFromUrl({
+ view: DEFAULT_DASHBOARD_VIEW,
+ breakdown: DEFAULT_DASHBOARD_BREAKDOWN,
+ properties: [],
+ ...dashboardParamsFromSearch(new URLSearchParams(search)),
+ })
+ },
+ })),
listeners(({ actions, values }) => {
const trackDashboardInteraction = (): void => {
// Only track after initialization to avoid tracking initial render/setup
@@ -1639,6 +1785,8 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
params.drillDownLevel = drillDownLevel
}
+ Object.assign(params, dashboardParamsFromSearch(searchParams))
+
// Apply URL params if any were found
if (Object.keys(params).length > 0) {
actions.syncFromUrl(params)
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts
index 97e3e9e1fd07..c763d0ae9e1f 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts
@@ -1,6 +1,11 @@
-import { BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
+import { BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
-import { ConversionGoalFilter, MarketingAnalyticsAttributionBreakdown, NodeKind } from '~/queries/schema/schema-general'
+import {
+ ConversionGoalFilter,
+ MarketingAnalyticsAttributionBreakdown,
+ NodeKind,
+ WebStatsBreakdown,
+} from '~/queries/schema/schema-general'
export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, string> = {
[MarketingAnalyticsAttributionBreakdown.Channel]: 'Channel',
@@ -13,6 +18,33 @@ export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, st
[MarketingAnalyticsAttributionBreakdown.LandingPage]: 'Landing page',
}
+/** The dimensions the dashboard offers. Content and term are left out because a marketer rarely
+ * breaks a whole dashboard down by them, and every extra option costs a row in the picker. */
+export const DASHBOARD_BREAKDOWNS: readonly MarketingAnalyticsAttributionBreakdown[] = [
+ MarketingAnalyticsAttributionBreakdown.Channel,
+ MarketingAnalyticsAttributionBreakdown.Source,
+ MarketingAnalyticsAttributionBreakdown.Campaign,
+ MarketingAnalyticsAttributionBreakdown.Medium,
+ MarketingAnalyticsAttributionBreakdown.ReferringDomain,
+ MarketingAnalyticsAttributionBreakdown.LandingPage,
+]
+
+export const DEFAULT_DASHBOARD_BREAKDOWN = MarketingAnalyticsAttributionBreakdown.Channel
+
+/** One page-level breakdown drives both the retention query, which takes this enum, and the web
+ * stats tables, which take their own. Declared total so a new member fails to compile here rather
+ * than silently dropping a table. */
+export const ATTRIBUTION_BREAKDOWN_TO_WEB_STATS: Record<MarketingAnalyticsAttributionBreakdown, WebStatsBreakdown> = {
+ [MarketingAnalyticsAttributionBreakdown.Channel]: WebStatsBreakdown.InitialChannelType,
+ [MarketingAnalyticsAttributionBreakdown.Source]: WebStatsBreakdown.InitialUTMSource,
+ [MarketingAnalyticsAttributionBreakdown.Campaign]: WebStatsBreakdown.InitialUTMCampaign,
+ [MarketingAnalyticsAttributionBreakdown.Medium]: WebStatsBreakdown.InitialUTMMedium,
+ [MarketingAnalyticsAttributionBreakdown.Content]: WebStatsBreakdown.InitialUTMContent,
+ [MarketingAnalyticsAttributionBreakdown.Term]: WebStatsBreakdown.InitialUTMTerm,
+ [MarketingAnalyticsAttributionBreakdown.ReferringDomain]: WebStatsBreakdown.InitialReferringDomain,
+ [MarketingAnalyticsAttributionBreakdown.LandingPage]: WebStatsBreakdown.InitialPage,
+}
+
/** True for the row the backend folds the long tail of breakdown values into. */
export const isFoldedBreakdownValue = (value: string): boolean => value === BREAKDOWN_OTHER_STRING_LABEL
@@ -21,7 +53,13 @@ export const displayBreakdownValue = (value: string, dimensionLabel: string): st
if (isFoldedBreakdownValue(value)) {
return 'Other'
}
- return value || `(no ${dimensionLabel.toLowerCase()})`
+ // The stats tables return an empty string for an untagged visit and trends returns its own
+ // null sentinel. Both have to read the same, or the same row and line get different labels
+ // and clicking the row cannot focus its line.
+ if (!value || value === BREAKDOWN_NULL_STRING_LABEL) {
+ return `(no ${dimensionLabel.toLowerCase()})`
+ }
+ return value
}
/** Warehouse goals are keyed by distinct id, so the events-based session queries can't join them. */
diff --git a/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.stories.tsx b/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.stories.tsx
new file mode 100644
index 000000000000..978eb5bb020c
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.stories.tsx
@@ -0,0 +1,84 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+import {
+ MarketingDashboardView,
+ marketingAnalyticsLogic,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import {
+ BREAKDOWN_LABELS,
+ DASHBOARD_BREAKDOWNS,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'
+
+import { MarketingAnalyticsAttributionBreakdown } from '~/queries/schema/schema-general'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { MarketingSectionSwitcher } from './MarketingSectionSwitcher'
+
+function NavigationPreview(): JSX.Element {
+ const { dashboardBreakdown, dashboardProperties } = useValues(marketingAnalyticsLogic)
+ const { setDashboardBreakdown, setDashboardProperties } = useActions(marketingAnalyticsLogic)
+
+ return (
+ <div className="flex flex-col gap-4 w-full">
+ <div className="flex">
+ <MarketingSectionSwitcher />
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonSelect
+ aria-label="Breakdown"
+ value={dashboardBreakdown}
+ onChange={(value) => value && setDashboardBreakdown(value)}
+ options={DASHBOARD_BREAKDOWNS.map((value) => ({ value, label: BREAKDOWN_LABELS[value] }))}
+ />
+ <LemonButton
+ onClick={() =>
+ setDashboardProperties([
+ {
+ type: PropertyFilterType.Session,
+ key: '$channel_type',
+ operator: PropertyOperator.Exact,
+ value: 'Direct',
+ },
+ ])
+ }
+ >
+ Filter direct traffic
+ </LemonButton>
+ <span>{`Active filters: ${dashboardProperties.length}`}</span>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ to={`${urls.marketingAnalyticsApp()}?view=${MarketingDashboardView.RETENTION}&breakdown=${MarketingAnalyticsAttributionBreakdown.Source}`}
+ >
+ Open retention link
+ </LemonButton>
+ <LemonButton to={urls.marketingAnalyticsApp()}>Open default link</LemonButton>
+ </div>
+ </div>
+ )
+}
+
+const meta: Meta<typeof MarketingSectionSwitcher> = {
+ title: 'Marketing Analytics/Dashboard/Section switcher',
+ component: MarketingSectionSwitcher,
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
+ pageUrl: urls.marketingAnalyticsApp(),
+ },
+}
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const InteractiveNavigation: Story = { render: () => <NavigationPreview /> }
+export const Narrow: Story = {
+ render: () => (
+ <div className="w-[32.5rem] max-w-full">
+ <MarketingSectionSwitcher />
+ </div>
+ ),
+}
diff --git a/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.tsx b/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.tsx
new file mode 100644
index 000000000000..74c05c84eff4
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.tsx
@@ -0,0 +1,54 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCursor, IconPeople, IconPieChart, IconRetention, IconTarget } from '@posthog/icons'
+import { LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+
+import {
+ MarketingDashboardView,
+ marketingAnalyticsLogic,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+
+const SECTIONS: { value: MarketingDashboardView; label: string; icon: JSX.Element }[] = [
+ { value: MarketingDashboardView.OVERVIEW, label: 'Overview', icon: <IconPieChart /> },
+ { value: MarketingDashboardView.ACQUISITION, label: 'Acquisition', icon: <IconPeople /> },
+ { value: MarketingDashboardView.ENGAGEMENT, label: 'Engagement', icon: <IconCursor /> },
+ { value: MarketingDashboardView.RETENTION, label: 'Retention', icon: <IconRetention /> },
+ { value: MarketingDashboardView.CONVERSION, label: 'Conversion', icon: <IconTarget /> },
+]
+
+export function MarketingSectionSwitcher(): JSX.Element {
+ const { dashboardView } = useValues(marketingAnalyticsLogic)
+ const { setDashboardView } = useActions(marketingAnalyticsLogic)
+
+ // Both controls render and a container query picks one, so the switch needs no measurement and
+ // follows the space the header actually has rather than the window.
+ return (
+ <div className="@container flex-1 basis-56 min-w-0">
+ <LemonSegmentedButton
+ className="hidden @min-[36rem]:flex"
+ size="small"
+ value={dashboardView}
+ onChange={(view) => setDashboardView(view)}
+ options={SECTIONS.map((section) => ({
+ value: section.value,
+ label: section.label,
+ icon: section.icon,
+ 'data-attr': `marketing-dashboard-section-${section.value}`,
+ }))}
+ />
+ <LemonSelect
+ className="@min-[36rem]:hidden"
+ size="small"
+ value={dashboardView}
+ onChange={(view) => view && setDashboardView(view)}
+ options={SECTIONS.map((section) => ({
+ value: section.value,
+ label: section.label,
+ icon: section.icon,
+ }))}
+ data-attr="marketing-dashboard-section-select"
+ aria-label="Dashboard section"
+ />
+ </div>
+ )
+}