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(product-analytics): let users copy PostHog Home into a dashboard (#120242)

Daniel Parker335c15bd534c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ad4da153f54c..30fb1c7e7ae2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14183,25 +14183,25 @@ snapshots:
scenes-app-product-analytics-home-chart-card--primary--light:
hash: v1.k794b7964.3029d681745bb041a125cd38a82c90d88e8c1c4f1c94e983f1a2afe002b399c7.P2tcznoufujQ1-OR3EiKU0wghPvd46O5Xx0NK-v0k3Y
scenes-app-product-analytics-home-dashboard-starter--ai-unavailable--dark:
- hash: v1.k794b7964.5bf7151d2a7e6ef56d5a76e338e75b59633fa7eb89147dbdd184d05786b20fed.8PVRxPC366nvKYdY0J2GsSAsYuMFCBJ07Oyofv4O_jA
+ hash: v1.k794b7964.ca3354bec47eaee1eb0fae23d182a64d8d0cd713567705afcac953c6c19ef250.wzNkYipTommWToi3oQ5z-aFFAuXUaxC43BcjqhMU7MQ
scenes-app-product-analytics-home-dashboard-starter--ai-unavailable--light:
- hash: v1.k794b7964.5f9f0a650d937fb0cffc296e40e8a41684924607128959f5f1900d7bc4b01311.5qPlWuFBvIco06jGpJL1swWQq59BCnILpz9AZNkkv0w
+ hash: v1.k794b7964.c12ccda55b30daba0b4e7d75c3d756ea6c71a5c1f6857f3bbf1fa75c08d9d058.L5YldxnOc04bbvuxKTRk2SyQK3tqQ8UcaXA3-bIobgU
scenes-app-product-analytics-home-dashboard-starter--creating-with-ai--dark:
- hash: v1.k794b7964.629ddf06258af494702a2160340959f0620bc81299448204eb93235a9109bafc.29iBASvfNT2PzBNlR3qTpPsdZi7etOSdwDCnH0wshjk
+ hash: v1.k794b7964.97e975c0c86805c9965fffc76bf4bcdeaa6cea0902c05d75b2c5bb2ffcff48ed.fqswmyImhQNt_FiYZuxn72GF00W6wgHSc_3v09E91BM
scenes-app-product-analytics-home-dashboard-starter--creating-with-ai--light:
- hash: v1.k794b7964.fd8ab5342ac51f4729f9a385de5dd5ab2956ffcd6b29eb1690a72a462bf90f4e.7bgTiJJU_H3zQo07hjK3q7qJ5-bNaY_GiHefUVE9JeM
+ hash: v1.k794b7964.7e2dcf46facadac0aad15ae614b6fff91c89b106f90eecf57df28816a7fddc02.1SX6H1XTurkL_ptYLeWaP85m95qbk5lBPBKHPyfxOcc
scenes-app-product-analytics-home-dashboard-starter--default--dark:
- hash: v1.k794b7964.774bf9c6790573a26157a45e4d8906da9b11c99802aabcee5ad6af747a344013.9J29IAXV-wsmcrNLKmNcBE6XpXriHSavjhlkQcQMfgw
+ hash: v1.k794b7964.cde090e3502edcb7a4bb7a44e6cef04bbfe4b12e39abc97d790f5d7249e8f2d9.N6oOnegrNLGQ_vYcK96iQ-MbN9x1rN3hRCzI66JVCd0
scenes-app-product-analytics-home-dashboard-starter--default--light:
- hash: v1.k794b7964.34810e36faf714c7bf5c221d7617aca16ce168c1ee3c3f227849a53c4e4ff026.M6O6oXEJbVYa_V8uAbBAKiI3absozEiU7BieF29xDhQ
+ hash: v1.k794b7964.26b8cb70fc4ca32258deca6f79f93bb278697aea07ac3d96caf96ee46fc506c8.XosQwFr2PN4U2qqYJDCaLuVINpJhduDtk9VwssP33Ao
scenes-app-product-analytics-home-dashboard-starter--narrow--dark:
- hash: v1.k794b7964.e706f55976c5b7194cb0c31f33144de525c0a49b658a1a18a86f6731fc5d4a7c.7WRp1QfY2fhPOPDq-gxBWB8LhLzrfk8IwJA7oS0jQiM
+ hash: v1.k794b7964.01d01b3843732f6177aade2c39becc7202ad453a18cda1f497e4a15e92c6a63d.AasvsiQogtVBtdczIu4akOIaup7k6_EI5_uCxBcNQQ0
scenes-app-product-analytics-home-dashboard-starter--narrow--light:
- hash: v1.k794b7964.276d0ef80178dc508a340cb81bf8f52296b6703670c087bb40eac140a32e2502.CaSSqGEDyId0v_dBLKPSZ8fdeD7T2EHYOl6aATO1HwQ
+ hash: v1.k794b7964.bbde0c6e0991a3f0db34a0fbca9613762516093e2caa56acc1afc31190d0263a.GZqzUp6SCY9ENtc0FcOv2wsgRHb1voVqylP7KI73oes
scenes-app-product-analytics-home-dashboard-starter--with-custom-dashboard--dark:
- hash: v1.k794b7964.7af35801aa8aa0db5a26914c106505559cc49bbf95fa8098cc84c74f8a52741d.IWvbgu_dQv4iVAPePRgd1d1A0t7BLfFoTHoe8Y_G0es
+ hash: v1.k794b7964.05e649d1fffdae1a3ab3e04ac3f9e4250dbfa1458bf627fcbef13552f3cd8987.5DIsAmvBW_GRTUuaeOfyldf8S5ZbrKIye5C_QKVOz_0
scenes-app-product-analytics-home-dashboard-starter--with-custom-dashboard--light:
- hash: v1.k794b7964.3955f90c8826d28cbc8ea87ae21c2736e2ff3b67999586e1901969a2a11a7acb.YjXt5UQ0a2xK9iFx0IGxA9lIQFU4q66REMcDhWsHAXs
+ hash: v1.k794b7964.d046e7c378631fbc809bf0516603a283be253fbfe9ee3c8670ef9f048240f8a5.Eup-VPPpS0s9a1iCk1V6W9Qo2fJ_05f1XcZfa5Alfw8
scenes-app-product-analytics-home-overview--before-ingestion--dark:
hash: v1.k794b7964.c9c3a3bcad0d8d6b1978454f6b7425e931171755e46d4422f9483a3f3e9d7066.OrUa2KPTzEeViZagRu3IMyexInpaS4_kRvrSd1LnKmk
scenes-app-product-analytics-home-overview--before-ingestion--light:
diff --git a/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx b/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx
index 3f519f73ebee..e78b46598b11 100644
--- a/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx
+++ b/frontend/src/lib/components/SceneDashboardChoice/SceneDashboardChoiceModal.tsx
@@ -49,7 +49,7 @@ export function SceneDashboardChoiceModal({ scene }: SceneDashboardChoiceModalPr
closeSceneDashboardChoiceModal()
}}
>
- {scene === Scene.ProductAnalyticsHomeTab ? 'Use PostHog Home' : 'Reset to "new tab"'}
+ {scene === Scene.ProductAnalyticsHomeTab ? 'Use default dashboard' : 'Reset to "new tab"'}
</LemonButton>
) : null}
<LemonButton
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 52363f8b20f5..054ce844c783 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -64,6 +64,8 @@ interface DashboardProps {
/** When set, the "Edit dashboard" menu item links to the dashboard editor with a back button pointing here. */
backTo?: { url: string; name: string }
showCreateAnomalyAlertButton?: boolean
+ /** Shows the dashboard without tile menus or drag-to-edit controls. */
+ readOnly?: boolean
}
export const parseDashboardId = (id: string | undefined): number => {
@@ -95,11 +97,12 @@ export function Dashboard({
themes,
backTo,
showCreateAnomalyAlertButton,
+ readOnly,
}: DashboardProps): JSX.Element {
useMountedLogic(dataThemeLogic({ themes }))
return (
- <BindLogic logic={dashboardLogic} props={{ id: parseDashboardId(id), placement, dashboard }}>
+ <BindLogic logic={dashboardLogic} props={{ id: parseDashboardId(id), placement, dashboard, readOnly }}>
<DashboardScene backTo={backTo} showCreateAnomalyAlertButton={showCreateAnomalyAlertButton} />
</BindLogic>
)
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 0df65df8966a..5393a6523304 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -321,6 +321,40 @@ describe('DashboardItems', () => {
)
})
+ it.each([
+ [false, true],
+ [true, false],
+ ])('with readOnly %s on a built-in dashboard, offers editing controls: %s', (readOnly, editable) => {
+ const defaultValues = mockedUseValues.getMockImplementation()!
+ mockedUseValues.mockImplementation((logic) =>
+ logic === dashboardLogic
+ ? {
+ ...defaultValues(logic),
+ placement: DashboardPlacement.Builtin,
+ readOnly,
+ layoutEditMode: false,
+ dashboardEditing: null,
+ }
+ : defaultValues(logic)
+ )
+
+ const setDashboardEditing = jest.fn()
+ const defaultActions = mockedUseActions.getMockImplementation()!
+ mockedUseActions.mockImplementation((logic) =>
+ logic === dashboardLogic ? { ...defaultActions(logic), setDashboardEditing } : defaultActions(logic)
+ )
+
+ render(<DashboardItems />)
+
+ const cardProps = mockInsightCard.mock.calls[mockInsightCard.mock.calls.length - 1][0]
+ expect(cardProps.showEditingControls).toBe(editable)
+ cardProps.onEnterEditModeFromEdge(
+ { target: document.body, clientX: 0, clientY: 0, nativeEvent: new MouseEvent('mousemove') },
+ 'e'
+ )
+ expect(setDashboardEditing).toHaveBeenCalledTimes(editable ? 1 : 0)
+ })
+
it.each([
['tight', '8,8'],
['condensed', '12,12'],
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 3455251daad3..ee41d04f2444 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -89,6 +89,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
layouts,
layoutEditMode,
placement,
+ readOnly,
isRefreshingQueued,
isRefreshing,
highlightedInsightId,
@@ -227,11 +228,11 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}
}, [containerRef])
const isMobileView = !!gridWidth && gridWidth <= BREAKPOINTS['sm']
- const isEditablePlacement = [
- DashboardPlacement.Dashboard,
- DashboardPlacement.ProjectHomepage,
- DashboardPlacement.Builtin,
- ].includes(placement)
+ const isEditablePlacement =
+ !readOnly &&
+ [DashboardPlacement.Dashboard, DashboardPlacement.ProjectHomepage, DashboardPlacement.Builtin].includes(
+ placement
+ )
const canEnterEditModeFromEdge =
!!dashboard && canEditDashboard && !layoutEditMode && !isMobileView && isEditablePlacement
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 3bb1db6084e3..101932845846 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -217,6 +217,8 @@ export interface DashboardLogicProps {
id: number
dashboard?: DashboardType
placement?: DashboardPlacement
+ /** Hides the tile menus and the drag-to-edit controls, even for users who can edit the dashboard. */
+ readOnly?: boolean
}
interface PendingFilterChange {
@@ -429,6 +431,7 @@ export interface dashboardLogicValues {
placement: DashboardPlacement
previewedDashboardSettings: DashboardSettings | null
projectTreeRef: ProjectTreeRef
+ readOnly: boolean
refreshEligibilityTick: number
refreshMetrics: {
completed: number
@@ -1283,6 +1286,7 @@ export interface dashboardLogicMeta {
) => boolean
asDashboardTemplate: (dashboard: DashboardType | null) => DashboardTemplateEditorType | undefined
placement: (arg: any) => DashboardPlacement
+ readOnly: (arg: any) => boolean
apiUrl: (
id: number
) => (
@@ -3177,6 +3181,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
() => [(_, props) => props.placement],
(placement): DashboardPlacement => placement || DashboardPlacement.Dashboard,
],
+ readOnly: [() => [(_, props) => props.readOnly], (readOnly: boolean | undefined): boolean => !!readOnly],
apiUrl: [
(_, p) => [p.id],
(id: number) => {
diff --git a/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.stories.tsx b/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.stories.tsx
index 5b1efd05322c..67e7aa26b551 100644
--- a/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.stories.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.stories.tsx
@@ -10,6 +10,7 @@ const meta: Meta<typeof HomeDashboardStarterModal> = {
args: {
isOpen: true,
onClose: noop,
+ onCopyPostHogHome: noop,
onTalkToAI: noop,
onStartFromTemplate: noop,
onChooseExisting: noop,
diff --git a/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx b/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx
index 816904f95b66..9da7d2277ee9 100644
--- a/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeDashboardStarterModal.tsx
@@ -1,9 +1,10 @@
-import { IconChevronRight, IconDashboard, IconHome, IconSparkles, IconStack } from '@posthog/icons'
+import { IconChevronRight, IconCopy, IconDashboard, IconHome, IconSparkles, IconStack } from '@posthog/icons'
import { LemonButton, LemonModal } from '@posthog/lemon-ui'
export interface HomeDashboardStarterModalProps {
isOpen: boolean
onClose: () => void
+ onCopyPostHogHome: () => void
onTalkToAI: () => void
onStartFromTemplate: () => void
onChooseExisting: () => void
@@ -17,6 +18,7 @@ export interface HomeDashboardStarterModalProps {
export function HomeDashboardStarterModal({
isOpen,
onClose,
+ onCopyPostHogHome,
onTalkToAI,
onStartFromTemplate,
onChooseExisting,
@@ -28,6 +30,15 @@ export function HomeDashboardStarterModal({
}: HomeDashboardStarterModalProps): JSX.Element {
const creationDisabledReason = creatingWithAI ? 'Creating your dashboard…' : undefined
const choices = [
+ {
+ title: 'Copy default dashboard',
+ description: 'Start with the charts you see on Home, then edit, add, or remove them.',
+ icon: <IconCopy />,
+ onClick: onCopyPostHogHome,
+ dataAttr: 'home-dashboard-copy-posthog-home',
+ loading: false,
+ disabledReason: creationDisabledReason,
+ },
{
title: 'Talk to PostHog AI',
description: 'Describe what you want to track and let PostHog AI build it.',
@@ -101,9 +112,9 @@ export function HomeDashboardStarterModal({
data-attr="home-dashboard-restore-posthog-home"
>
<span className="flex min-w-0 flex-col gap-0.5 py-1">
- <span className="font-semibold">Use PostHog Home</span>
+ <span className="font-semibold">Use default dashboard</span>
<span className="whitespace-normal text-xs font-normal text-secondary">
- Return to the ready-made product analytics overview.
+ Go back to the default product analytics dashboard.
</span>
</span>
</LemonButton>
diff --git a/products/product_analytics/frontend/insights/home/HomeTab.test.tsx b/products/product_analytics/frontend/insights/home/HomeTab.test.tsx
index 80e47ab39158..b1f4bc0664ed 100644
--- a/products/product_analytics/frontend/insights/home/HomeTab.test.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTab.test.tsx
@@ -2,13 +2,15 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
import { HomeTab } from './HomeTab'
+import { homeTabDashboardProps } from './homeTabDashboardLogic'
jest.mock('./HomeTabDefault', () => ({
HomeTabDefault: () => <div>PostHog Home</div>,
@@ -35,6 +37,23 @@ describe('HomeTab', () => {
expect(screen.getByText(expectedContent)).toBeInTheDocument()
})
+ it('falls back to PostHog Home and reloads the team when the selected dashboard is gone', () => {
+ initKeaTests()
+ teamLogic.mount()
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ home_tab_dashboard: 42,
+ })
+ render(<HomeTab />)
+
+ act(() => {
+ dashboardLogic(homeTabDashboardProps(42)).actions.dashboardNotFound()
+ })
+
+ expect(screen.getByText('PostHog Home')).toBeInTheDocument()
+ expect(teamLogic.values.currentTeamLoading).toBe(true)
+ })
+
it('keeps the selected dashboard visible while team data refreshes', () => {
initKeaTests()
teamLogic.mount()
diff --git a/products/product_analytics/frontend/insights/home/HomeTab.tsx b/products/product_analytics/frontend/insights/home/HomeTab.tsx
index 75e98e1b05fd..6c71c76a2c60 100644
--- a/products/product_analytics/frontend/insights/home/HomeTab.tsx
+++ b/products/product_analytics/frontend/insights/home/HomeTab.tsx
@@ -4,12 +4,10 @@ import type { ReactNode } from 'react'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { Dashboard } from 'scenes/dashboard/Dashboard'
import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
import { teamLogic } from 'scenes/teamLogic'
-import { DashboardPlacement } from '~/types'
-
+import { HomeTabDashboard } from './HomeTabDashboard'
import { HomeTabDefault } from './HomeTabDefault'
export function HomeTab({ dashboardActions }: { dashboardActions?: ReactNode }): JSX.Element {
@@ -41,9 +39,7 @@ export function HomeTab({ dashboardActions }: { dashboardActions?: ReactNode }):
<LemonSkeleton.Row repeat={3} />
</div>
) : currentTeam?.home_tab_dashboard ? (
- <div className="-mt-8">
- <Dashboard id={String(currentTeam.home_tab_dashboard)} placement={DashboardPlacement.Builtin} />
- </div>
+ <HomeTabDashboard dashboardId={currentTeam.home_tab_dashboard} dashboardActions={dashboardActions} />
) : (
<HomeTabDefault dashboardActions={dashboardActions} />
)}
diff --git a/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx b/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx
new file mode 100644
index 000000000000..da0331673cf7
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/HomeTabDashboard.tsx
@@ -0,0 +1,27 @@
+import { useValues } from 'kea'
+import type { ReactNode } from 'react'
+
+import { Dashboard } from 'scenes/dashboard/Dashboard'
+
+import { homeTabDashboardLogic, homeTabDashboardProps } from './homeTabDashboardLogic'
+import { HomeTabDefault } from './HomeTabDefault'
+
+export function HomeTabDashboard({
+ dashboardId,
+ dashboardActions,
+}: {
+ dashboardId: number
+ dashboardActions?: ReactNode
+}): JSX.Element {
+ const { dashboardMissing } = useValues(homeTabDashboardLogic({ dashboardId }))
+
+ if (dashboardMissing) {
+ return <HomeTabDefault dashboardActions={dashboardActions} />
+ }
+ const { id, placement, readOnly } = homeTabDashboardProps(dashboardId)
+ return (
+ <div className="-mt-8">
+ <Dashboard id={String(id)} placement={placement} readOnly={readOnly} />
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts b/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts
new file mode 100644
index 000000000000..c3122e29287c
--- /dev/null
+++ b/products/product_analytics/frontend/insights/home/homeTabDashboardLogic.ts
@@ -0,0 +1,74 @@
+import { MakeLogicType, connect, kea, key, listeners, path, props, selectors } from 'kea'
+
+import { DashboardLogicProps, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { DashboardPlacement, DashboardType } from '~/types'
+
+export interface HomeTabDashboardLogicProps {
+ dashboardId: number
+}
+
+export const homeTabDashboardProps = (dashboardId: number): DashboardLogicProps => ({
+ id: dashboardId,
+ placement: DashboardPlacement.Builtin,
+ readOnly: true,
+})
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabDashboardLogicValues {
+ dashboard: DashboardType | null // dashboardLogic
+ error404: boolean // dashboardLogic
+ dashboardMissing: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabDashboardLogicActions {
+ dashboardNotFound: () => {
+ value: true
+ } // dashboardLogic
+ loadCurrentTeam: () => any // teamLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface homeTabDashboardLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ dashboardMissing: (error404: boolean, dashboard: DashboardType | null) => boolean
+ }
+}
+
+export type homeTabDashboardLogicType = MakeLogicType<
+ homeTabDashboardLogicValues,
+ homeTabDashboardLogicActions,
+ HomeTabDashboardLogicProps,
+ homeTabDashboardLogicMeta
+>
+
+export const homeTabDashboardLogic = kea<homeTabDashboardLogicType>([
+ props({} as HomeTabDashboardLogicProps),
+ key((props) => props.dashboardId),
+ path((key) => ['products', 'product_analytics', 'home', 'homeTabDashboardLogic', key]),
+ connect((props: HomeTabDashboardLogicProps) => ({
+ values: [dashboardLogic(homeTabDashboardProps(props.dashboardId)), ['dashboard', 'error404']],
+ actions: [
+ dashboardLogic(homeTabDashboardProps(props.dashboardId)),
+ ['dashboardNotFound'],
+ teamLogic,
+ ['loadCurrentTeam'],
+ ],
+ })),
+ selectors({
+ dashboardMissing: [
+ (s) => [s.error404, s.dashboard],
+ (error404: boolean, dashboard: DashboardType | null): boolean => error404 && !dashboard,
+ ],
+ }),
+ listeners(({ actions }) => ({
+ // Another tab or person can delete the dashboard after this team loaded. The backend clears
+ // the Home dashboard on delete, so a reload returns the team to PostHog Home.
+ dashboardNotFound: () => {
+ actions.loadCurrentTeam()
+ },
+ })),
+])
diff --git a/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.test.ts b/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.test.ts
index ee6eab62244e..6da86fd5acfc 100644
--- a/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.test.ts
+++ b/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.test.ts
@@ -18,6 +18,7 @@ import {
getHomeTabAudienceOptions,
getHomeTabBreakdownOptions,
getHomeTabChartOptions,
+ getHomeTabDashboardTemplate,
getHomeTabExploreUrl,
getHomeTabInterval,
getHomeTabStatQueries,
@@ -286,4 +287,62 @@ describe('homeTabDefaultTiles', () => {
expect(editorQuery.source).toEqual(JSON.parse(JSON.stringify(chart!.query.source)))
expect(editorQuery.source.dateRange).toEqual(dateRange)
})
+
+ it('copies Home into a dashboard template with saved queries and a non-overlapping layout', () => {
+ const { tiles } = getHomeTabDashboardTemplate()
+
+ expect(tiles.map((tile) => tile.type === 'INSIGHT' && tile.name)).toEqual([
+ 'Weekly active users',
+ 'Sessions',
+ 'First-time users',
+ 'Avg. session duration',
+ 'Avg. DAU',
+ 'Daily active users',
+ 'Top pages',
+ 'Top screens',
+ 'Top events',
+ 'New user retention',
+ 'Active users by country',
+ 'Sessions by device',
+ ])
+ const cells = new Set<string>()
+ for (const tile of tiles) {
+ expect(tile.type === 'INSIGHT' && tile.query).toMatchObject({ kind: NodeKind.InsightVizNode })
+ expect(tile.type === 'INSIGHT' && tile.query).not.toHaveProperty('embedded')
+ const { x, y, w, h } = tile.layouts!.sm!
+ expect(x + w).toBeLessThanOrEqual(12)
+ for (let column = x; column < x + w; column++) {
+ for (let row = y; row < y + h; row++) {
+ expect(cells.has(`${column},${row}`)).toBe(false)
+ cells.add(`${column},${row}`)
+ }
+ }
+ }
+ expect(tiles.slice(0, 5).map((tile) => tile.type === 'INSIGHT' && tile.query)).toMatchObject([
+ {
+ source: {
+ series: [{ math: BaseMathType.WeeklyActiveUsers }],
+ interval: 'day',
+ trendsFilter: { display: ChartDisplayType.Metric, metricSummary: 'latest' },
+ },
+ },
+ { source: { trendsFilter: { display: ChartDisplayType.Metric, metricSummary: 'total' } } },
+ { source: { trendsFilter: { display: ChartDisplayType.Metric, metricSummary: 'total' } } },
+ {
+ source: {
+ trendsFilter: {
+ display: ChartDisplayType.Metric,
+ metricSummary: 'average',
+ aggregationAxisFormat: 'duration',
+ },
+ },
+ },
+ {
+ source: {
+ interval: 'day',
+ trendsFilter: { display: ChartDisplayType.Metric, metricSummary: 'average' },
+ },
+ },
+ ])
+ })
})
diff --git a/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts b/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts
index 4136f0b90327..3a2d40ea69d9 100644
--- a/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts
+++ b/products/product_analytics/frontend/insights/home/homeTabDefaultTiles.ts
@@ -18,6 +18,8 @@ import {
import {
BaseMathType,
ChartDisplayType,
+ DashboardTemplateStoredInsightTile,
+ DashboardTemplateType,
FilterLogicalOperator,
IntervalType,
PropertyMathType,
@@ -28,7 +30,7 @@ import {
TrendResult,
} from '~/types'
-import type { HomeTabMetricKey } from './homeTabDefaultLogic'
+import { HOME_TAB_DEFAULT_DATE_RANGE, type HomeTabMetricKey } from './homeTabDefaultLogic'
/** A single-number stat shown in the compact tile row at the top of the Home tab. */
export interface HomeTabStatQuery {
@@ -472,3 +474,107 @@ export function getHomeTabExploreUrl(query: HomeTabChartOption['query']): string
const insightQuery: HomeTabChartOption['query'] = { ...query, embedded: undefined }
return urls.insightNew({ query: insightQuery })
}
+
+interface HomeTabDashboardTile {
+ name: string
+ description: string
+ source: TrendsQuery | RetentionQuery
+ w: number
+ h: number
+}
+
+// The Metric display (number with a sparkline) sums the interval points, which counts a person once per
+// active day. Weekly active users on the latest day counts each person once and still has a daily trend.
+const HOME_TAB_STAT_METRIC_SUMMARIES: Record<HomeTabMetricKey, 'total' | 'average' | 'latest'> = {
+ active_users: 'latest',
+ sessions: 'total',
+ new_users: 'total',
+ session_duration: 'average',
+ daily_active_users: 'average',
+}
+
+const HOME_TAB_STAT_DASHBOARD_NAMES: Partial<Record<HomeTabMetricKey, string>> = {
+ active_users: 'Weekly active users',
+ session_duration: 'Avg. session duration',
+}
+
+/** PostHog Home as a dashboard template, so a copy keeps the Home charts and the user can edit them. */
+export function getHomeTabDashboardTemplate(): DashboardTemplateType {
+ const dateRange = HOME_TAB_DEFAULT_DATE_RANGE
+ const compare = true
+ const charts = new Map(
+ [
+ ...getHomeTabChartOptions(dateRange, compare),
+ ...getHomeTabBreakdownOptions(dateRange),
+ ...getHomeTabAudienceOptions(dateRange),
+ ].map((option) => [option.key, option])
+ )
+ const chartTile = (key: string, w: number, h: number): HomeTabDashboardTile => {
+ const chart = charts.get(key)
+ if (!chart) {
+ throw new Error(`Home chart ${key} does not exist`)
+ }
+ return { name: chart.title, description: chart.description, source: chart.query.source, w, h }
+ }
+ const statTiles = getHomeTabStatQueries(dateRange, compare).map((stat): HomeTabDashboardTile => {
+ const weeklyActiveUsers = stat.key === 'active_users'
+ return {
+ name: HOME_TAB_STAT_DASHBOARD_NAMES[stat.key] ?? stat.title,
+ description: '',
+ source: {
+ ...stat.query,
+ ...(weeklyActiveUsers
+ ? {
+ series: [activityEvent(BaseMathType.WeeklyActiveUsers)],
+ interval: 'day',
+ compareFilter: { compare: false },
+ }
+ : {}),
+ trendsFilter: {
+ ...stat.query.trendsFilter,
+ display: ChartDisplayType.Metric,
+ metricSummary: HOME_TAB_STAT_METRIC_SUMMARIES[stat.key],
+ ...(stat.kind === 'duration_s' ? { aggregationAxisFormat: 'duration' } : {}),
+ },
+ },
+ w: weeklyActiveUsers || stat.key === 'daily_active_users' ? 3 : 2,
+ h: 3,
+ }
+ })
+ const rows: HomeTabDashboardTile[][] = [
+ statTiles,
+ [chartTile('daily_active_users', 12, 5)],
+ [chartTile('top_pages', 6, 5), chartTile('top_screens', 6, 5)],
+ [chartTile('top_events', 6, 5), chartTile('retention', 6, 5)],
+ [chartTile('users_by_country', 8, 6), chartTile('sessions_by_device', 4, 6)],
+ ]
+
+ const tiles: DashboardTemplateStoredInsightTile[] = []
+ let y = 0
+ let stackedY = 0
+ for (const row of rows) {
+ let x = 0
+ for (const { name, description, source, w, h } of row) {
+ tiles.push({
+ type: 'INSIGHT',
+ name,
+ description,
+ query: { kind: NodeKind.InsightVizNode, source },
+ layouts: { sm: { x, y, w, h }, xs: { x: 0, y: stackedY, w: 1, h } },
+ })
+ x += w
+ stackedY += h
+ }
+ y += Math.max(...row.map(({ h }) => h))
+ }
+
+ return {
+ id: 'product-analytics-home',
+ template_name: 'My product analytics Home',
+ dashboard_description: 'A copy of the default product analytics dashboard. You can edit, add, or remove tiles.',
+ dashboard_filters: {},
+ tiles,
+ variables: [],
+ tags: [],
+ }
+}
diff --git a/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx b/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx
index 49367c4f0724..b3acc6756cb6 100644
--- a/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx
+++ b/products/product_analytics/frontend/insights/savedInsights/SavedInsights.tsx
@@ -61,6 +61,7 @@ import { AccessControlLevel, AccessControlResourceType, ActivityScope, SavedInsi
import { productAnalyticsEmptyState } from 'products/product_analytics/frontend/emptyState/productAnalyticsEmptyState'
import { HomeDashboardStarterModal } from 'products/product_analytics/frontend/insights/home/HomeDashboardStarterModal'
import { HomeTab } from 'products/product_analytics/frontend/insights/home/HomeTab'
+import { getHomeTabDashboardTemplate } from 'products/product_analytics/frontend/insights/home/homeTabDefaultTiles'
import { NewInsightButton } from 'products/product_analytics/frontend/insights/newInsightMenu/NewInsightMenu'
import { NewInsightShortcuts } from 'products/product_analytics/frontend/insights/newInsightMenu/newInsightsMenu'
import { ProductAnalyticsNotifications } from 'products/product_analytics/frontend/notifications/ProductAnalyticsNotifications'
@@ -113,7 +114,8 @@ export function SavedInsights(): JSX.Element {
showStarterOptions,
} = useActions(dashboardChoiceLogic)
const { isLoading: dashboardCreationLoading } = useValues(newDashboardLogic)
- const { addDashboard, setAsHomeTabDashboardAfterCreation, showNewDashboardModal } = useActions(newDashboardLogic)
+ const { addDashboard, createDashboardFromTemplate, setAsHomeTabDashboardAfterCreation, showNewDashboardModal } =
+ useActions(newDashboardLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
const { tab } = filters
@@ -348,6 +350,15 @@ export function SavedInsights(): JSX.Element {
})
}
+ const copyPostHogHome = (): void => {
+ if (dashboardCreationLoading) {
+ return
+ }
+ closeSceneDashboardChoiceModal()
+ setAsHomeTabDashboardAfterCreation(true)
+ createDashboardFromTemplate(getHomeTabDashboardTemplate(), [], false, 'product_analytics_home_copy')
+ }
+
const openHomeDashboardTemplates = (): void => {
closeSceneDashboardChoiceModal()
setAsHomeTabDashboardAfterCreation(true)
@@ -364,13 +375,18 @@ export function SavedInsights(): JSX.Element {
currentTeam?.home_tab_dashboard ? (
<LemonMenu
items={[
+ {
+ label: 'Open dashboard',
+ to: urls.dashboard(currentTeam.home_tab_dashboard),
+ 'data-attr': 'home-tab-open-dashboard',
+ },
{
label: 'Change Home dashboard',
onClick: openHomeDashboardStarter,
'data-attr': 'home-tab-choose-dashboard',
},
{
- label: 'Use PostHog Home',
+ label: 'Use default dashboard',
onClick: restorePostHogHome,
'data-attr': 'home-tab-restore-posthog-home',
},
@@ -438,6 +454,12 @@ export function SavedInsights(): JSX.Element {
<TooltipContent>Home dashboard options</TooltipContent>
</QuillTooltip>
<DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuItem
+ onClick={() => push(urls.dashboard(currentTeam.home_tab_dashboard!))}
+ data-attr="home-tab-open-dashboard"
+ >
+ Open dashboard
+ </DropdownMenuItem>
<DropdownMenuItem
onClick={openHomeDashboardStarter}
data-attr="home-tab-choose-dashboard"
@@ -448,7 +470,7 @@ export function SavedInsights(): JSX.Element {
onClick={restorePostHogHome}
data-attr="home-tab-restore-posthog-home"
>
- Use PostHog Home
+ Use default dashboard
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -505,6 +527,7 @@ export function SavedInsights(): JSX.Element {
<HomeDashboardStarterModal
isOpen={homeDashboardModalOpen && dashboardChoiceView === 'starter'}
onClose={closeSceneDashboardChoiceModal}
+ onCopyPostHogHome={copyPostHogHome}
onTalkToAI={createHomeDashboardWithAI}
onStartFromTemplate={openHomeDashboardTemplates}
onChooseExisting={showDashboardPicker}