: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
fix(insights): match home sample charts to live data (#116026)
Daniel Parkere137c7c0ece6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 517737e5e825..aea4fb14f6fb 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13362,6 +13362,10 @@ snapshots:hash: v1.k794b7964.7af35801aa8aa0db5a26914c106505559cc49bbf95fa8098cc84c74f8a52741d.IWvbgu_dQv4iVAPePRgd1d1A0t7BLfFoTHoe8Y_G0esscenes-app-product-analytics-home-dashboard-starter--with-custom-dashboard--light:hash: v1.k794b7964.3955f90c8826d28cbc8ea87ae21c2736e2ff3b67999586e1901969a2a11a7acb.YjXt5UQ0a2xK9iFx0IGxA9lIQFU4q66REMcDhWsHAXs+ scenes-app-product-analytics-home-overview--before-ingestion--dark:+ hash: v1.k794b7964.5c36b1b0d87d73dfcfea7bcb2fe8cd15a04686439f90cda7745b7b082594084e.zrTwy8dlOOfkqeuaHrtsMrWuzISvRfirpNwEGucFQjY+ scenes-app-product-analytics-home-overview--before-ingestion--light:+ hash: v1.k794b7964.1592f53eebdac858bb95c394a03ed074b82fbf6ad4e066ced25894138efba2b4.zlvZTFmxl2PnEPVKSMYNB_ilmXSAzojEMT3JhBZWicEscenes-app-product-analytics-home-overview--empty--dark:hash: v1.k794b7964.803d51407dca494e41d04f4cb5fb324abd193b22d9cad2b60b92087ec1bf76b5.nESq7Ay6ngu1UriAYHASMUKdnt6lU8FQZwgXkFcizKwscenes-app-product-analytics-home-overview--empty--light:diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.scss b/frontend/src/scenes/insights/EmptyStates/SampleDataState.scssindex 38c0618dda7a..704163959035 100644--- a/frontend/src/scenes/insights/EmptyStates/SampleDataState.scss+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.scss@@ -31,6 +31,13 @@}}+ &__viz--custom {+ flex-direction: column;+ align-items: stretch;+ justify-content: flex-start;+ padding-top: 2rem;+ }+&__chart {// The quill chart root stretches via flex-1, so it needs a flex column parentdisplay: flex;diff --git a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsxindex c4c621b66e82..19bc5a19e16e 100644--- a/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx+++ b/frontend/src/scenes/insights/EmptyStates/SampleDataState.tsx@@ -2,7 +2,7 @@ import './SampleDataState.scss'import clsx from 'clsx'import { useValues } from 'kea'-import { useEffect, useState } from 'react'+import { useEffect, useState, type ReactNode } from 'react'import { TextMorph } from 'torph/react'import { LemonButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'@@ -181,7 +181,13 @@ function SampleDataTooltipContent(): JSX.Element {}/** Obviously-fake placeholder chart shown instead of an empty state before a project has ingested any events. */-export function SampleDataState({ variant = 'line' }: { variant?: SampleDataVariant }): JSX.Element {+export function SampleDataState({+ variant = 'line',+ children,+}: {+ variant?: SampleDataVariant+ children?: ReactNode+}): JSX.Element {const { setupStatus, setupStatusLoading } = useValues(setupWizardStatusLogic)const { wizardCommand, isCloudOrDev } = useWizardCommand()const isStatic =@@ -228,7 +234,7 @@ export function SampleDataState({ variant = 'line' }: { variant?: SampleDataVari</LemonTag></Tooltip>)}- {variant === 'line' && !setupStatus && !setupStatusLoading && isCloudOrDev && (+ {!children && variant === 'line' && !setupStatus && !setupStatusLoading && isCloudOrDev && (<Tooltiptitle={<div className="max-w-72 space-y-1.5 p-0.5">@@ -262,14 +268,15 @@ export function SampleDataState({ variant = 'line' }: { variant?: SampleDataVari</LemonTag></Tooltip></div>- <div className="SampleDataState__viz">- {variant === 'number' ? (- <SampleNumber animate={!isStatic} />- ) : variant === 'table' ? (- <SampleTable />- ) : (- <SampleChart variant={variant} />- )}+ <div className={clsx('SampleDataState__viz', children && 'SampleDataState__viz--custom')}>+ {children ??+ (variant === 'number' ? (+ <SampleNumber animate={!isStatic} />+ ) : variant === 'table' ? (+ <SampleTable />+ ) : (+ <SampleChart variant={variant} />+ ))}</div></div>)diff --git a/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx b/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsxindex 17ff59e2ab63..d8939e5a9313 100644--- a/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx+++ b/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx@@ -1,12 +1,14 @@import './HomeTabChartCard.scss'import { useValues } from 'kea'-import type { ReactNode } from 'react'+import { useMemo, type ReactNode } from 'react'import { IconInfo } from '@posthog/icons'import { LemonButton, LemonCard } from '@posthog/lemon-ui'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { SampleDataState } from 'scenes/insights/EmptyStates/SampleDataState'+import { sampleDataStateLogic } from 'scenes/insights/EmptyStates/sampleDataStateLogic'import { teamLogic } from 'scenes/teamLogic'import { Query } from '~/queries/Query/Query'@@ -14,6 +16,7 @@ import { Query } from '~/queries/Query/Query'import { homeTabDefaultLogic } from './homeTabDefaultLogic'import { getHomeTabExploreUrl, type HomeTabChartOption } from './homeTabDefaultTiles'import { homeTabChartInsightId, homeTabDataCollectionId } from './homeTabQueryKeys'+import { getHomeTabSampleData } from './homeTabSampleData'interface HomeTabChartCardProps {option: HomeTabChartOption@@ -24,6 +27,30 @@ interface HomeTabChartCardProps {export function HomeTabChartCard({ option, size, control, source }: HomeTabChartCardProps): JSX.Element {const { currentTeamId } = useValues(teamLogic)+ const { shouldShowSampleData } = useValues(sampleDataStateLogic)+ const sampleData = useMemo(+ () => (shouldShowSampleData ? getHomeTabSampleData(option) : undefined),+ [shouldShowSampleData, option]+ )+ const chartKey = sampleData ? `${option.key}.sample` : option.key+ const chart = (+ <Query+ key={`${currentTeamId}.${chartKey}`}+ query={option.query}+ readOnly+ inSharedMode={!!sampleData}+ cachedResults={sampleData}+ uniqueKey={`HomeTab.${currentTeamId}.${chartKey}`}+ context={{+ insightProps: {+ dashboardItemId: homeTabChartInsightId(currentTeamId, chartKey),+ dataNodeCollectionId: homeTabDataCollectionId(currentTeamId),+ query: option.query,+ },+ }}+ attachTo={homeTabDefaultLogic}+ />+ )return (<LemonCard hoverEffect={false} className="HomeTabChartCard flex min-w-0 flex-col overflow-hidden p-0"><div className="HomeTabChartCard__header border-b border-primary px-4 py-2.5">@@ -55,20 +82,7 @@ export function HomeTabChartCard({ option, size, control, source }: HomeTabChart<divclassName={`HomeTabDefaultChart HomeTabChartCard__visualization HomeTabChartCard__visualization--${size}`}>- <Query- key={currentTeamId}- query={option.query}- readOnly- uniqueKey={`HomeTab.${currentTeamId}.${option.key}`}- context={{- insightProps: {- dashboardItemId: homeTabChartInsightId(currentTeamId, option.key),- dataNodeCollectionId: homeTabDataCollectionId(currentTeamId),- query: option.query,- },- }}- attachTo={homeTabDefaultLogic}- />+ {sampleData ? <SampleDataState>{chart}</SampleDataState> : chart}</div></LemonCard>)diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.stories.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.stories.tsxindex 7891a5fc89a1..56ec713eaf62 100644--- a/products/product_analytics/frontend/insights/home/HomeTabDefault.stories.tsx+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.stories.tsx@@ -1,5 +1,9 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { Meta, StoryObj } from '@storybook/react'+import { teamLogic } from 'scenes/teamLogic'+import { mswDecorator } from '~/mocks/browser'import trendsBarBreakdown from '~/mocks/fixtures/api/projects/team_id/insights/trendsBarBreakdown.json'import trendsLine from '~/mocks/fixtures/api/projects/team_id/insights/trendsLine.json'@@ -183,3 +187,22 @@ export const Empty: Story = {}),],}++export const BeforeIngestion: Story = {+ render: () => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, ingested_event: false, is_demo: false })+ return (+ <div className="@container/main-content mx-auto w-full max-w-screen-xl p-4">+ <HomeTabDefault />+ </div>+ )+ },+ decorators: [+ mswDecorator({+ post: {+ '/api/environments/:team_id/query/': { results: [] },+ '/api/environments/:team_id/query/:query_kind/': { results: [] },+ },+ }),+ ],+}diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsxindex dc14d903aae2..59db928e839d 100644--- a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx@@ -1,3 +1,5 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import '@testing-library/jest-dom'import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'@@ -76,4 +78,19 @@ describe('HomeTabDefault query reuse', () => {within(screen.getByLabelText('Active users', { selector: 'button' })).getByText('20')).toBeInTheDocument()})++ it('replaces sample charts with live queries when the project starts receiving events', async () => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, ingested_event: false, is_demo: false })+ const { container } = render(<HomeTabDefault />)++ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(6))+ expect(container.querySelectorAll('[data-attr="insight-sample-data-state"]')).toHaveLength(5)++ await act(async () => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, ingested_event: true, is_demo: false })+ })++ await waitFor(() => expect(mockedQuery).toHaveBeenCalledTimes(11))+ expect(container.querySelector('[data-attr="insight-sample-data-state"]')).toBeNull()+ })})diff --git a/products/product_analytics/frontend/insights/home/homeTabSampleData.ts b/products/product_analytics/frontend/insights/home/homeTabSampleData.tsnew file mode 100644index 000000000000..0fe7a36f2a2d--- /dev/null+++ b/products/product_analytics/frontend/insights/home/homeTabSampleData.ts@@ -0,0 +1,87 @@+import { dayjs } from 'lib/dayjs'++import { NodeKind, RetentionQueryResponse, TrendsQueryResponse } from '~/queries/schema/schema-general'+import { TrendResult } from '~/types'++import { HomeTabChartOption } from './homeTabDefaultTiles'++const BREAKDOWNS: Record<string, [string, number][]> = {+ users_by_country: [+ ['US', 640],+ ['GB', 280],+ ['DE', 210],+ ['IN', 180],+ ['BR', 120],+ ['AU', 90],+ ],+ sessions_by_device: [+ ['Desktop', 640],+ ['Mobile', 280],+ ['Tablet', 80],+ ],+ top_pages: [+ ['/', 1280],+ ['/pricing', 940],+ ['/docs', 720],+ ['/signup', 480],+ ['/blog', 260],+ ],+ top_screens: [+ ['Home', 1280],+ ['Search', 940],+ ['Settings', 720],+ ['Profile', 480],+ ],+ top_events: [+ ['$pageview', 1280],+ ['$autocapture', 940],+ ['$screen', 720],+ ['signed_up', 480],+ ['purchase', 260],+ ],+}++export function getHomeTabSampleData(+ option: HomeTabChartOption+): TrendsQueryResponse | RetentionQueryResponse | undefined {+ const source = option.query.source+ if (source.kind === NodeKind.RetentionQuery) {+ const intervals = source.retentionFilter.totalIntervals ?? 5+ const end = dayjs().startOf('week').subtract(1, 'week')+ return {+ results: Array.from({ length: intervals }, (_, cohortIndex) => {+ const size = 240 + cohortIndex * 30+ return {+ label: `Week ${cohortIndex}`,+ date: end.subtract(intervals - cohortIndex - 1, 'week').toISOString(),+ values: Array.from({ length: intervals - cohortIndex }, (_, interval) => ({+ count: interval === 0 ? size : Math.round(size * 0.6 * 0.75 ** (interval - 1)),+ })),+ }+ }),+ }+ }++ const breakdowns = BREAKDOWNS[option.key]+ if (!breakdowns) {+ return undefined+ }++ const results: TrendResult[] = breakdowns.map(([label, count]) => ({+ action: {+ id: source.series[0].kind === NodeKind.EventsNode ? (source.series[0].event ?? null) : null,+ type: 'events',+ order: 0,+ name: 'Sample',+ math: source.series[0].math,+ },+ label,+ breakdown_value: label,+ count,+ aggregated_value: count,+ data: [count],+ days: [dayjs().format('YYYY-MM-DD')],+ labels: ['Sample'],+ }))+ return { results }+}