:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { beforeUnload, combineUrl, router } from 'kea-router'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardsTab } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import type { AnyPropertyFilter, IntervalType, TeamBasicType } from '~/types'
import { crossProjectDashboardTracking } from './crossProjectDashboardTracking'
import { changedTileLayouts, layoutsDiffer, layoutsForTiles, type ResponsiveTileLayouts } from './crossProjectLayouts'
import { findMissingPropertyKeys, propertyKeysIn } from './crossProjectPropertyKeys'
import {
crossProjectDashboardsDestroy,
crossProjectDashboardsPartialUpdate,
crossProjectDashboardsRetrieve,
crossProjectDashboardsTilesCreate,
crossProjectDashboardsTilesDestroy,
crossProjectDashboardsTilesPartialUpdate,
} from './generated/api'
import type {
CrossProjectDashboardApi,
CrossProjectDashboardTileApi,
PatchedCrossProjectDashboardApi,
} from './generated/api.schemas'
import { openDeleteCrossProjectDashboardDialog } from './openDeleteCrossProjectDashboardDialog'
export interface CrossProjectDashboardLogicProps {
id: string
}
export interface CrossProjectDashboardFilters {
date_from?: string | null
date_to?: string | null
interval?: IntervalType | null
properties?: AnyPropertyFilter[]
}
export type CrossProjectDashboardDetails = Pick<PatchedCrossProjectDashboardApi, 'name' | 'description'>
export interface CrossProjectTileProject {
name: string
timezone: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface crossProjectDashboardLogicValues {
dashboard: CrossProjectDashboardApi | null
dashboardFilters: CrossProjectDashboardFilters
dashboardLoading: boolean
gridLayouts: Partial<ResponsiveTileLayouts>
hasUnsavedLayoutChanges: boolean
layoutEditMode: boolean
layoutSaving: boolean
missingPropertyKeys: Record<number, string[]>
missingPropertyKeysLoading: boolean
pendingLayouts: Partial<ResponsiveTileLayouts> | null
projectIds: number[]
savedLayouts: ResponsiveTileLayouts
tileProjects: Record<number, CrossProjectTileProject>
tiles: readonly CrossProjectDashboardTileApi[]
timezonesDiverge: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface crossProjectDashboardLogicActions {
cancelLayoutEdit: () => {
value: true
}
checkPropertyKeys: () => any
checkPropertyKeysFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
checkPropertyKeysSuccess: (
missingPropertyKeys: Record<number, string[]>,
payload?: any
) => {
missingPropertyKeys: Record<number, string[]>
payload?: any
}
deleteDashboard: () => {
value: true
}
enterLayoutEdit: () => {
value: true
}
exitLayoutEdit: () => {
value: true
}
loadDashboard: () => {
value: true
}
loadDashboardFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadDashboardSuccess: (
dashboard: CrossProjectDashboardApi | null,
payload?: {
value: true
}
) => {
dashboard: CrossProjectDashboardApi | null
payload?: {
value: true
}
}
removeTile: (tileId: string) => {
tileId: string
}
restoreTile: (tile: CrossProjectDashboardTileApi) => {
tile: CrossProjectDashboardTileApi
}
saveLayout: () => {
value: true
}
saveLayoutFailed: () => {
value: true
}
saveLayoutStarted: () => {
value: true
}
setDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setInterval: (interval: IntervalType | null) => {
interval: IntervalType | null
}
setPendingLayouts: (layouts: Partial<ResponsiveTileLayouts>) => {
layouts: Partial<ResponsiveTileLayouts>
}
setProperties: (properties: AnyPropertyFilter[]) => {
properties: AnyPropertyFilter[]
}
setTileColor: (
tileId: string,
color: string | null
) => {
color: string | null
tileId: string
}
setTileOverride: (
tileId: string,
overrides: CrossProjectDashboardFilters
) => {
overrides: CrossProjectDashboardFilters
tileId: string
}
updateDashboard: (details: CrossProjectDashboardDetails) => {
details: CrossProjectDashboardDetails
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface crossProjectDashboardLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
tiles: (dashboard: CrossProjectDashboardApi | null) => readonly CrossProjectDashboardTileApi[]
projectIds: (tiles: readonly CrossProjectDashboardTileApi[]) => number[]
dashboardFilters: (dashboard: CrossProjectDashboardApi | null) => CrossProjectDashboardFilters
tileProjects: (
currentOrganization: null | import('~/types').OrganizationType
) => Record<number, CrossProjectTileProject>
timezonesDiverge: (
tiles: readonly CrossProjectDashboardTileApi[],
tileProjects: Record<number, CrossProjectTileProject>
) => boolean
savedLayouts: (tiles: readonly CrossProjectDashboardTileApi[]) => ResponsiveTileLayouts
hasUnsavedLayoutChanges: (
layoutEditMode: boolean,
savedLayouts: ResponsiveTileLayouts,
pendingLayouts: Partial<ResponsiveTileLayouts> | null
) => boolean
gridLayouts: (
hasUnsavedLayoutChanges: boolean,
pendingLayouts: Partial<ResponsiveTileLayouts> | null,
savedLayouts: ResponsiveTileLayouts
) => Partial<ResponsiveTileLayouts>
}
}
export type crossProjectDashboardLogicType = MakeLogicType<
crossProjectDashboardLogicValues,
crossProjectDashboardLogicActions,
CrossProjectDashboardLogicProps,
crossProjectDashboardLogicMeta
>
export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([
path((key) => ['products', 'cross_project_dashboards', 'frontend', 'crossProjectDashboardLogic', key]),
props({} as CrossProjectDashboardLogicProps),
key((props) => props.id),
actions({
loadDashboard: true,
removeTile: (tileId: string) => ({ tileId }),
restoreTile: (tile: CrossProjectDashboardTileApi) => ({ tile }),
setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setInterval: (interval: IntervalType | null) => ({ interval }),
enterLayoutEdit: true,
exitLayoutEdit: true,
setPendingLayouts: (layouts: Partial<ResponsiveTileLayouts>) => ({ layouts }),
saveLayout: true,
saveLayoutStarted: true,
saveLayoutFailed: true,
cancelLayoutEdit: true,
setTileOverride: (tileId: string, overrides: CrossProjectDashboardFilters) => ({ tileId, overrides }),
setTileColor: (tileId: string, color: string | null) => ({ tileId, color }),
setProperties: (properties: AnyPropertyFilter[]) => ({ properties }),
updateDashboard: (details: CrossProjectDashboardDetails) => ({ details }),
deleteDashboard: true,
}),
reducers({
layoutEditMode: [false, { enterLayoutEdit: () => true, exitLayoutEdit: () => false }],
layoutSaving: [
false,
{ saveLayoutStarted: () => true, saveLayoutFailed: () => false, exitLayoutEdit: () => false },
],
pendingLayouts: [
null as Partial<ResponsiveTileLayouts> | null,
{
setPendingLayouts: (_, { layouts }) => layouts,
enterLayoutEdit: () => null,
exitLayoutEdit: () => null,
},
],
}),
loaders(({ props, values }) => ({
missingPropertyKeys: [
{} as Record<number, string[]>,
{
checkPropertyKeys: async () => {
return await findMissingPropertyKeys(
values.projectIds,
propertyKeysIn(values.dashboardFilters.properties)
)
},
},
],
dashboard: [
null as CrossProjectDashboardApi | null,
{
loadDashboard: async () => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId) {
return null
}
return await crossProjectDashboardsRetrieve(organizationId, props.id)
},
},
],
})),
selectors({
tiles: [(s) => [s.dashboard], (dashboard: CrossProjectDashboardApi | null) => dashboard?.tiles ?? []],
projectIds: [
(s) => [s.tiles],
(tiles: CrossProjectDashboardTileApi[]) => Array.from(new Set(tiles.map((tile) => tile.project_id))),
],
dashboardFilters: [
(s) => [s.dashboard],
(dashboard: CrossProjectDashboardApi | null) =>
((dashboard?.filters as CrossProjectDashboardFilters | undefined) ??
{}) as CrossProjectDashboardFilters,
],
// Only projects the organization listing returns, so a project the reader cannot reach
// has no entry and its tile stays unlabeled.
tileProjects: [
() => [organizationLogic.selectors.currentOrganization],
(currentOrganization: { teams?: TeamBasicType[] } | null) =>
Object.fromEntries(
(currentOrganization?.teams ?? []).map((team) => [
team.id,
{ name: team.name, timezone: team.timezone },
])
) as Record<number, CrossProjectTileProject>,
],
timezonesDiverge: [
(s) => [s.tiles, s.tileProjects],
(tiles: readonly CrossProjectDashboardTileApi[], tileProjects: Record<number, CrossProjectTileProject>) => {
const zones = new Set(tiles.map((tile) => tileProjects[tile.project_id]?.timezone).filter(Boolean))
return zones.size > 1
},
],
savedLayouts: [(s) => [s.tiles], (tiles: readonly CrossProjectDashboardTileApi[]) => layoutsForTiles(tiles)],
hasUnsavedLayoutChanges: [
(s) => [s.layoutEditMode, s.savedLayouts, s.pendingLayouts],
(
layoutEditMode: boolean,
savedLayouts: ResponsiveTileLayouts,
pendingLayouts: Partial<ResponsiveTileLayouts> | null
) => layoutEditMode && layoutsDiffer(savedLayouts, pendingLayouts),
],
// Keeps the grid controlled, so switching back to the saved layout on cancel moves the tiles back.
gridLayouts: [
(s) => [s.hasUnsavedLayoutChanges, s.pendingLayouts, s.savedLayouts],
(
hasUnsavedLayoutChanges: boolean,
pendingLayouts: Partial<ResponsiveTileLayouts> | null,
savedLayouts: ResponsiveTileLayouts
): Partial<ResponsiveTileLayouts> =>
hasUnsavedLayoutChanges && pendingLayouts ? pendingLayouts : savedLayouts,
],
}),
listeners(({ props, actions, values }) => {
// Saves send the whole filters object, so they run one at a time to never start from a stale copy.
// A rename joins the same queue, so a late response cannot put back filters that a newer save replaced.
let saves: Promise<boolean> = Promise.resolve(true)
// Undo stays clickable while its toast closes, and a second restore of the same tile fails as a duplicate.
const restoringTileIds = new Set<string>()
// Saves and tile edits also land through loadDashboardSuccess, and only the first load is a view.
let viewTracked = false
const saveDashboard = (
changes: () => PatchedCrossProjectDashboardApi,
errorMessage: string
): Promise<boolean> => {
saves = saves.then(async () => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId) {
return false
}
try {
actions.loadDashboardSuccess(
await crossProjectDashboardsPartialUpdate(organizationId, props.id, changes())
)
return true
} catch (error: any) {
lemonToast.error(error?.detail || errorMessage)
actions.loadDashboard()
return false
}
})
return saves
}
const saveFilters = (
update: (filters: CrossProjectDashboardFilters) => void,
errorMessage: string
): Promise<boolean> =>
saveDashboard(() => {
const filters: CrossProjectDashboardFilters = { ...values.dashboardFilters }
update(filters)
return { filters }
}, errorMessage)
const applySavedTiles = (saved: CrossProjectDashboardTileApi[]): void => {
if (!values.dashboard) {
return
}
const byId = new Map(saved.map((tile) => [tile.id, tile]))
actions.loadDashboardSuccess({
...values.dashboard,
tiles: values.dashboard.tiles.map((tile) => byId.get(tile.id) ?? tile),
})
}
return {
loadDashboardSuccess: ({ dashboard }) => {
if (dashboard && !viewTracked) {
viewTracked = true
crossProjectDashboardTracking.viewed(props.id, dashboard.tiles)
}
},
updateDashboard: async ({ details }) => {
if (await saveDashboard(() => details, 'Could not save that change. Try again.')) {
crossProjectDashboardTracking.edited(props.id, details.name !== undefined ? 'name' : 'description')
}
},
deleteDashboard: () => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId || !values.dashboard) {
return
}
openDeleteCrossProjectDashboardDialog(values.dashboard.name, async () => {
await crossProjectDashboardsDestroy(organizationId, props.id)
crossProjectDashboardTracking.deleted(props.id, 'dashboard')
router.actions.push(combineUrl(urls.dashboards(), { tab: DashboardsTab.CrossProject }).url)
})
},
setDates: async ({ dateFrom, dateTo }) => {
const saved = await saveFilters((filters) => {
// An unset bound is dropped, so the stored blob carries only the bounds actually chosen
// and each tile keeps its own insight's value for the other one.
dateFrom ? (filters.date_from = dateFrom) : delete filters.date_from
dateTo ? (filters.date_to = dateTo) : delete filters.date_to
}, 'Could not apply that date range. Try again.')
if (saved) {
crossProjectDashboardTracking.edited(props.id, 'date_range')
}
},
setInterval: async ({ interval }) => {
const saved = await saveFilters((filters) => {
interval ? (filters.interval = interval) : delete filters.interval
}, 'Could not apply that interval. Try again.')
if (saved) {
crossProjectDashboardTracking.edited(props.id, 'interval')
}
},
enterLayoutEdit: () => {
lemonToast.info('Now editing the dashboard. Press E or click Save to persist changes.')
},
saveLayout: async () => {
if (values.layoutSaving) {
return
}
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId || !values.hasUnsavedLayoutChanges || !values.pendingLayouts) {
actions.exitLayoutEdit()
return
}
const updates = changedTileLayouts(values.tiles, values.pendingLayouts)
actions.saveLayoutStarted()
try {
const saved = await Promise.all(
updates.map((update) =>
crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, update.tileId, {
layouts: update.layouts,
})
)
)
// A reload would unmount the grid and refetch every tile.
applySavedTiles(saved)
actions.exitLayoutEdit()
lemonToast.success('Dashboard saved')
crossProjectDashboardTracking.edited(props.id, 'layout')
} catch (error: any) {
lemonToast.error(error?.detail || 'Could not save the layout. Try again.')
actions.saveLayoutFailed()
}
},
cancelLayoutEdit: () => {
const promptEnabled =
!!featureFlagLogic.values.featureFlags[FEATURE_FLAGS.DASHBOARD_LAYOUT_DISCARD_PROMPT]
if (!promptEnabled || !values.hasUnsavedLayoutChanges) {
actions.exitLayoutEdit()
return
}
LemonDialog.open({
title: 'Discard unsaved changes?',
description:
'You have unsaved layout changes. If you discard now, the dashboard will revert to its last saved state.',
primaryButton: {
children: 'Discard changes',
status: 'danger',
onClick: () => actions.exitLayoutEdit(),
'data-attr': 'cross-project-dashboard-edit-mode-discard-confirm',
},
secondaryButton: { children: 'Keep editing' },
})
},
setProperties: async ({ properties }) => {
const saved = await saveFilters((filters) => {
properties.length > 0 ? (filters.properties = properties) : delete filters.properties
}, 'Could not apply that filter. Try again.')
if (saved) {
// Checked here rather than on open: the answer only changes when the filter does.
actions.checkPropertyKeys()
crossProjectDashboardTracking.edited(props.id, 'property_filter')
}
},
setTileOverride: async ({ tileId, overrides }) => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId) {
return
}
try {
const saved = await crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, tileId, {
filters_overrides: overrides,
})
applySavedTiles([saved])
lemonToast.success('Tile filters saved')
crossProjectDashboardTracking.edited(props.id, 'tile_filters')
} catch (error: any) {
lemonToast.error(error?.detail || 'Could not save the tile filters. Try again.')
}
},
setTileColor: async ({ tileId, color }) => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId) {
return
}
try {
applySavedTiles([
await crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, tileId, { color }),
])
crossProjectDashboardTracking.edited(props.id, 'tile_color')
} catch (error: any) {
lemonToast.error(error?.detail || 'Could not change the tile color. Try again.')
}
},
removeTile: async ({ tileId }) => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId) {
return
}
const removedTile = values.tiles.find((tile) => tile.id === tileId)
try {
await crossProjectDashboardsTilesDestroy(organizationId, props.id, tileId)
crossProjectDashboardTracking.tileRemoved(props.id)
if (removedTile) {
lemonToast.info('Tile removed from the dashboard', {
button: {
label: 'Undo',
action: () => actions.restoreTile(removedTile),
dataAttr: 'cross-project-dashboard-tile-undo',
},
})
}
} catch (error: any) {
lemonToast.error(error?.detail || 'Could not remove that tile. Try again.')
}
actions.loadDashboard()
},
// Removal deletes the tile, so undo adds it back with everything it carried.
restoreTile: async ({ tile }) => {
const organizationId = organizationLogic.values.currentOrganization?.id
if (!organizationId || restoringTileIds.has(tile.id)) {
return
}
restoringTileIds.add(tile.id)
try {
await crossProjectDashboardsTilesCreate(organizationId, props.id, {
project_id: tile.project_id,
insight_id: tile.insight_id,
layouts: tile.layouts,
color: tile.color,
filters_overrides: tile.filters_overrides,
})
lemonToast.success('Tile restored')
crossProjectDashboardTracking.tileRestored(props.id)
} catch (error: any) {
lemonToast.error(error?.detail || 'Could not restore the tile. Add the insight again.')
} finally {
restoringTileIds.delete(tile.id)
}
actions.loadDashboard()
},
}
}),
beforeUnload(({ values, actions }) => ({
enabled: (newLocation) => {
if (!values.hasUnsavedLayoutChanges) {
return false
}
// An in-page navigation, such as opening a side panel, keeps the edits.
return !(newLocation && newLocation.pathname === router.values.location.pathname)
},
message: 'Leave dashboard?\nChanges you made to the layout will be discarded.',
onConfirm: () => actions.exitLayoutEdit(),
})),
afterMount(({ actions }) => {
actions.loadDashboard()
}),
])