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(web-analytics): show a tabbed report for each page (#123509)

Jordan Mryyanf5143b042b97
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ffca986a89ef..c573c2a85bc0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15962,6 +15962,10 @@ snapshots:
hash: v1.k794b7964.0673d34d6bf0b4fd471c62fbcece324dd1fbb6180a6a37e7ffffee639f57e209.oEb2yD3dty7AG4d_62ypUf61Dhc28FYVFs9oMzUyRlw
scenes-app-web-analytics-livemetricscharts--users-per-minute-empty--light:
hash: v1.k794b7964.08f6363b9b1efb601ef2b7fb5e28f46c8c6726f861d927c6e994213085e666d3.BdfZOIp9Rfr_MYCMTsHW6qmhKUH_Z4u1S2beLgY0eqs
+ scenes-app-web-analytics-page-reports-page-health-card--statuses--dark:
+ hash: v1.k794b7964.20b213a26f1fccece45da99285654f977234b3897340f5218b9034c9d7f44ba0.pjvdtkXf_E6pAEMOFtadD_xgy__zYnRCS8idyWy5sLA
+ scenes-app-web-analytics-page-reports-page-health-card--statuses--light:
+ hash: v1.k794b7964.eec445093be15103165264d561f8a7cb14f9cacda7ad423cc444b949abaa1e89.FEOxmxet-N1p8rUsTt1-ba2sqNSYmiYEH167zEOFkpY
scenes-app-web-analytics-pageperformancemetriccard--decrease--dark:
hash: v1.k794b7964.3f63a6ca6c96ecfa8d06124b4e18d56a38607bf556f3b1047b2b53e0ce65a11a.LCU961p9dYD1lX1bB0gN9D0HEmO_UHdHkRE9dduvuas
scenes-app-web-analytics-pageperformancemetriccard--decrease--light:
diff --git a/frontend/src/scenes/web-analytics/CrossSellButtons/ReplayButton.tsx b/frontend/src/scenes/web-analytics/CrossSellButtons/ReplayButton.tsx
index 83ea3da1e619..b69eab9ee555 100644
--- a/frontend/src/scenes/web-analytics/CrossSellButtons/ReplayButton.tsx
+++ b/frontend/src/scenes/web-analytics/CrossSellButtons/ReplayButton.tsx
@@ -148,6 +148,7 @@ export const ReplayButton = ({
<div onClick={handleClick}>
<ViewRecordingsPlaylistButton
filters={filters}
+ label={<span className="@max-[28rem]/page-report-tile:hidden">View recordings</span>}
type="tertiary"
size="xsmall"
tooltip="View session recordings for this segment"
diff --git a/frontend/src/scenes/web-analytics/PageReports.tsx b/frontend/src/scenes/web-analytics/PageReports.tsx
index f1872b5f0e36..cdaeaddc91f8 100644
--- a/frontend/src/scenes/web-analytics/PageReports.tsx
+++ b/frontend/src/scenes/web-analytics/PageReports.tsx
@@ -9,6 +9,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { PageReportDetail } from 'products/web_analytics/frontend/pageReports/PageReportDetail'
import { PageReportsDirectory } from 'products/web_analytics/frontend/pageReports/PageReportsDirectory'
import { pageReportsTeaserLogic } from 'products/web_analytics/frontend/pageReports/pageReportsTeaserLogic'
@@ -73,7 +74,7 @@ export function PageReportsFilters({ tabs }: { tabs: JSX.Element }): JSX.Element
dateOptions={webAnalyticsDateMapping}
/>
<WebAnalyticsCompareFilter />
- {isDirectoryEnabled && !pageUrl ? (
+ {isDirectoryEnabled ? (
<div className="flex-1" />
) : (
<LemonInputSelect
@@ -112,13 +113,7 @@ export function PageReports(): JSX.Element {
})
if (isDirectoryEnabled) {
- return pageUrl ? (
- <div className="space-y-2 mt-2 h-full min-h-0">
- <Tiles tiles={tiles} compact={true} />
- </div>
- ) : (
- <PageReportsDirectory />
- )
+ return pageUrl ? <PageReportDetail pageUrl={pageUrl} /> : <PageReportsDirectory />
}
if (!hasPageUrl) {
diff --git a/frontend/src/scenes/web-analytics/pageReportsLogic.test.ts b/frontend/src/scenes/web-analytics/pageReportsLogic.test.ts
index 5a71a942d5f9..236747b6399f 100644
--- a/frontend/src/scenes/web-analytics/pageReportsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/pageReportsLogic.test.ts
@@ -52,8 +52,31 @@ describe('createPageReportsFilters', () => {
expectedHostValues: [],
expectKeys: ['$current_url'],
},
- ])('$name', ({ url, selectedHost, expectedHostValues, expectKeys }) => {
- const filters = createPageReportsFilters(url, true, selectedHost)
+ {
+ name: 'hostless path matches every host when the directory is off',
+ url: '/pricing',
+ selectedHost: null,
+ expectedHostValues: [],
+ expectKeys: ['$pathname'],
+ },
+ {
+ name: 'hostless path matches only events without a host when the directory is on',
+ url: '/pricing',
+ selectedHost: null,
+ hostlessMeansNoHost: true,
+ expectedHostValues: [undefined],
+ expectKeys: ['$host', '$pathname'],
+ },
+ {
+ name: 'selected host wins over the hostless match',
+ url: '/pricing',
+ selectedHost: 'posthog.com',
+ hostlessMeansNoHost: true,
+ expectedHostValues: ['posthog.com'],
+ expectKeys: ['$host', '$pathname'],
+ },
+ ])('$name', ({ url, selectedHost, hostlessMeansNoHost, expectedHostValues, expectKeys }) => {
+ const filters = createPageReportsFilters(url, true, selectedHost, false, hostlessMeansNoHost)
expect(hostFilters(filters).map((filter) => filter.value)).toEqual(expectedHostValues)
expect(filters.map((filter) => filter.key).sort()).toEqual([...expectKeys].sort())
diff --git a/frontend/src/scenes/web-analytics/pageReportsLogic.ts b/frontend/src/scenes/web-analytics/pageReportsLogic.ts
index fbf5a7fd4f9b..553bb9068be3 100644
--- a/frontend/src/scenes/web-analytics/pageReportsLogic.ts
+++ b/frontend/src/scenes/web-analytics/pageReportsLogic.ts
@@ -335,6 +335,12 @@ export function buildPageUrlOptions(
return [...representativeByCleaned.entries()].map(([label, key]) => ({ key, label }))
}
+const NO_HOST_FILTER: WebAnalyticsPropertyFilters[number] = {
+ type: PropertyFilterType.Event,
+ key: '$host',
+ operator: PropertyOperator.IsNotSet,
+}
+
function createHostFilter(host: string | null): WebAnalyticsPropertyFilters {
return host ? [{ type: PropertyFilterType.Event, key: '$host', operator: PropertyOperator.Exact, value: host }] : []
}
@@ -349,14 +355,17 @@ export function createPageReportsFilters(
url: string,
stripQueryParams: boolean,
selectedHost: string | null,
- isPathCleaningEnabled: boolean = false
+ isPathCleaningEnabled: boolean = false,
+ hostlessMeansNoHost: boolean = false
): WebAnalyticsPropertyFilters {
const filters = createUrlPropertyFilter(url, stripQueryParams)
// Drop the URL's own host so the explicitly selected host wins, then apply it.
const withSelectedHost = selectedHost
? [...filters.filter((filter) => filter.key !== '$host'), ...createHostFilter(selectedHost)]
- : filters
+ : hostlessMeansNoHost && String(url ?? '').startsWith('/')
+ ? [...filters, NO_HOST_FILTER]
+ : filters
return applyPathCleaningToFilters(withSelectedHost, isPathCleaningEnabled)
}
@@ -610,7 +619,8 @@ export interface pageReportsLogicMeta {
shouldFilterTestAccounts: boolean,
compareFilter: CompareFilter,
isPathCleaningEnabled: boolean,
- selectedHost: string | null
+ selectedHost: string | null,
+ isDirectoryEnabled: boolean
) =>
| {
avgTimeOnPageTrendQuery: InsightVizNode<TrendsQuery> | undefined
@@ -682,7 +692,8 @@ export interface pageReportsLogicMeta {
stripQueryParams: boolean,
shouldFilterTestAccounts: boolean,
selectedHost: string | null,
- isPathCleaningEnabled: boolean
+ isPathCleaningEnabled: boolean,
+ isDirectoryEnabled: boolean
) => (dateFilter: DateFilterState) => InsightVizNode<TrendsQuery>
tiles: (
queries:
@@ -967,6 +978,7 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
s.compareFilter,
s.isPathCleaningEnabled,
s.selectedHost,
+ s.isDirectoryEnabled,
],
(
webAnalyticsTiles: WebAnalyticsTile[],
@@ -976,7 +988,8 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
shouldFilterTestAccounts: boolean,
compareFilter: CompareFilter,
isPathCleaningEnabled: boolean,
- selectedHost: string | null
+ selectedHost: string | null,
+ isDirectoryEnabled: boolean
) => {
// If we don't have a pageUrl, return empty queries to rendering problems
if (!pageUrl) {
@@ -1008,7 +1021,8 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
pageUrl,
stripQueryParams,
selectedHost,
- isPathCleaningEnabled
+ isPathCleaningEnabled,
+ isDirectoryEnabled
)
const dateRange = { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo }
@@ -1143,13 +1157,21 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
}),
],
combinedMetricsQuery: [
- (s) => [s.pageUrl, s.stripQueryParams, s.shouldFilterTestAccounts, s.selectedHost, s.isPathCleaningEnabled],
+ (s) => [
+ s.pageUrl,
+ s.stripQueryParams,
+ s.shouldFilterTestAccounts,
+ s.selectedHost,
+ s.isPathCleaningEnabled,
+ s.isDirectoryEnabled,
+ ],
(
pageUrl: string | null,
stripQueryParams: boolean,
shouldFilterTestAccounts: boolean,
selectedHost: string | null,
- isPathCleaningEnabled: boolean
+ isPathCleaningEnabled: boolean,
+ isDirectoryEnabled: boolean
) =>
(dateFilter: typeof webAnalyticsLogic.values.dateFilter): InsightVizNode<TrendsQuery> => ({
kind: NodeKind.InsightVizNode,
@@ -1186,7 +1208,13 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
},
filterTestAccounts: shouldFilterTestAccounts,
properties: pageUrl
- ? createPageReportsFilters(pageUrl, stripQueryParams, selectedHost, isPathCleaningEnabled)
+ ? createPageReportsFilters(
+ pageUrl,
+ stripQueryParams,
+ selectedHost,
+ isPathCleaningEnabled,
+ isDirectoryEnabled
+ )
: [],
tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
},
@@ -1470,9 +1498,6 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
listeners: ({ actions, values }) => ({
openPageReport: ({ source, position }) => {
posthog.capture('web analytics page report opened', { source, row_position: position })
- if (values.isInitialLoad) {
- actions.loadPages('')
- }
},
backToDirectory: () => {
posthog.capture('web analytics page report back to directory', { method: 'breadcrumb' })
@@ -1487,16 +1512,11 @@ export const pageReportsLogic = kea<pageReportsLogicType>({
actions.loadPages(searchTerm)
},
loadPages: ({ searchTerm }) => {
- if (values.isDirectoryEnabled && !values.pageUrl) {
+ if (values.isDirectoryEnabled) {
return
}
actions.loadPagesUrls({ searchTerm })
},
- setPageUrl: () => {
- if (values.isDirectoryEnabled && values.pageUrl && values.isInitialLoad) {
- actions.loadPages('')
- }
- },
setDates: () => {
if (values.featureFlags[FEATURE_FLAGS.PAGE_REPORTS_RANKED_URL_SEARCH]) {
actions.loadPages(values.pageUrlSearchTerm)
diff --git a/products/web_analytics/frontend/pageReports/PageHealthCard.stories.tsx b/products/web_analytics/frontend/pageReports/PageHealthCard.stories.tsx
new file mode 100644
index 000000000000..73d4d3132867
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageHealthCard.stories.tsx
@@ -0,0 +1,94 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { PageHealthSummary } from './pageHealth'
+import { PageHealthCard } from './PageHealthCard'
+
+const CARDS: PageHealthSummary[] = [
+ {
+ key: 'search',
+ title: 'Search visibility',
+ status: 'strong',
+ value: '35%',
+ detail: 'from Google, site average 30%',
+ headline: '35% of visitors come from Google search, against 30% site-wide.',
+ reasons: [
+ '35% of visitors come from Google search, against 30% site-wide.',
+ 'The average Google position is 3.1.',
+ ],
+ },
+ {
+ key: 'ai',
+ title: 'AI visibility',
+ status: 'needs_attention',
+ value: '0%',
+ detail: 'from AI assistants, site average 11%',
+ headline: 'Read by 23 AI crawlers but no AI assistant sent visitors.',
+ reasons: ['Read by 23 AI crawlers but no AI assistant sent visitors.'],
+ },
+ {
+ key: 'engagement',
+ title: 'Engagement',
+ status: 'fair',
+ value: '24s',
+ detail: 'for 90% of visits · 41% bounce',
+ headline: '90% of visitors spend up to 24s on this page.',
+ reasons: ['90% of visitors spend up to 24s on this page.'],
+ },
+ {
+ key: 'search',
+ title: 'Search visibility',
+ status: 'not_found',
+ value: '0%',
+ detail: 'from Google, site average 31%',
+ headline: 'No visitors from Google search',
+ reasons: ["None of this page's 420 visitors arrived from Google search."],
+ },
+ {
+ key: 'ai',
+ title: 'AI visibility',
+ status: 'not_set_up',
+ value: null,
+ detail: null,
+ headline: 'AI crawlers are not measured yet',
+ reasons: ['Forward your server logs to see which AI crawlers read this page.'],
+ },
+ {
+ key: 'engagement',
+ title: 'Engagement',
+ status: 'no_data',
+ value: null,
+ detail: null,
+ headline: 'Not enough visitors yet',
+ reasons: ['This page had 12 visitors in this period. Health needs at least 30.'],
+ },
+ {
+ key: 'search',
+ title: 'Search visibility',
+ status: 'loading',
+ headline: 'Checking this page',
+ reasons: [],
+ value: null,
+ detail: null,
+ },
+]
+
+function AllStatuses(): JSX.Element {
+ return (
+ <div className="grid grid-cols-3 max-w-4xl border rounded-lg bg-surface-primary overflow-hidden divide-x divide-y">
+ {CARDS.map((card) => (
+ <PageHealthCard key={`${card.key}-${card.status}`} card={card} onClick={() => {}} onHover={() => {}} />
+ ))}
+ </div>
+ )
+}
+
+const meta: Meta<typeof AllStatuses> = {
+ title: 'Scenes-App/Web Analytics/Page reports/Page health card',
+ component: AllStatuses,
+ parameters: {
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export default meta
+
+export const Statuses: StoryObj<typeof AllStatuses> = {}
diff --git a/products/web_analytics/frontend/pageReports/PageHealthCards.tsx b/products/web_analytics/frontend/pageReports/PageHealthCards.tsx
new file mode 100644
index 000000000000..102ef8863133
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageHealthCards.tsx
@@ -0,0 +1,50 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { PageReportTab } from 'scenes/web-analytics/pageReportsLogic'
+
+import { PageHealthCard } from './PageHealthCard'
+import { pageReportDetailLogic } from './pageReportDetailLogic'
+import { PageVisitorsCard } from './PageVisitorsCard'
+
+export function PageHealthCards(): JSX.Element {
+ const { healthCards, healthFailed, pageMetrics, searchConsole, siteTotals } = useValues(pageReportDetailLogic)
+ const { hoverHealthCard, clickHealthCard, setPageReportTab, reloadHealth } = useActions(pageReportDetailLogic)
+
+ if (healthFailed) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: reloadHealth }}>
+ Couldn't load the health summary for this page.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <>
+ <div
+ className="grid grid-cols-2 @min-[60rem]/main-content:grid-cols-4 border rounded-lg bg-surface-primary overflow-hidden divide-x divide-y @min-[60rem]/main-content:divide-y-0"
+ data-attr="page-report-health-cards"
+ >
+ <PageVisitorsCard
+ visitors={pageMetrics?.visitors ?? null}
+ siteVisitors={siteTotals?.visitors?.current ?? null}
+ onClick={() => setPageReportTab(PageReportTab.Overview)}
+ />
+ {healthCards.map((card) => (
+ <PageHealthCard
+ key={card.key}
+ card={card}
+ onClick={() => clickHealthCard(card)}
+ onHover={() => hoverHealthCard(card)}
+ />
+ ))}
+ </div>
+ {searchConsole === 'error' && (
+ <LemonBanner type="warning" action={{ children: 'Try again', onClick: reloadHealth }}>
+ Couldn't load Google Search Console data for this page.
+ </LemonBanner>
+ )}
+ </>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageReportAiTab.tsx b/products/web_analytics/frontend/pageReports/PageReportAiTab.tsx
new file mode 100644
index 000000000000..107dc1184c88
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageReportAiTab.tsx
@@ -0,0 +1,123 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { TileId } from 'scenes/web-analytics/common'
+import { PagePerformanceCard } from 'scenes/web-analytics/PagePerformanceCard'
+import { createPagePerformanceInsightProps } from 'scenes/web-analytics/pagePerformanceLogic'
+
+import { QueryContext } from '~/queries/types'
+
+import { AiAssistantList } from 'products/web_analytics/frontend/searchAndAi/AiAssistantList'
+import { AiTableCard } from 'products/web_analytics/frontend/searchAndAi/AiTableCard'
+import { AiTrendCard } from 'products/web_analytics/frontend/searchAndAi/AiTrendCard'
+import { CRAWLER_COLUMNS } from 'products/web_analytics/frontend/searchAndAi/crawlerColumns'
+import { SearchAndAiLoading } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiLoading'
+import { SearchAndAiQuery } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiQuery'
+import { SearchAndAiSectionHeading } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiSectionHeading'
+
+import { pageReportDetailLogic } from './pageReportDetailLogic'
+
+const SERVER_LOGS_DOCS_URL = 'https://posthog.com/docs/web-analytics/sending-http-logs'
+const PAGE_REPORT_SCOPE = 'page-report'
+
+const crawlersInsightProps = createPagePerformanceInsightProps(TileId.AI_CRAWLERS, PAGE_REPORT_SCOPE)
+const crawlersContext: QueryContext = {
+ columns: CRAWLER_COLUMNS,
+ emptyStateHeading: 'No AI crawlers read this page',
+}
+
+export function PageReportAiTab(): JSX.Element {
+ const {
+ aiAssistants,
+ aiAssistantsLoading,
+ aiCrawlersQuery,
+ aiLandingPagesQuery,
+ aiReferralTrendQuery,
+ crawlTrendQuery,
+ crawlersMeasured,
+ failedLoads,
+ healthFailed,
+ } = useValues(pageReportDetailLogic)
+ const { loadAiAssistants } = useActions(pageReportDetailLogic)
+
+ return (
+ <div className="flex flex-col gap-6" data-attr="page-report-ai-tab">
+ <section>
+ <SearchAndAiSectionHeading description="People who landed on this page from an AI assistant such as ChatGPT, Claude, or Perplexity.">
+ Traffic from AI
+ </SearchAndAiSectionHeading>
+ <div className="flex flex-col gap-4">
+ <AiTrendCard
+ title="Referrals over time"
+ query={aiReferralTrendQuery}
+ tileId={TileId.AI_REFERRALS_TREND}
+ uniqueKey="page-report-ai-referrals-trend"
+ scope={PAGE_REPORT_SCOPE}
+ />
+ <div className="grid grid-cols-1 @min-[64rem]/main-content:grid-cols-2 gap-4">
+ <PagePerformanceCard
+ title="By assistant"
+ className="min-w-0"
+ footer="Some assistants strip the referrer, so this is a lower bound."
+ >
+ <AiAssistantList
+ rows={aiAssistants}
+ loading={aiAssistantsLoading}
+ emptyText="No visitors arrived from an AI assistant in this period."
+ failed={failedLoads.aiAssistants}
+ onRetry={() => loadAiAssistants(null)}
+ />
+ </PagePerformanceCard>
+ <AiTableCard
+ title="Where AI visitors started"
+ query={aiLandingPagesQuery}
+ tileId={TileId.AI_LANDING_PAGES}
+ scope={PAGE_REPORT_SCOPE}
+ tableLayout="auto"
+ footer="The first page people opened after arriving from an AI assistant, on visits that went on to reach this page. If it's this page, they came straight here."
+ />
+ </div>
+ </div>
+ </section>
+ <section>
+ <SearchAndAiSectionHeading description="Bots that read this page to train a model or to answer someone's question about it.">
+ AI crawlers
+ </SearchAndAiSectionHeading>
+ {crawlersMeasured === false ? (
+ <LemonBanner type="info">
+ AI crawlers don't run the PostHog snippet, so they only show up when your server logs are
+ forwarded to PostHog.{' '}
+ <Link to={SERVER_LOGS_DOCS_URL} target="_blank">
+ Learn how to forward server logs
+ </Link>
+ </LemonBanner>
+ ) : crawlersMeasured === null && !healthFailed ? (
+ <SearchAndAiLoading loading label="Checking for server logs" className="min-h-64" />
+ ) : (
+ <div className="flex flex-col gap-4">
+ <AiTrendCard
+ title="Crawler activity over time"
+ query={crawlTrendQuery}
+ tileId={TileId.AI_CRAWLERS_TREND}
+ uniqueKey="page-report-ai-crawl-trend"
+ scope={PAGE_REPORT_SCOPE}
+ />
+ <PagePerformanceCard
+ title="By crawler"
+ footer="Crawlers are bots that read the page for AI models. They are not counted as visitors."
+ >
+ <SearchAndAiQuery
+ uniqueKey="page-report-ai-crawlers"
+ query={aiCrawlersQuery}
+ insightProps={crawlersInsightProps}
+ context={crawlersContext}
+ />
+ </PagePerformanceCard>
+ </div>
+ )}
+ </section>
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageReportDetail.tsx b/products/web_analytics/frontend/pageReports/PageReportDetail.tsx
new file mode 100644
index 000000000000..45284f125ccf
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageReportDetail.tsx
@@ -0,0 +1,47 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { LemonTabs } from '@posthog/lemon-ui'
+
+import { PageReportTab, pageReportsLogic } from 'scenes/web-analytics/pageReportsLogic'
+
+import { PageHealthCards } from './PageHealthCards'
+import { PageReportAiTab } from './PageReportAiTab'
+import { pageReportDetailLogic } from './pageReportDetailLogic'
+import { PageReportHeader } from './PageReportHeader'
+import { PageReportSearchTab } from './PageReportSearchTab'
+import { pageKeyForUrl } from './pageReportsUtils'
+import { PageReportTileRows } from './PageReportTileRows'
+
+export function PageReportDetail({ pageUrl }: { pageUrl: string }): JSX.Element {
+ const { pageReportTab, tilesByTab, isPathCleaningEnabled, pathCleaningFilters, selectedHost } =
+ useValues(pageReportsLogic)
+ const { setPageReportTab } = useActions(pageReportsLogic)
+ const pageKey = pageKeyForUrl(pageUrl, isPathCleaningEnabled, pathCleaningFilters, selectedHost)
+
+ const tileTab = (tab: PageReportTab): JSX.Element => <PageReportTileRows rows={tilesByTab[tab] ?? []} />
+
+ return (
+ <BindLogic logic={pageReportDetailLogic} props={{ pageKey, pageUrl }}>
+ <div className="flex flex-col gap-3 mt-2 pb-24" data-attr="page-report-detail">
+ <PageReportHeader pageKey={pageKey} pageUrl={pageUrl} selectedHost={selectedHost} />
+ <PageHealthCards />
+ <LemonTabs
+ activeKey={pageReportTab}
+ onChange={setPageReportTab}
+ data-attr="page-report-tabs"
+ tabs={[
+ { key: PageReportTab.Overview, label: 'Overview', content: tileTab(PageReportTab.Overview) },
+ { key: PageReportTab.Traffic, label: 'Traffic', content: tileTab(PageReportTab.Traffic) },
+ {
+ key: PageReportTab.Search,
+ label: 'Search',
+ content: <PageReportSearchTab />,
+ },
+ { key: PageReportTab.AI, label: 'AI', content: <PageReportAiTab /> },
+ { key: PageReportTab.Audience, label: 'Audience', content: tileTab(PageReportTab.Audience) },
+ ]}
+ />
+ </div>
+ </BindLogic>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageReportHeader.tsx b/products/web_analytics/frontend/pageReports/PageReportHeader.tsx
new file mode 100644
index 000000000000..b6b155e6e276
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageReportHeader.tsx
@@ -0,0 +1,102 @@
+import { useActions } from 'kea'
+
+import { IconChevronRight, IconEllipsis, IconExternal } from '@posthog/icons'
+import { LemonButton, LemonMenu, Link } from '@posthog/lemon-ui'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { tryDecodeURIComponent } from 'lib/utils/url'
+import { urls } from 'scenes/urls'
+import { pageReportsLogic } from 'scenes/web-analytics/pageReportsLogic'
+
+import { pageReportDetailLogic } from './pageReportDetailLogic'
+import { pageUrlForHost, splitPageKey } from './pageReportsUtils'
+
+export interface PageReportHeaderProps {
+ pageKey: string
+ pageUrl: string
+ selectedHost: string | null
+}
+
+export function PageReportHeader({ pageKey, pageUrl, selectedHost }: PageReportHeaderProps): JSX.Element {
+ const { backToDirectory } = useActions(pageReportsLogic)
+ const { clickOpenPage, clickHeaderMenuItem } = useActions(pageReportDetailLogic)
+ const { host, path } = splitPageKey(tryDecodeURIComponent(pageKey))
+ const absoluteUrl = pageUrlForHost(pageUrl, selectedHost)
+ const canOpen = /^https?:\/\//i.test(absoluteUrl)
+
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2" data-attr="page-report-header">
+ <nav aria-label="Breadcrumb" className="flex items-center gap-1 min-w-0 flex-1">
+ <Link
+ to={urls.webAnalyticsPageReports()}
+ subtle
+ className="shrink-0"
+ onClick={(event) => {
+ if (!event.shiftKey) {
+ event.preventDefault()
+ backToDirectory()
+ }
+ }}
+ data-attr="page-report-breadcrumb"
+ >
+ Page reports
+ </Link>
+ {host ? (
+ <>
+ <IconChevronRight className="shrink-0 text-secondary" />
+ <span className="shrink-0 text-secondary">{host}</span>
+ </>
+ ) : null}
+ <IconChevronRight className="shrink-0 text-secondary" />
+ <span className="font-semibold text-primary truncate min-w-0" title={path} aria-current="page">
+ {path}
+ </span>
+ </nav>
+ <div className="flex flex-wrap items-center gap-2">
+ {canOpen ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ to={absoluteUrl}
+ targetBlank
+ sideIcon={<IconExternal />}
+ onClick={clickOpenPage}
+ data-attr="page-report-open-page"
+ >
+ Open page
+ </LemonButton>
+ ) : null}
+ <LemonMenu
+ items={[
+ {
+ label: 'Copy link to this report',
+ onClick: () => {
+ clickHeaderMenuItem('copy_link')
+ void copyToClipboard(window.location.href, 'link to this report')
+ },
+ },
+ ...(canOpen
+ ? [
+ {
+ label: 'View heatmap',
+ to: urls.heatmapNew(
+ `pageURL=${encodeURIComponent(absoluteUrl)}&dataURL=${encodeURIComponent(absoluteUrl)}`
+ ),
+ onClick: () => clickHeaderMenuItem('heatmap'),
+ },
+ ]
+ : []),
+ ]}
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconEllipsis />}
+ aria-label="More actions"
+ data-attr="page-report-more"
+ />
+ </LemonMenu>
+ </div>
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageReportSearchTab.tsx b/products/web_analytics/frontend/pageReports/PageReportSearchTab.tsx
new file mode 100644
index 000000000000..26451c0d555b
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageReportSearchTab.tsx
@@ -0,0 +1,50 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { TileId } from 'scenes/web-analytics/common'
+import { PagePerformanceCard } from 'scenes/web-analytics/PagePerformanceCard'
+import { createPagePerformanceInsightProps } from 'scenes/web-analytics/pagePerformanceLogic'
+
+import { GoogleSearchConsoleKeywords } from 'products/web_analytics/frontend/searchAndAi/GoogleSearchConsoleKeywords'
+import { SearchAndAiQuery } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiQuery'
+
+import { pageReportDetailLogic } from './pageReportDetailLogic'
+
+const keywordsInsightProps = createPagePerformanceInsightProps(TileId.PAGE_PERFORMANCE_TABLE, 'page-report-keywords')
+const googleTrendInsightProps = createPagePerformanceInsightProps(TileId.PAGE_PERFORMANCE_TABLE, 'page-report-google')
+
+export function PageReportSearchTab(): JSX.Element {
+ const { googleTrendQuery, window, isPathCleaningEnabled, currentTeam } = useValues(pageReportDetailLogic)
+ const { props } = useMountedLogic(pageReportDetailLogic)
+ const { clickSearchConsoleConnect } = useActions(pageReportDetailLogic)
+
+ return (
+ <div
+ className="grid grid-cols-1 @min-[64rem]/main-content:grid-cols-2 gap-3"
+ data-attr="page-report-search-tab"
+ >
+ <PagePerformanceCard title="Visitors from Google search">
+ <div className="min-h-72 flex flex-col">
+ <SearchAndAiQuery
+ uniqueKey="page-report-google-trend"
+ query={googleTrendQuery}
+ insightProps={googleTrendInsightProps}
+ />
+ </div>
+ </PagePerformanceCard>
+ <PagePerformanceCard
+ title="Top search queries"
+ footer="Queries this page ranks for in Google, with clicks and average position from Google Search Console."
+ >
+ <GoogleSearchConsoleKeywords
+ page={props.pageKey}
+ window={window}
+ isPathCleaningEnabled={isPathCleaningEnabled}
+ pathCleaningFilters={currentTeam?.path_cleaning_filters}
+ insightProps={keywordsInsightProps}
+ uniqueKey="page-report-gsc-keywords"
+ onConnectClick={clickSearchConsoleConnect}
+ />
+ </PagePerformanceCard>
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/PageReportTileRows.tsx b/products/web_analytics/frontend/pageReports/PageReportTileRows.tsx
new file mode 100644
index 000000000000..01f8cc4cdec2
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/PageReportTileRows.tsx
@@ -0,0 +1,68 @@
+import clsx from 'clsx'
+
+import { PageReportTileRow } from 'scenes/web-analytics/pageReportsLogic'
+import { QueryTileItem } from 'scenes/web-analytics/WebAnalyticsDashboard'
+
+const ROW_CLASS = 'grid grid-cols-1 @min-[44rem]/main-content:grid-cols-2 @min-[64rem]/main-content:grid-cols-6 gap-3'
+
+const TRUNCATED_LABEL_COLUMN = clsx(
+ '[&_tbody_td:first-child]:max-w-0 [&_tbody_td:first-child]:w-full [&_tbody_td:first-child]:truncate',
+ '[&_thead_th:first-child]:max-w-0 [&_thead_th:first-child]:w-full [&_thead_th:first-child]:whitespace-normal [&_thead_th:first-child_*]:whitespace-normal'
+)
+
+const WIDE_SPAN: Record<number, string> = {
+ 2: '@min-[64rem]/main-content:col-span-2',
+ 3: '@min-[64rem]/main-content:col-span-3',
+ 4: '@min-[64rem]/main-content:col-span-4',
+ 6: '@min-[64rem]/main-content:col-span-6',
+}
+
+const FULL_ROW_ON_TWO_COLUMNS = '@min-[44rem]/main-content:col-span-2'
+
+function wideSpan(count: number, index: number): number {
+ if (count === 1) {
+ return 6
+ }
+ if (count === 2 || count === 4) {
+ return 3
+ }
+ if (count === 5) {
+ return index < 3 ? 2 : 3
+ }
+ return 2
+}
+
+function tileSpanClass(row: PageReportTileRow, index: number): string {
+ const count = row.tiles.length
+ if (row.variant === 'feature') {
+ return clsx(FULL_ROW_ON_TWO_COLUMNS, WIDE_SPAN[count === 1 ? 6 : index === 0 ? 4 : 2])
+ }
+ const isLoneTileOnTwoColumns = count % 2 === 1 && index === count - 1
+ return clsx(isLoneTileOnTwoColumns && FULL_ROW_ON_TWO_COLUMNS, WIDE_SPAN[wideSpan(count, index)])
+}
+
+export function PageReportTileRows({ rows }: { rows: PageReportTileRow[] }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-3">
+ {rows.map((row) => (
+ <div
+ key={row.key}
+ className={clsx(ROW_CLASS, TRUNCATED_LABEL_COLUMN)}
+ data-attr={`page-report-row-${row.key}`}
+ >
+ {row.tiles.map((tile, index) => (
+ <div
+ key={tile.tileId}
+ className={clsx(
+ '@container/page-report-tile min-w-0 flex flex-col',
+ tileSpanClass(row, index)
+ )}
+ >
+ <QueryTileItem tile={tile} />
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/pageReports/pageReportDetailLogic.ts b/products/web_analytics/frontend/pageReports/pageReportDetailLogic.ts
index b939cc4c4d51..47f42af5c24c 100644
--- a/products/web_analytics/frontend/pageReports/pageReportDetailLogic.ts
+++ b/products/web_analytics/frontend/pageReports/pageReportDetailLogic.ts
@@ -669,7 +669,7 @@ export const pageReportDetailLogic: LogicWrapper<pageReportDetailLogicType> = ke
filterTestAccounts,
properties: [
...webAnalyticsFilters,
- ...createPageReportsFilters(pageUrl, true, selectedHost, isPathCleaningEnabled),
+ ...createPageReportsFilters(pageUrl, true, selectedHost, isPathCleaningEnabled, true),
],
}),
],
diff --git a/products/web_analytics/frontend/pageReports/pageReportsUtils.test.ts b/products/web_analytics/frontend/pageReports/pageReportsUtils.test.ts
new file mode 100644
index 000000000000..199f3a4d5823
--- /dev/null
+++ b/products/web_analytics/frontend/pageReports/pageReportsUtils.test.ts
@@ -0,0 +1,35 @@
+import { pageKeyForUrl, pageUrlForHost } from './pageReportsUtils'
+
+describe('pageReportsUtils', () => {
+ test.each<[string, string, string | null, string]>([
+ ['keeps the URL host', 'https://example.com/pricing?ref=nav', null, 'example.com/pricing'],
+ [
+ 'uses the selected host over the URL host',
+ 'https://example.com/pricing',
+ 'docs.example.com',
+ 'docs.example.com/pricing',
+ ],
+ ['keeps a hostless path hostless', '/pricing', null, '/pricing'],
+ ['scopes a hostless path to the selected host', '/pricing', 'example.com', 'example.com/pricing'],
+ ])('pageKeyForUrl: %s', (_name, url, selectedHost, expected) => {
+ expect(pageKeyForUrl(url, false, [], selectedHost)).toEqual(expected)
+ })
+
+ test.each<[string, string, string | null, string]>([
+ [
+ 'keeps the URL without a selected host',
+ 'https://example.com/pricing?ref=nav',
+ null,
+ 'https://example.com/pricing?ref=nav',
+ ],
+ [
+ 'swaps in the selected host',
+ 'https://example.com/pricing?ref=nav',
+ 'docs.example.com',
+ 'https://docs.example.com/pricing?ref=nav',
+ ],
+ ['adds the selected host to a hostless path', '/pricing', 'example.com', 'https://example.com/pricing'],
+ ])('pageUrlForHost: %s', (_name, url, selectedHost, expected) => {
+ expect(pageUrlForHost(url, selectedHost)).toEqual(expected)
+ })
+})
diff --git a/products/web_analytics/frontend/pageReports/pageReportsUtils.ts b/products/web_analytics/frontend/pageReports/pageReportsUtils.ts
index aef2e2e9ae27..63292c0a8310 100644
--- a/products/web_analytics/frontend/pageReports/pageReportsUtils.ts
+++ b/products/web_analytics/frontend/pageReports/pageReportsUtils.ts
@@ -68,6 +68,14 @@ export const valueChange = (value: WebPageDirectoryValue | null | undefined): nu
export const pageReportUrlForPage = (page: string): string =>
page.startsWith('/') || /^[a-z]+:\/\//i.test(page) ? page : `https://${page}`
+export const pageUrlForHost = (page: string, host: string | null): string => {
+ const url = pageReportUrlForPage(page)
+ if (!host) {
+ return url
+ }
+ return url.startsWith('/') ? `https://${host}${url}` : url.replace(/^([a-z]+:\/\/)[^/?#]*/i, `$1${host}`)
+}
+
export const pageReportPath = (page: string, searchParams: Record<string, any> = {}): string =>
combineUrl(urls.webAnalyticsPageReports(), { ...searchParams, pageURL: pageReportUrlForPage(page) }).url
@@ -82,18 +90,19 @@ export const looksLikePageUrl = (search: string): boolean => {
export const pageKeyForUrl = (
url: string,
isPathCleaningEnabled: boolean,
- pathCleaningFilters: PathCleaningFilter[]
+ pathCleaningFilters: PathCleaningFilter[],
+ selectedHost: string | null
): string => {
const cleanPath = (pathname: string): string =>
isPathCleaningEnabled ? applyPathCleaning(pathname, pathCleaningFilters) : pathname
if (url.startsWith('/')) {
- return cleanPath(url.split(/[?#]/)[0])
+ return `${selectedHost ?? ''}${cleanPath(url.split(/[?#]/)[0])}`
}
const parsed = parseWebAnalyticsURL(pageReportUrlForPage(url))
if (!parsed.isValid || !parsed.pathname) {
return url
}
- return `${parsed.host ?? ''}${cleanPath(parsed.pathname.replace(/%3C([^/%]*)%3E/gi, '<$1>'))}`
+ return `${selectedHost ?? parsed.host ?? ''}${cleanPath(parsed.pathname.replace(/%3C([^/%]*)%3E/gi, '<$1>'))}`
}
export const splitPageKey = (page: string): { host: string | null; path: string } => {