: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
feat(web-analytics): trial MetricCard for overview number cards (#61984)
Paul D'Ambra291fbf97dd52
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5e35240216bf..272e3befcc60 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6222,6 +6222,10 @@ snapshots:hash: v1.k794b7964.7b4434236a2118c3a34540cf8245f4f9f08f1d209f868d5323462332160275d0.wUzGBcvTbECroCJ6uEjdcozJUJq1uniLxVkSYMaEvAwscenes-app-web-analytics--web-analytics-dashboard-loading--light:hash: v1.k794b7964.86d2e5319eeddd603f5ca5b3da1fe1156d198f9d543dc5e5ad9cf0068faeb521.4i-CGLH6Jyfjj_hg-B6BtjyrJRQScB1RHuMy0Av-MgU+ scenes-app-web-analytics--web-analytics-dashboard-metric-cards--dark:+ hash: v1.k794b7964.a57cc69f41eeba38ce0d9c16808cdc7d24931406bcad89c37f4d0cb301139714.IP-A5Q2EQ8BQCoKz5qxWQoMW7O68rWW-35rEf739uQ8+ scenes-app-web-analytics--web-analytics-dashboard-metric-cards--light:+ hash: v1.k794b7964.f93eaa7cef4cefb54ea4eb0ae632e77b95ad2c651cb383c479c231cef702f536.AuCTvG5Bk1P7Ju6VmVPTCtPvh_5qHa8lft-mGXoEf8Ascenes-other-billing--billing--dark:hash: v1.k794b7964.7d8d15966d60d5c51ac111ecad259fb4bbe471cbc293fc270ebf2f56809c8d85.90swJKlcQ3DfRle4imvs1QT0vP0TYxJsqA_8dQEbl2Escenes-other-billing--billing--light:@@ -6882,6 +6886,26 @@ snapshots:hash: v1.k794b7964.c17be7ebf593bcdc6ad760d1ae2035be3dadad1e049d39ef6c72b9e093a03067.KVwJMpXcfhchvEMKnnqsNnyBE6EI5d9YIUWIB-08xfYutils-autocapture-preview-image--tab-relative-image-with-current-url--light:hash: v1.k794b7964.3e7d7a6fa83916bae8280f36864538241c45bd4122e167b299a046939c802b03.oW1U5X9JYmxSLcn72S6kPmgj_jxgZTKyJa0uZ1kbRJs+ web-analytics-overview-metric-cards--conversion-goal--dark:+ hash: v1.k794b7964.ffd8e9b5ff6b2d9960c9c7fda017852e9e1c1958edf258a64b9e10709267bf54.q_8D22J2_TiOOAHEP0Y-Tc-3E0qc1ciosb29dOzCEVw+ web-analytics-overview-metric-cards--conversion-goal--light:+ hash: v1.k794b7964.6f4ee701d4ebf203016caf563106c3abe869c06189db2bdaf1b5599f0345580c.4S3FzL7yk2UG0G14LUs9Q6pqrMzLFE_0Ny-s5joL9Mc+ web-analytics-overview-metric-cards--default--dark:+ hash: v1.k794b7964.26014b56230710ce79a961172145b41f4ce07b74ab0ee7cbccf7f3fb0d4ff9a8.fVflpLBVpngwXsyreeIMfHzyJIS1xKEyxgPCZAmZenc+ web-analytics-overview-metric-cards--default--light:+ hash: v1.k794b7964.12aefb12da3286087ca38df4297bae1d84fd491a77558e91c2da67ec4b7dfcad.YQonGS1VRcemHrcwHYx0b8ZjuqvAoh13CeOkG0Iic_o+ web-analytics-overview-metric-cards--loading--dark:+ hash: v1.k794b7964.c4b0f2c685343cc0ae169e4a45bdc3157058b4b22ef06cab4ff7aa18cc3c72d4.g2nIOSLtvs_9MkYlfcZ-AcSBgq3TXJkpVKecTdaZ7Q8+ web-analytics-overview-metric-cards--loading--light:+ hash: v1.k794b7964.045640f10c7f6ce7a63c452bb75b84a76004d580e28d0191a898b9072be415b6.daX9FcHNSvUY7BILs2cBEI-3vMX99abG7zmI23A6n60+ web-analytics-overview-metric-cards--with-warning--dark:+ hash: v1.k794b7964.1be5351363a268e91aff342372429ab8386e170e60ccddba1960c53e3584ab5f.8FVhdsTI15PF7gx1plDfJM38yEdJiJmebZh4FFKHZXk+ web-analytics-overview-metric-cards--with-warning--light:+ hash: v1.k794b7964.513140f3a07e4bce5f44fe469685b1b3d8270eb15bc29e5007d49b9e9c06778f.ixsQR_vjrm4XqsSY5V0WPPZYMsIl4KgtDJAGoICmsCU+ web-analytics-overview-metric-cards--without-comparison--dark:+ hash: v1.k794b7964.8825120f2b27646cf45cc0d8d0542c5ee1e3507e0655206e73545189bd1f1dbb.cVd8lH8I8g1jIhadVw5d8usNH1QRh6yv2CIVuOguaBU+ web-analytics-overview-metric-cards--without-comparison--light:+ hash: v1.k794b7964.3dd39840375b4273c7da065e98ac10275ab343d5984f83ae5f4592c2f40f938a.7gkGGhVI0N8ieih821st4MUfXsiQWjGKu0HyQQzOJ2Aweb-analytics-tile-skeletons--chart--dark:hash: v1.k794b7964.7aa1344291af29b3bea21b1b4fc2962bf865899c63cb8137383d5d6e941a96bf.AElvCuEYtP-fom9VLZcolkkA-soqOxUPJLSlN1SB4NEweb-analytics-tile-skeletons--chart--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 43bd2e32df9f..f7f8c6b02073 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -508,6 +508,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_LIVE_MAP: 'web-analytics-live-map', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_LIVE_PERSON_DRILLDOWN: 'web-analytics-live-person-drilldown', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_MARKETING: 'marketing-analytics', // owner: @jabahamondes #team-web-analytics+ WEB_ANALYTICS_METRIC_CARDS: 'web-analytics-metric-cards', // owner: #team-web-analyticsWEB_ANALYTICS_OPEN_URL: 'web-analytics-open-url', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_PRECOMPUTE_TOGGLE: 'web-analytics-precompute-toggle', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_REGIONS_MAP: 'web-analytics-regions-map', // owner: @jordanm-posthog #team-web-analyticsdiff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsxindex 4246a74e7920..52ee60af1f56 100644--- a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx@@ -16,6 +16,8 @@ import { teamLogic } from 'scenes/teamLogic'import { EvenlyDistributedRows } from '~/queries/nodes/WebOverview/EvenlyDistributedRows'import { WebAnalyticsItemKind } from '~/queries/schema/schema-general'+export const NO_BASELINE_CHANGE_SENTINEL = 999999+const OVERVIEW_ITEM_CELL_MIN_WIDTH_REMS_COMPACT = 6const OVERVIEW_ITEM_CELL_MIN_WIDTH_REMS_DEFAULT = 10@@ -96,17 +98,24 @@ export function OverviewGrid({/>))}</EvenlyDistributedRows>- {samplingRate && !(samplingRate.numerator === 1 && (samplingRate.denominator ?? 1) === 1) ? (- <LemonBanner type="info" className="my-4">- These results are using a sampling factor of {samplingRate.numerator}- <span>{(samplingRate.denominator ?? 1 !== 1) ? `/${samplingRate.denominator}` : ''}</span>. Sampling- is currently in beta.- </LemonBanner>- ) : null}+ <SamplingNotice samplingRate={samplingRate} /></>)}+export function SamplingNotice({ samplingRate }: { samplingRate?: SamplingRate }): JSX.Element | null {+ if (!samplingRate || (samplingRate.numerator === 1 && (samplingRate.denominator ?? 1) === 1)) {+ return null+ }+ return (+ <LemonBanner type="info" className="my-4">+ These results are using a sampling factor of {samplingRate.numerator}+ <span>{(samplingRate.denominator ?? 1) !== 1 ? `/${samplingRate.denominator}` : ''}</span>. Sampling is+ currently in beta.+ </LemonBanner>+ )+}+const OverviewItemCellSkeleton = ({ compact }: { compact: boolean }): JSX.Element => {const cellClasses = compact ? OVERVIEW_ITEM_CELL_CLASSES_COMPACT : OVERVIEW_ITEM_CELL_CLASSES_DEFAULTreturn (@@ -152,7 +161,7 @@ const OverviewItemCell = ({const label = labelFromKey(item.key)const trend =- isNotNil(item.changeFromPreviousPct) && Math.abs(item.changeFromPreviousPct) < 999999+ isNotNil(item.changeFromPreviousPct) && Math.abs(item.changeFromPreviousPct) < NO_BASELINE_CHANGE_SENTINEL? item.changeFromPreviousPct === 0? { Icon: IconTrendingFlat, color: getColorVar('muted') }: item.changeFromPreviousPct > 0@@ -171,7 +180,7 @@ const OverviewItemCell = ({isNotNil(item.value) &&isNotNil(item.previous) &&isNotNil(item.changeFromPreviousPct) &&- Math.abs(item.changeFromPreviousPct) < 999999+ Math.abs(item.changeFromPreviousPct) < NO_BASELINE_CHANGE_SENTINEL? item.value === 0 && item.previous === 0? `${label}: No change (0 in both periods)`: Math.abs(item.changeFromPreviousPct) < 1@@ -184,7 +193,9 @@ const OverviewItemCell = ({item.kind,{ precise: true, currency: baseCurrency })}`- : isNotNil(item.value) && isNotNil(item.previous) && Math.abs(item.changeFromPreviousPct || 0) >= 999999+ : isNotNil(item.value) &&+ isNotNil(item.previous) &&+ Math.abs(item.changeFromPreviousPct || 0) >= NO_BASELINE_CHANGE_SENTINEL? `${label}: ${formatItem(item.value, item.kind, { precise: true, currency: baseCurrency })} (was 0 in previous period)`: isNotNil(item.value)? `${label}: ${formatItem(item.value, item.kind, { precise: true, currency: baseCurrency })}`@@ -270,7 +281,8 @@ const OverviewItemCell = ({<trend.Icon color={trend.color} />{formatPercentage(item.changeFromPreviousPct)}</div>- ) : isNotNil(item.changeFromPreviousPct) && Math.abs(item.changeFromPreviousPct) >= 999999 ? (+ ) : isNotNil(item.changeFromPreviousPct) &&+ Math.abs(item.changeFromPreviousPct) >= NO_BASELINE_CHANGE_SENTINEL ? (<div className="text-muted">-</div>) : item.caption ? (<div@@ -295,7 +307,7 @@ const formatUnit = (x: number, options?: { precise?: boolean }): string => {return humanFriendlyLargeNumber(x)}-const formatItem = (+export const formatItem = (value: number | string | undefined,kind: WebAnalyticsItemKind,options?: { precise?: boolean; currency?: string }diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.stories.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.stories.tsxnew file mode 100644index 000000000000..7b470dc08044--- /dev/null+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.stories.tsx@@ -0,0 +1,75 @@+import { Meta, StoryObj } from '@storybook/react'++import { labelFromKey } from '~/queries/nodes/WebOverview/WebOverview'++import { OverviewMetricCardGrid, OverviewMetricCardItem } from './OverviewMetricCardGrid'++type Story = StoryObj<typeof OverviewMetricCardGrid>++const meta: Meta<typeof OverviewMetricCardGrid> = {+ title: 'Web Analytics/Overview Metric Cards',+ component: OverviewMetricCardGrid,+ parameters: { layout: 'padded' },+ args: {+ loading: false,+ numSkeletons: 5,+ labelFromKey,+ },+}+export default meta++const overviewItems: OverviewMetricCardItem[] = [+ { key: 'visitors', value: 171861, previous: 160000, changeFromPreviousPct: 12, kind: 'unit' },+ { key: 'views', value: 4863551, previous: 4700000, changeFromPreviousPct: 16, kind: 'unit' },+ { key: 'sessions', value: 547323, previous: 552000, changeFromPreviousPct: -1, kind: 'unit' },+ { key: 'session duration', value: 724.92, previous: 724, changeFromPreviousPct: 0, kind: 'duration_s' },+ {+ key: 'bounce rate',+ value: 9.92,+ previous: 10,+ changeFromPreviousPct: -1,+ kind: 'percentage',+ isIncreaseBad: true,+ },+]++const conversionGoalItems: OverviewMetricCardItem[] = [+ { key: 'visitors', value: 171861, previous: 160000, changeFromPreviousPct: 12, kind: 'unit' },+ { key: 'total conversions', value: 24310, previous: 21000, changeFromPreviousPct: 16, kind: 'unit' },+ { key: 'unique conversions', value: 18402, previous: 17900, changeFromPreviousPct: 3, kind: 'unit' },+ { key: 'conversion rate', value: 10.71, previous: 11.2, changeFromPreviousPct: -4, kind: 'percentage' },+]++export const Default: Story = {+ args: { items: overviewItems },+}++export const Loading: Story = {+ args: { items: [], loading: true },+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}++export const ConversionGoal: Story = {+ args: { items: conversionGoalItems, numSkeletons: 4 },+}++export const WithoutComparison: Story = {+ args: {+ items: overviewItems.map(({ previous, changeFromPreviousPct, ...rest }) => rest),+ },+}++export const WithWarning: Story = {+ args: {+ items: overviewItems.map((item) =>+ item.key === 'visitors'+ ? {+ ...item,+ warning:+ 'Visitors counts may be underreported. Set up a reverse proxy so that events are less likely to be intercepted by tracking blockers.',+ warningLink: 'https://posthog.com/docs/advanced/proxy',+ }+ : item+ ),+ },+}diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsxnew file mode 100644index 000000000000..ce40364af8fc--- /dev/null+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx@@ -0,0 +1,170 @@+import clsx from 'clsx'+import { useValues } from 'kea'+import type React from 'react'++import { IconWarning } from '@posthog/icons'+import { LemonSkeleton, Link } from '@posthog/lemon-ui'+import { MetricCard, type MetricChange } from '@posthog/quill-charts'++import { PreAggregatedBadge } from 'lib/components/PreAggregatedBadge'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { range } from 'lib/utils'+import { teamLogic } from 'scenes/teamLogic'++import { formatItem, NO_BASELINE_CHANGE_SENTINEL, OverviewItem, SamplingNotice, SamplingRate } from './OverviewGrid'++export interface OverviewMetricCardItem extends Omit<OverviewItem, 'value' | 'previous'> {+ value: number | undefined+ previous?: number+}++interface OverviewMetricCardGridProps {+ items: OverviewMetricCardItem[]+ loading: boolean+ numSkeletons: number+ samplingRate?: SamplingRate+ usedPreAggregatedTables?: boolean+ usedLazyPrecompute?: boolean+ labelFromKey: (key: string) => string+}++export function OverviewMetricCardGrid({+ items,+ loading,+ numSkeletons,+ samplingRate,+ usedPreAggregatedTables = false,+ usedLazyPrecompute = false,+ labelFromKey,+}: OverviewMetricCardGridProps): JSX.Element {+ return (+ <>+ <div className="grid gap-2 grid-cols-[repeat(auto-fit,minmax(10rem,1fr))]">+ {loading+ ? range(numSkeletons).map((i) => <MetricCardSkeleton key={i} />)+ : items.map((item) => (+ <MetricCardCell+ key={item.key}+ item={item}+ usedPreAggregatedTables={usedPreAggregatedTables}+ usedLazyPrecompute={usedLazyPrecompute}+ labelFromKey={labelFromKey}+ />+ ))}+ </div>+ <SamplingNotice samplingRate={samplingRate} />+ </>+ )+}++function MetricCardCell({+ item,+ usedPreAggregatedTables,+ usedLazyPrecompute,+ labelFromKey,+}: {+ item: OverviewMetricCardItem+ usedPreAggregatedTables: boolean+ usedLazyPrecompute: boolean+ labelFromKey: (key: string) => string+}): JSX.Element {+ const { baseCurrency } = useValues(teamLogic)++ const format = (n: number): string => formatItem(n, item.kind, { currency: baseCurrency })+ const subtitle = item.previous != null ? `vs. ${format(item.previous)} prior` : item.caption++ const clickable = !!item.onClick+ const handleClick = clickable+ ? (event: React.MouseEvent) => {+ event.stopPropagation()+ item.onClick?.()+ }+ : undefined+ const handleKeyDown = clickable+ ? (event: React.KeyboardEvent) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ item.onClick?.()+ }+ }+ : undefined++ return (+ <div+ className={clsx(+ 'relative flex flex-col rounded border bg-surface-primary p-3 transition-colors',+ item.selected && 'border-accent ring-1 ring-accent',+ clickable && 'cursor-pointer hover:border-accent'+ )}+ onClick={handleClick}+ onKeyDown={handleKeyDown}+ role={clickable ? 'button' : undefined}+ tabIndex={clickable ? 0 : undefined}+ aria-pressed={clickable ? !!item.selected : undefined}+ >+ {usedLazyPrecompute ? (+ <PreAggregatedBadge variant="precomputed" />+ ) : usedPreAggregatedTables ? (+ <PreAggregatedBadge variant="preagg" />+ ) : null}+ <MetricCard+ title={<MetricCardTitle label={labelFromKey(item.key)} item={item} />}+ value={item.value}+ change={metricChange(item)}+ goodDirection={item.isIncreaseBad ? 'down' : 'up'}+ formatValue={format}+ subtitle={subtitle}+ />+ </div>+ )+}++function MetricCardTitle({ label, item }: { label: string; item: OverviewMetricCardItem }): JSX.Element {+ if (!item.warning) {+ return <>{label}</>+ }+ return (+ <span className="inline-flex items-center gap-1">+ {label}+ <Tooltip+ interactive={!!item.warningLink}+ title={+ <div>+ {item.warning}+ {item.warningLink && (+ <>+ {' '}+ <Link to={item.warningLink} className="text-link">+ Learn more+ </Link>+ </>+ )}+ </div>+ }+ >+ <IconWarning className="text-warning h-3.5 w-3.5 cursor-pointer" />+ </Tooltip>+ </span>+ )+}++function metricChange(item: OverviewMetricCardItem): MetricChange | null {+ if (+ item.changeFromPreviousPct == null ||+ item.changeFromPreviousPct === 0 ||+ Math.abs(item.changeFromPreviousPct) >= NO_BASELINE_CHANGE_SENTINEL+ ) {+ return null+ }+ return { value: item.changeFromPreviousPct }+}++function MetricCardSkeleton(): JSX.Element {+ return (+ <div className="flex flex-col gap-2 rounded border bg-surface-primary p-3">+ <LemonSkeleton className="h-3 w-16" />+ <LemonSkeleton className="h-9 w-24" />+ <LemonSkeleton className="h-3 w-20" />+ </div>+ )+}diff --git a/frontend/src/queries/nodes/WebOverview/WebOverview.tsx b/frontend/src/queries/nodes/WebOverview/WebOverview.tsxindex 0e7e5fe20bb7..78170462cd0a 100644--- a/frontend/src/queries/nodes/WebOverview/WebOverview.tsx+++ b/frontend/src/queries/nodes/WebOverview/WebOverview.tsx@@ -7,7 +7,8 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { capitalizeFirstLetter } from 'lib/utils'-import { OverviewGrid, OverviewItem } from '~/queries/nodes/OverviewGrid/OverviewGrid'+import { OverviewGrid } from '~/queries/nodes/OverviewGrid/OverviewGrid'+import { OverviewMetricCardGrid, OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'import { AnyResponseType, WebOverviewQuery, WebOverviewQueryResponse } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'@@ -54,7 +55,7 @@ export function WebOverview(props: {// Convert WebOverviewItem to OverviewItem// Handle both `results` (from direct query response) and `result` (from cached insight)const resultsArray = webOverviewQueryResponse?.results ?? (response as any)?.result- const overviewItems: OverviewItem[] =+ const overviewItems: OverviewMetricCardItem[] =resultsArray?.map((item: any) => ({key: item.key,value: item.value,@@ -68,6 +69,20 @@ export function WebOverview(props: {warningLink: showWarning ? 'https://posthog.com/docs/advanced/proxy' : undefined,})) || []+ if (featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_METRIC_CARDS]) {+ return (+ <OverviewMetricCardGrid+ items={overviewItems}+ loading={responseLoading}+ numSkeletons={numSkeletons}+ samplingRate={samplingRate}+ usedPreAggregatedTables={usedWebAnalyticsPreAggregatedTables}+ usedLazyPrecompute={usedWebAnalyticsLazyPrecompute}+ labelFromKey={labelFromKey}+ />+ )+ }+return (<OverviewGriditems={overviewItems}@@ -81,7 +96,7 @@ export function WebOverview(props: {)}-const labelFromKey = (key: string): string => {+export const labelFromKey = (key: string): string => {switch (key) {case 'visitors':return 'Visitors'diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsxindex d3b69678ddbe..085584db5ea8 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx@@ -84,6 +84,21 @@ export function WebAnalyticsDashboard(): JSX.Element {return <App />}+WebAnalyticsDashboardMetricCards.parameters = {+ ...meta.parameters,+ featureFlags: [...((meta.parameters?.featureFlags as string[]) ?? []), FEATURE_FLAGS.WEB_ANALYTICS_METRIC_CARDS],+}+export function WebAnalyticsDashboardMetricCards(): JSX.Element {+ const { setSourceTab, setDeviceTab } = useActions(webAnalyticsLogic)++ useEffect(() => {+ setSourceTab(SourceTab.REFERRING_DOMAIN)+ setDeviceTab(DeviceTab.BROWSER)+ }, [setDeviceTab, setSourceTab])++ return <App />+}+WebAnalyticsDashboardLoading.parameters = {layout: 'fullscreen',viewMode: 'story',