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): redesign page performance as search & AI (#83372)

Jordan Mryyanb9f73094c3ba
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 62a4eeb1331c..f3c1bed8b2b0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7908,6 +7908,30 @@ snapshots:
hash: v1.k794b7964.4985b07e9f0062954fa68380bc57ba975141f437e96ac938c8025540aae5d92b.Pae87mHyCuaDYoeU92NuOV9zJx0hqar1R0vunkOZUN0
scenes-app-web-analytics-achievements--weekly-only-arm--light:
hash: v1.k794b7964.eb042d165752cd9ff0145ee3b49f0769671244ca00e931c8ece93ec0d01a9a6f.YlQzVwE6qBKZs4cKyA1-lYowaxlhGEGt_K4jt076OSE
+ scenes-app-web-analytics-pageperformancemetriccard--decrease--dark:
+ hash: v1.k794b7964.3f63a6ca6c96ecfa8d06124b4e18d56a38607bf556f3b1047b2b53e0ce65a11a.LCU961p9dYD1lX1bB0gN9D0HEmO_UHdHkRE9dduvuas
+ scenes-app-web-analytics-pageperformancemetriccard--decrease--light:
+ hash: v1.k794b7964.f4c9b3fc7e004b38bc4a27bee305f77d8fee7b48f86c8517d12feafbbb85a94a.T9xTjpSSCZqPc3TmridipGTYruInUVDD4MJVCHfIn7w
+ scenes-app-web-analytics-pageperformancemetriccard--increase--dark:
+ hash: v1.k794b7964.8f1d1ce3291b2c7aed9272d18d52b109fb54291b5c98694ab315c05694fffff0.WTOte2A60XnOMd4NvMejHxOe-cEfR_ZRjIqTfRjtwpQ
+ scenes-app-web-analytics-pageperformancemetriccard--increase--light:
+ hash: v1.k794b7964.af930a0e4b0748e27a6b496bbc1d25f1a2881759a24b043a33b1f7014d845d5b.YgOAHmji50DhA820iu-nhcIC6hB0D3ueTXNIHDrgA_8
+ scenes-app-web-analytics-pageperformancemetriccard--loading--dark:
+ hash: v1.k794b7964.812b7f0a1b89e89a31e3b8d37ed2f8e65949536abff5174d2086a2b4c2575907.-HTeYjiy0pGdyZjnxQqUCBgfZcZHlyIMsZMC5nzKJ4k
+ scenes-app-web-analytics-pageperformancemetriccard--loading--light:
+ hash: v1.k794b7964.f443ef8e5973b74cf0be0f1ef3a918e06b6dcb725a7049ee3cc779fb7117345c.5hMKj4vx2ZkD5TueIzw5BXRuLxwD3LWJp8mN8Nj60Tw
+ scenes-app-web-analytics-pageperformancemetriccard--without-comparison--dark:
+ hash: v1.k794b7964.1cadb5aad49d7549f85057b62cf40bc180f60b4d53c26436f982f090df13a850.F1fJFyWYUTgxvG5m84r-VX1zEFiYRI-wTA7wuqmO-i4
+ scenes-app-web-analytics-pageperformancemetriccard--without-comparison--light:
+ hash: v1.k794b7964.9a094c9dde8671b80c387303f82fc6515c46f783e03dc593314f1ecdd94a829b.hQ3HPNQWJPhjmKZ29zO1SkWVxjJpkwtl84sezv_3OHU
+ scenes-app-web-analytics-pageperformancemetriccard--without-sparkline--dark:
+ hash: v1.k794b7964.08b7a631d1c2c0e8aba495b507d69db07be0bc23cc4e59b089953d71c3be8117.hk8hnqmt3mR8GvpyghZJ3IZ1CrSL-gChlxdF4yCS7yE
+ scenes-app-web-analytics-pageperformancemetriccard--without-sparkline--light:
+ hash: v1.k794b7964.27bbdd01e4451fe0fe7cfbf693975714907972cdef4cc9b74ab13f99c28f5c34.9VZtUj_jx6H9AXXqTTKz1uomaF3X9e8cENkeIs8iJ_I
+ scenes-app-web-analytics-search-ai--web-analytics-page-performance--dark:
+ hash: v1.k794b7964.59a8f6024a2ea5bf33a41c4c3f1de33162797cac03eeb2a6e75196686126fdcd.IEU7UFRnMeS-XS_Eibt7SRW7QxH6_R4l4Ut1Kuepjm0
+ scenes-app-web-analytics-search-ai--web-analytics-page-performance--light:
+ hash: v1.k794b7964.a6ba7deb703189986a29cd9fb512528232cc1fb8a602716b072fdff8a378695d.dt9pqc4bKRhF4MB52Ph_323zhIke8DbgpLAasOFzFHc
scenes-inbox-scout-tags--editor-and-filter--dark:
hash: v1.k794b7964.a6c6018c279d1c7b6dc6cfe7ade21997d71bc5a3f970a76ca68f4bd374b1def6.wiY4XKEvSpFFtmciViAMFvc_yZLC5SeA5L6TmAYaNqQ
scenes-inbox-scout-tags--editor-and-filter--light:
diff --git a/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx b/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx
new file mode 100644
index 000000000000..ea9e2f981baf
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx
@@ -0,0 +1,172 @@
+import { Meta } from '@storybook/react'
+import { useActions } from 'kea'
+import { useEffect } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { webAnalyticsLogic } from './webAnalyticsLogic'
+
+const BUCKETS = ['2023-01-26', '2023-01-27', '2023-01-28', '2023-01-29', '2023-01-30', '2023-01-31', '2023-02-01']
+
+const OVERVIEW_HUMAN = {
+ columns: ['bucket', 'visitors', 'visitors_previous', 'google', 'google_previous', 'llm', 'llm_previous', 'pages'],
+ results: [
+ ['1970-01-01 00:00:00', 1430, 1210, 384, 361, 812, 260, 128],
+ ...[170, 190, 165, 235, 210, 245, 215].map((visitors, index) => [
+ `${BUCKETS[index]} 00:00:00`,
+ visitors,
+ 0,
+ Math.round(visitors * 0.42),
+ 0,
+ Math.round(visitors * 0.03),
+ 0,
+ 0,
+ ]),
+ ],
+}
+
+const OVERVIEW_CRAWLER = {
+ columns: ['bucket', 'crawls', 'crawls_previous'],
+ results: [
+ ['1970-01-01 00:00:00', 88100, 78600],
+ ...[9800, 11200, 10400, 14100, 13600, 15200, 13800].map((crawls, index) => [
+ `${BUCKETS[index]} 00:00:00`,
+ crawls,
+ 0,
+ ]),
+ ],
+}
+
+// Every metric tuple is [current, previous], except agent crawls, which is [crawls, distinct agents].
+const PAGE_ROWS = [
+ ['hedgebox.net/pricing', [172, 141], [50, 44], [121, 19], [900, 60], [16, 12], 94],
+ ['hedgebox.net/docs/getting-started', [164, 152], [61, 58], [103, 61], [921, 60], [12, 13], 61],
+ ['hedgebox.net/blog/why-hedgehogs-love-analytics', [162, 131], [45, 49], [117, 11], [889, 60], [14, 9], 132],
+ ['hedgebox.net/', [157, 149], [42, 40], [114, 84], [944, 60], [15, 15], 78],
+ ['hedgebox.net/features', [148, 119], [44, 41], [104, 17], [0, 0], [14, 11], 145],
+ ['hedgebox.net/about', [143, 133], [49, 52], [93, 66], [18, 17], [15, 14], 96],
+ ['hedgebox.net/docs/web-analytics', [137, 126], [42, 37], [95, 20], [861, 60], [16, 16], 112],
+ ['localhost:8010/login', [2, 1], [0, 0], [0, 0], [0, 0], [0, 0], 585],
+]
+
+const LEADERBOARD = {
+ columns: [
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.google_search',
+ 'context.columns.llm_referrals',
+ 'context.columns.agent_crawls',
+ 'context.columns.conversions',
+ 'context.columns.avg_time',
+ ],
+ results: PAGE_ROWS,
+}
+
+const CANDIDATES = {
+ columns: ['context.columns.breakdown_value'],
+ results: PAGE_ROWS.map((row) => [row[0]]),
+}
+
+const trend = (label: string, values: number[]): Record<string, unknown> => ({
+ results: [
+ {
+ action: { id: label, name: label, type: 'events', order: 0 },
+ label,
+ data: values,
+ days: BUCKETS,
+ labels: BUCKETS,
+ count: values.reduce((sum, value) => sum + value, 0),
+ },
+ ],
+})
+
+const breakdownTable = (rows: (string | number)[][]): Record<string, unknown> => ({
+ columns: ['context.columns.breakdown_value', 'context.columns.visitors'],
+ results: rows,
+})
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Web Analytics/Search & AI',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2023-02-01',
+ pageUrl: urls.webAnalyticsPagePerformance(),
+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE],
+ testOptions: {
+ includeNavigationInSnapshot: true,
+ waitForLoadersToDisappear: true,
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/stats': () => [200, { users_on_product: 2387 }],
+ '/api/projects/:team_id/event_definitions': () => [200, { count: 5 }],
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const query = ((await request.json()) as any).query
+ const source = query.source ?? query
+ const kind = source.kind
+
+ if (kind === 'DatabaseSchemaQuery') {
+ return [200, { tables: {}, joins: [] }]
+ }
+ if (kind === 'TrendsQuery') {
+ return [200, trend('Visitors', [180, 220, 190, 260, 240, 310, 295])]
+ }
+ if (kind === 'WebBotsTableQuery') {
+ return [
+ 200,
+ breakdownTable([
+ ['GPTBot', 31200],
+ ['ClaudeBot', 24800],
+ ['PerplexityBot', 16400],
+ ['Google-Extended', 9700],
+ ]),
+ ]
+ }
+ if (kind === 'WebStatsTableQuery') {
+ if (source.breakdownBy === 'InitialReferringDomain') {
+ return [
+ 200,
+ breakdownTable([
+ ['chatgpt.com', 640],
+ ['perplexity.ai', 410],
+ ['claude.ai', 220],
+ ]),
+ ]
+ }
+ return [200, CANDIDATES]
+ }
+ if (kind === 'HogQLQuery') {
+ if (source.query?.includes('AS crawls')) {
+ return [200, OVERVIEW_CRAWLER]
+ }
+ if (source.query?.includes('AS visitors')) {
+ return [200, OVERVIEW_HUMAN]
+ }
+ return [200, LEADERBOARD]
+ }
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+export function WebAnalyticsPagePerformance(): JSX.Element {
+ const { setConversionGoal } = useActions(webAnalyticsLogic)
+
+ useEffect(() => {
+ setConversionGoal({ customEventName: 'signed_up' })
+ }, [setConversionGoal])
+
+ return <App />
+}
diff --git a/frontend/src/scenes/web-analytics/PagePerformance.tsx b/frontend/src/scenes/web-analytics/PagePerformance.tsx
index 5b7fb782ed0b..5e4bb62f59f1 100644
--- a/frontend/src/scenes/web-analytics/PagePerformance.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformance.tsx
@@ -1,96 +1,122 @@
import clsx from 'clsx'
import { useActions, useMountedLogic, useValues } from 'kea'
-import { useMemo } from 'react'
+import { forwardRef, useMemo } from 'react'
import { IconTrending } from '@posthog/icons'
import { LemonBanner, LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { getColorVar } from 'lib/colors'
+import { useChartTheme } from 'lib/charts/hooks'
+import { seriesColor } from 'lib/charts/utils/theme'
import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { percentage } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
import { tryDecodeURIComponent } from 'lib/utils/url'
-import { OverviewGrid } from '~/queries/nodes/OverviewGrid/OverviewGrid'
import { Query } from '~/queries/Query/Query'
import { DataTableNode } from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumnComponent, QueryContextColumnTitleComponent } from '~/queries/types'
import { TileId } from './common'
import { PagePerformanceBreakdownModal } from './PagePerformanceBreakdownModal'
+import { PagePerformanceCard } from './PagePerformanceCard'
+import { PagePerformanceCardHeader } from './PagePerformanceCardHeader'
import {
- OVERVIEW_CARD_LABELS,
PagePerformanceMetric,
+ changeVsPrevious,
createPagePerformanceInsightProps,
+ formatShare,
+ pageVisitorsFromRecord,
pagePerformanceLogic,
+ parseMetricCell,
} from './pagePerformanceLogic'
+import { PagePerformanceMetricCard } from './PagePerformanceMetricCard'
import { WebQuery, webAnalyticsDataTableQueryContext } from './tiles/WebAnalyticsTile'
import { webAnalyticsLogic } from './webAnalyticsLogic'
-const asTuple = (value: unknown): [number, number] | null => {
- if (Array.isArray(value) && value.length >= 2) {
- return [Number(value[0] ?? 0), Number(value[1] ?? 0)]
- }
- return null
-}
-
const formatCount = (value: unknown): string =>
typeof value === 'number' ? value.toLocaleString() : String(value ?? 0)
type TrendIndicator = {
Icon: typeof IconTrending | typeof IconTrendingDown | typeof IconTrendingFlat
- color: string
className: string
}
-const trendIndicator = (pctChange: number | null): TrendIndicator | null => {
- if (pctChange === null) {
- return null
- }
+// The icons fill with `currentColor`, so the wrapper's text color is the whole story.
+const trendIndicator = (pctChange: number): TrendIndicator => {
if (pctChange === 0) {
- return { Icon: IconTrendingFlat, color: getColorVar('muted'), className: 'text-secondary' }
+ return { Icon: IconTrendingFlat, className: 'text-secondary' }
}
if (pctChange > 0) {
- return { Icon: IconTrending, color: getColorVar('success'), className: 'text-success' }
+ return { Icon: IconTrending, className: 'text-success' }
}
- return { Icon: IconTrendingDown, color: getColorVar('danger'), className: 'text-danger' }
+ return { Icon: IconTrendingDown, className: 'text-danger' }
}
-const DeltaValue = ({ value }: { value: unknown }): JSX.Element => {
- const { compareFilter } = useValues(pagePerformanceLogic)
- const tuple = asTuple(value)
- if (!tuple) {
- return <span>{formatCount(value)}</span>
+interface CellValueProps extends React.HTMLAttributes<HTMLDivElement> {
+ value: string
+ secondary?: React.ReactNode
+}
+
+/** Every numeric cell is one shape: the value, centered over a muted second line giving its context.
+ * Forwards its ref and props so `Tooltip` can use it as a trigger. */
+const CellValue = forwardRef<HTMLDivElement, CellValueProps>(function CellValue(
+ { value, secondary, ...rest },
+ ref
+): JSX.Element {
+ return (
+ <div ref={ref} className="flex flex-col items-center leading-tight" {...rest}>
+ <span className="whitespace-nowrap">{value}</span>
+ {secondary ? <span className="text-xs whitespace-nowrap text-secondary">{secondary}</span> : null}
+ </div>
+ )
+})
+
+/** The muted line under every value: its share of visitors, then how it moved. */
+const secondaryLine = (share: string | null, pctChange: number | null): React.ReactNode | undefined => {
+ if (!share && pctChange === null) {
+ return null
}
- const [current, previous] = tuple
- const compareOn = compareFilter.compare !== false
- const pctChange = !compareOn || previous === 0 ? null : current === previous ? 0 : current / previous - 1
- const trend = trendIndicator(pctChange)
- const tooltip =
- pctChange !== null && pctChange !== 0
- ? `${current >= previous ? 'Increased' : 'Decreased'} by ${percentage(Math.abs(pctChange), 0)} vs previous period`
- : undefined
+ const trend = pctChange === null ? null : trendIndicator(pctChange)
return (
- <Tooltip title={tooltip}>
- <span className="whitespace-nowrap">
- {formatCount(current)}
- {trend && (
- <span className={clsx('ml-1 inline-flex items-center text-xs', trend.className)}>
- <trend.Icon color={trend.color} />
- {pctChange !== null && pctChange !== 0 ? percentage(Math.abs(pctChange), 0) : ''}
- </span>
- )}
- </span>
- </Tooltip>
+ <span className="inline-flex items-center gap-1">
+ {share}
+ {share && trend ? <span>·</span> : null}
+ {trend && pctChange !== null ? (
+ <span className={clsx('inline-flex items-center', trend.className)}>
+ <trend.Icon />
+ {percentage(Math.abs(pctChange), 0)}
+ </span>
+ ) : null}
+ </span>
)
}
-const ValueWithSubtitle = ({ value, subtitle }: { value: string; subtitle: string }): JSX.Element => (
- <div className="flex flex-col items-end leading-tight">
- <span className="whitespace-nowrap">{value}</span>
- <span className="text-secondary text-xs whitespace-nowrap">{subtitle}</span>
- </div>
-)
+const changeTooltip = (pctChange: number | null): string | null =>
+ pctChange
+ ? `${pctChange > 0 ? 'Increased' : 'Decreased'} by ${percentage(Math.abs(pctChange), 0)} vs previous period`
+ : null
+
+/** The shared body of every metric column: a count over its share of some whole and its movement. */
+const MetricCell = ({
+ current,
+ previous,
+ whole,
+ tooltip,
+}: {
+ current: number
+ previous: number
+ whole: number
+ tooltip: string
+}): JSX.Element => {
+ const { comparePeriods } = useValues(pagePerformanceLogic)
+ const pctChange = comparePeriods ? changeVsPrevious(current, previous) : null
+ return (
+ <Tooltip title={[tooltip, changeTooltip(pctChange)].filter(Boolean).join('. ')}>
+ <CellValue value={formatCount(current)} secondary={secondaryLine(formatShare(current, whole), pctChange)} />
+ </Tooltip>
+ )
+}
const BreakdownLink = ({
metric,
@@ -108,7 +134,9 @@ const BreakdownLink = ({
type="tertiary"
size="small"
noPadding
- className="underline decoration-dotted underline-offset-2 hover:decoration-solid"
+ fullWidth
+ center
+ className="hover:underline"
onClick={() => openBreakdown({ page, metric })}
>
{children}
@@ -128,54 +156,97 @@ const PageCell: QueryContextColumnComponent = ({ value }) => {
)
}
-const VisitorsCell: QueryContextColumnComponent = ({ value }) => <DeltaValue value={value} />
+const VisitorsCell: QueryContextColumnComponent = ({ value }) => {
+ const { siteVisitors } = useValues(pagePerformanceLogic)
+ const cell = parseMetricCell(value)
+ if (!cell) {
+ return <span>{formatCount(value)}</span>
+ }
+ const share = formatShare(cell.current, siteVisitors)
+ return (
+ <MetricCell
+ current={cell.current}
+ previous={cell.previous}
+ whole={siteVisitors}
+ tooltip={share ? `${share} of the ${formatCount(siteVisitors)} visitors to your site this period` : ''}
+ />
+ )
+}
const GoogleSearchCell: QueryContextColumnComponent = ({ value, record }) => {
- const tuple = asTuple(value)
- const google = tuple?.[0] ?? 0
- const visitors = tuple?.[1] ?? 0
- const share = visitors > 0 ? percentage(google / visitors, 0) : '-'
+ const cell = parseMetricCell(value)
+ const visitors = pageVisitorsFromRecord(record)
return (
<BreakdownLink metric="google_search" record={record}>
- <ValueWithSubtitle value={formatCount(google)} subtitle={`${share} of visitors`} />
+ <MetricCell
+ current={cell?.current ?? 0}
+ previous={cell?.previous ?? 0}
+ whole={visitors}
+ tooltip={`${formatCount(cell?.current ?? 0)} of this page's ${formatCount(visitors)} visitors came from Google search`}
+ />
</BreakdownLink>
)
}
-const LlmReferralsCell: QueryContextColumnComponent = ({ value, record }) => (
- <BreakdownLink metric="llm_referrals" record={record}>
- <DeltaValue value={value} />
- </BreakdownLink>
-)
+const LlmReferralsCell: QueryContextColumnComponent = ({ value, record }) => {
+ const cell = parseMetricCell(value)
+ const visitors = pageVisitorsFromRecord(record)
+ return (
+ <BreakdownLink metric="llm_referrals" record={record}>
+ <MetricCell
+ current={cell?.current ?? 0}
+ previous={cell?.previous ?? 0}
+ whole={visitors}
+ tooltip={`${formatCount(cell?.current ?? 0)} of this page's ${formatCount(visitors)} visitors arrived from an AI assistant. This is a lower bound: some assistants strip the referrer, so those visits land in Direct`}
+ />
+ </BreakdownLink>
+ )
+}
+// Crawls count every bot hit rather than unique people, so this column shows a bot count, not a share.
const AgentCrawlsCell: QueryContextColumnComponent = ({ value, record }) => {
- const tuple = asTuple(value)
- const crawls = tuple?.[0] ?? 0
- const agents = tuple?.[1] ?? 0
+ const cell = parseMetricCell(value)
+ const crawls = cell?.current ?? 0
+ const agents = pluralize(cell?.previous ?? 0, 'agent')
+ const visitors = pageVisitorsFromRecord(record)
return (
<BreakdownLink metric="agent_crawls" record={record}>
- <ValueWithSubtitle
- value={formatCount(crawls)}
- subtitle={`${agents} ${agents === 1 ? 'agent' : 'agents'}`}
- />
+ <Tooltip
+ title={`${formatCount(crawls)} crawls of this page by ${agents}, against ${formatCount(visitors)} human visitors. Crawls count every bot hit, so they are not a share of visitors`}
+ >
+ <CellValue value={formatCount(crawls)} secondary={crawls > 0 ? agents : undefined} />
+ </Tooltip>
</BreakdownLink>
)
}
-const ConversionsCell: QueryContextColumnComponent = ({ value }) => {
+const ConversionsCell: QueryContextColumnComponent = ({ value, record }) => {
const { conversionGoal } = useValues(pagePerformanceLogic)
+ const cell = parseMetricCell(value)
+ const visitors = pageVisitorsFromRecord(record)
if (!conversionGoal) {
return <span className="text-secondary">-</span>
}
- const tuple = asTuple(value)
- const conversions = tuple?.[0] ?? 0
- const visitors = tuple?.[1] ?? 0
- const cvr = visitors > 0 ? percentage(conversions / visitors, 1) : '-'
- return <ValueWithSubtitle value={formatCount(conversions)} subtitle={`${cvr} CVR`} />
+ return (
+ <MetricCell
+ current={cell?.current ?? 0}
+ previous={cell?.previous ?? 0}
+ whole={visitors}
+ tooltip={`${formatCount(cell?.current ?? 0)} conversions from this page's ${formatCount(visitors)} visitors`}
+ />
+ )
}
const AvgTimeCell: QueryContextColumnComponent = ({ value }) => (
- <span className="whitespace-nowrap">{value ? humanFriendlyDuration(Number(value)) : '-'}</span>
+ <Tooltip
+ title={
+ value
+ ? 'The 90th percentile time visitors spent on this page before moving on. Needs a following pageview to measure, so the last page of a visit is not counted'
+ : 'No timing yet. This needs a following pageview to measure against, so pages that end a visit stay blank'
+ }
+ >
+ <span className="whitespace-nowrap">{value ? humanFriendlyDuration(Number(value)) : '-'}</span>
+ </Tooltip>
)
const sortableTitle = (label: string, column: string): QueryContextColumnTitleComponent =>
@@ -189,7 +260,9 @@ const sortableTitle = (label: string, column: string): QueryContextColumnTitleCo
type="tertiary"
size="small"
noPadding
- className="group cursor-pointer inline-flex items-center"
+ // `uppercase` because a <button> doesn't inherit the thead text-transform, so without
+ // it the sortable headers read sentence case next to the plain ones.
+ className="group cursor-pointer inline-flex items-center uppercase"
onClick={() => setOrderBy(column, active && orderBy.direction === 'DESC' ? 'ASC' : 'DESC')}
aria-label={`Sort by ${label} ${active && orderBy.direction === 'DESC' ? 'ascending' : 'descending'}`}
>
@@ -204,10 +277,8 @@ const sortableTitle = (label: string, column: string): QueryContextColumnTitleCo
)
}
-const cardHeading = (title: string): JSX.Element => (
- <div className="flex items-baseline gap-2 px-3 pt-3">
- <h3 className="font-semibold m-0">{title}</h3>
- </div>
+const SectionHeading = ({ children }: { children: React.ReactNode }): JSX.Element => (
+ <h2 className="mb-4 text-xl font-semibold text-primary">{children}</h2>
)
const AiTableCard = ({
@@ -228,10 +299,9 @@ const AiTableCard = ({
[tileId]
)
return (
- <div className="border rounded bg-surface-primary flex flex-col flex-1">
- {cardHeading(title)}
+ <PagePerformanceCard title={title} className="flex-1">
<Query uniqueKey={`page-performance-${tileId}`} query={query} readOnly context={context} />
- </div>
+ </PagePerformanceCard>
)
}
@@ -242,44 +312,45 @@ export const PagePerformance = (): JSX.Element => {
pageCandidates,
candidatesError,
candidatesLoading,
- overviewCards,
+ overviewMetrics,
overviewError,
overviewLoading,
footerText,
aiSectionQueries,
} = useValues(pagePerformanceLogic)
const { loadOverview, loadCandidates } = useActions(pagePerformanceLogic)
+ const theme = useChartTheme()
const context = useMemo(
(): QueryContext => ({
insightProps: createPagePerformanceInsightProps(TileId.PAGE_PERFORMANCE_TABLE, 'table'),
columns: {
breakdown_value: { title: 'Page', render: PageCell, width: '28%' },
- visitors: { renderTitle: sortableTitle('Visitors', 'visitors'), render: VisitorsCell, align: 'right' },
+ visitors: { renderTitle: sortableTitle('Visitors', 'visitors'), render: VisitorsCell, align: 'center' },
google_search: {
renderTitle: sortableTitle('Google search', 'google_search'),
render: GoogleSearchCell,
- align: 'right',
+ align: 'center',
},
llm_referrals: {
renderTitle: sortableTitle('LLM referrals', 'llm_referrals'),
render: LlmReferralsCell,
- align: 'right',
+ align: 'center',
},
agent_crawls: {
renderTitle: sortableTitle('Agent crawls', 'agent_crawls'),
render: AgentCrawlsCell,
- align: 'right',
+ align: 'center',
},
conversions: {
renderTitle: sortableTitle('Conversions', 'conversions'),
render: ConversionsCell,
- align: 'right',
+ align: 'center',
},
avg_time: {
renderTitle: sortableTitle('Avg. time', 'avg_time'),
render: AvgTimeCell,
- align: 'right',
+ align: 'center',
},
},
}),
@@ -287,53 +358,68 @@ export const PagePerformance = (): JSX.Element => {
)
return (
- <>
- <LemonBanner type="info" dismissKey="page-performance-alpha-info" className="mb-4">
- One leaderboard for how each page earns visits from Google, AI assistants, and the agents crawling your
- site. AI referrals are a lower bound: some assistants strip the referrer, so those visits land in
- Direct.
+ <div className="flex flex-col gap-4">
+ <LemonBanner
+ type="info"
+ dismissKey="web-analytics-search-and-ai-feedback-banner"
+ action={{ children: 'Send feedback', id: 'web-analytics-search-and-ai-feedback-button' }}
+ >
+ We'd love to hear what you think about search and AI.
</LemonBanner>
- {overviewError ? (
- <LemonBanner type="error" className="mb-4" action={{ children: 'Try again', onClick: loadOverview }}>
- Could not load the summary metrics. Try again to reload.
- </LemonBanner>
- ) : (
- <OverviewGrid
- items={overviewCards}
- loading={overviewLoading && overviewCards.length === 0}
- numSkeletons={4}
- labelFromKey={(key) => OVERVIEW_CARD_LABELS[key] ?? key}
- />
- )}
- <div className="border rounded bg-surface-primary flex flex-col mt-4">
- <div className="flex items-baseline justify-between gap-2 px-3 pt-3">
- <h3 className="font-semibold m-0">Pages ranked by visitors</h3>
- </div>
- {candidatesError ? (
+ <section>
+ <SectionHeading>Key metrics</SectionHeading>
+ {overviewError ? (
<LemonBanner
type="error"
- className="m-3"
- action={{ children: 'Try again', onClick: loadCandidates }}
+ action={{ children: 'Try again', onClick: loadOverview, loading: overviewLoading }}
>
- Could not load page performance. Try again to reload the leaderboard.
+ Could not load the summary metrics. Try again to reload.
</LemonBanner>
- ) : candidatesLoading && pageCandidates === null ? (
- <div className="flex items-center justify-center py-12">
- <Spinner className="text-2xl" />
- </div>
) : (
- <Query
- uniqueKey="page-performance-table"
- query={pageTableQuery}
- readOnly
- context={context}
- dataAttr="page-performance-table"
- />
+ <div className="@container">
+ <div className="grid grid-cols-2 gap-3 @3xl:grid-cols-4">
+ {overviewMetrics.map(({ key, ...metric }, index) => (
+ <PagePerformanceMetricCard
+ key={key}
+ {...metric}
+ data-attr={`page-performance-metric-${key}`}
+ color={seriesColor(theme, index)}
+ theme={theme}
+ loading={overviewLoading}
+ />
+ ))}
+ </div>
+ </div>
)}
- <div className="text-secondary text-xs px-3 pb-3">{footerText}</div>
- </div>
- <div className="mt-4">
- <h2 className="text-lg font-semibold mb-4">Traffic from AI</h2>
+ </section>
+ <section>
+ <SectionHeading>Pages</SectionHeading>
+ <PagePerformanceCard footer={footerText}>
+ {candidatesError ? (
+ <LemonBanner
+ type="error"
+ className="m-3"
+ action={{ children: 'Try again', onClick: loadCandidates, loading: candidatesLoading }}
+ >
+ Could not load the page leaderboard. Try again to reload it.
+ </LemonBanner>
+ ) : candidatesLoading && pageCandidates === null ? (
+ <div className="flex items-center justify-center py-12">
+ <Spinner className="text-2xl" />
+ </div>
+ ) : (
+ <Query
+ uniqueKey="page-performance-table"
+ query={pageTableQuery}
+ readOnly
+ context={context}
+ dataAttr="page-performance-table"
+ />
+ )}
+ </PagePerformanceCard>
+ </section>
+ <section>
+ <SectionHeading>Traffic from AI</SectionHeading>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="md:col-span-2 min-h-[350px] flex flex-col">
<WebQuery
@@ -343,7 +429,7 @@ export const PagePerformance = (): JSX.Element => {
insightProps={createPagePerformanceInsightProps(TileId.AI_REFERRALS_TREND)}
showIntervalSelect
tileId={TileId.AI_REFERRALS_TREND}
- headerSlot={cardHeading('Referrals over time')}
+ headerSlot={<PagePerformanceCardHeader title="Referrals over time" />}
/>
</div>
<AiTableCard
@@ -357,9 +443,9 @@ export const PagePerformance = (): JSX.Element => {
tileId={TileId.AI_LANDING_PAGES}
/>
</div>
- </div>
- <div className="mt-4">
- <h2 className="text-lg font-semibold mb-4">AI crawlers</h2>
+ </section>
+ <section>
+ <SectionHeading>AI crawlers</SectionHeading>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="md:col-span-2 min-h-[350px] flex flex-col">
<WebQuery
@@ -369,7 +455,7 @@ export const PagePerformance = (): JSX.Element => {
insightProps={createPagePerformanceInsightProps(TileId.AI_CRAWLERS_TREND)}
showIntervalSelect
tileId={TileId.AI_CRAWLERS_TREND}
- headerSlot={cardHeading('Crawler activity over time')}
+ headerSlot={<PagePerformanceCardHeader title="Crawler activity over time" />}
/>
</div>
<AiTableCard title="By crawler" query={aiSectionQueries.byCrawler} tileId={TileId.AI_CRAWLERS} />
@@ -379,8 +465,8 @@ export const PagePerformance = (): JSX.Element => {
tileId={TileId.AI_CRAWLED_PAGES}
/>
</div>
- </div>
+ </section>
<PagePerformanceBreakdownModal />
- </>
+ </div>
)
}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceCard.tsx b/frontend/src/scenes/web-analytics/PagePerformanceCard.tsx
new file mode 100644
index 000000000000..63310b922aaa
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformanceCard.tsx
@@ -0,0 +1,20 @@
+import clsx from 'clsx'
+
+import { PagePerformanceCardHeader } from './PagePerformanceCardHeader'
+
+export interface PagePerformanceCardProps {
+ title?: string
+ footer?: React.ReactNode
+ className?: string
+ children: React.ReactNode
+}
+
+export function PagePerformanceCard({ title, footer, className, children }: PagePerformanceCardProps): JSX.Element {
+ return (
+ <div className={clsx('border rounded bg-surface-primary flex flex-col', className)}>
+ {title ? <PagePerformanceCardHeader title={title} /> : null}
+ <div className="flex flex-col flex-1 min-h-0">{children}</div>
+ {footer ? <div className="border-t px-3 py-2 text-xs text-secondary">{footer}</div> : null}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx b/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx
new file mode 100644
index 000000000000..e209ba5d0c34
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx
@@ -0,0 +1,7 @@
+export function PagePerformanceCardHeader({ title }: { title: string }): JSX.Element {
+ return (
+ <div className="flex items-baseline gap-2 border-b px-3 py-2">
+ <h3 className="m-0 text-sm font-semibold">{title}</h3>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.stories.tsx b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.stories.tsx
new file mode 100644
index 000000000000..8a3ede68aa4f
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.stories.tsx
@@ -0,0 +1,55 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { PagePerformanceMetricCard, PagePerformanceMetricCardProps } from './PagePerformanceMetricCard'
+
+type StoryProps = Omit<PagePerformanceMetricCardProps, 'theme'>
+
+const SPARKLINE = [820, 910, 760, 1180, 1040, 1320, 1290]
+const SPARKLINE_LABELS = ['Aug 7', 'Aug 8', 'Aug 9', 'Aug 10', 'Aug 11', 'Aug 12', 'Aug 13']
+
+function ThemedMetricCard(props: StoryProps): JSX.Element {
+ const theme = useChartTheme()
+ return (
+ <div className="w-64">
+ <PagePerformanceMetricCard {...props} theme={theme} color={theme.colors[0]} />
+ </div>
+ )
+}
+
+type Story = StoryObj<StoryProps>
+const meta: Meta<StoryProps> = {
+ title: 'Scenes-App/Web Analytics/PagePerformanceMetricCard',
+ component: ThemedMetricCard,
+ args: {
+ label: 'LLM referrals',
+ value: 1290,
+ previous: 980,
+ changeFromPreviousPct: 32,
+ sparkline: SPARKLINE,
+ sparklineLabels: SPARKLINE_LABELS,
+ color: '',
+ loading: false,
+ },
+}
+export default meta
+
+export const Increase: Story = {}
+
+export const Decrease: Story = {
+ args: { value: 640, previous: 980, changeFromPreviousPct: -35 },
+}
+
+export const WithoutComparison: Story = {
+ args: { previous: null, changeFromPreviousPct: null },
+}
+
+export const WithoutSparkline: Story = {
+ args: { sparkline: [], sparklineLabels: [] },
+}
+
+export const Loading: Story = {
+ args: { loading: true },
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx
new file mode 100644
index 000000000000..a4b5a3e8ef63
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx
@@ -0,0 +1,92 @@
+import { memo } from 'react'
+
+import { IconTrending } from '@posthog/icons'
+import { LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { Sparkline } from '@posthog/quill-charts'
+import type { ChartTheme } from '@posthog/quill-charts'
+
+import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
+import { formatPercentage, humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+const SPARKLINE_HEIGHT = 44
+
+export interface PagePerformanceMetricCardProps {
+ label: string
+ value: number
+ previous: number | null
+ changeFromPreviousPct: number | null
+ sparkline: number[]
+ sparklineLabels: string[]
+ color: string
+ theme: ChartTheme
+ loading: boolean
+ 'data-attr'?: string
+}
+
+function DeltaTag({
+ changeFromPreviousPct,
+ previous,
+}: {
+ changeFromPreviousPct: number
+ previous: number | null
+}): JSX.Element {
+ const Icon =
+ changeFromPreviousPct === 0 ? IconTrendingFlat : changeFromPreviousPct > 0 ? IconTrending : IconTrendingDown
+ const type = changeFromPreviousPct === 0 ? 'muted' : changeFromPreviousPct > 0 ? 'success' : 'danger'
+ const tag = (
+ <LemonTag type={type} size="small" icon={<Icon />} className="tabular-nums">
+ {`${changeFromPreviousPct > 0 ? '+' : ''}${formatPercentage(changeFromPreviousPct)}`}
+ </LemonTag>
+ )
+ if (previous === null) {
+ return tag
+ }
+ return <Tooltip title={`${humanFriendlyLargeNumber(previous)} in the previous period`}>{tag}</Tooltip>
+}
+
+// Every prop is referentially stable, so unrelated scene renders shouldn't redraw four sparklines.
+export const PagePerformanceMetricCard = memo(function PagePerformanceMetricCard({
+ label,
+ value,
+ previous,
+ changeFromPreviousPct,
+ sparkline,
+ sparklineLabels,
+ color,
+ theme,
+ loading,
+ 'data-attr': dataAttr,
+}: PagePerformanceMetricCardProps): JSX.Element {
+ const hasSparkline = sparkline.some((point) => point > 0)
+
+ return (
+ <div className="border rounded bg-surface-primary flex flex-col overflow-hidden" data-attr={dataAttr}>
+ <div className="flex flex-col gap-1 px-3 pt-3">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-secondary truncate">{label}</span>
+ {!loading && changeFromPreviousPct !== null && (
+ <DeltaTag changeFromPreviousPct={changeFromPreviousPct} previous={previous} />
+ )}
+ </div>
+ {loading ? (
+ <LemonSkeleton className="h-8 w-20 my-0.5" />
+ ) : (
+ <div className="text-2xl font-semibold tabular-nums">{humanFriendlyLargeNumber(value)}</div>
+ )}
+ <div className="text-xs text-secondary">Total</div>
+ </div>
+ {!loading && hasSparkline && (
+ <div className="mt-2">
+ <Sparkline
+ data={sparkline}
+ labels={sparklineLabels}
+ theme={theme}
+ color={color}
+ type="line"
+ height={SPARKLINE_HEIGHT}
+ />
+ </div>
+ )}
+ </div>
+ )
+})
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
index 0314cda99ce7..54f5a10749f0 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
@@ -766,7 +766,7 @@ const pagePerformanceTab = (
key: ProductTab.PAGE_PERFORMANCE,
label: (
<div className="flex items-center gap-1">
- Page performance
+ Search & AI
<LemonTag type="completion" className="uppercase">
Alpha
</LemonTag>
diff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.ts
index 1228722a0591..525d33cc85d0 100644
--- a/frontend/src/scenes/web-analytics/common.ts
+++ b/frontend/src/scenes/web-analytics/common.ts
@@ -278,7 +278,7 @@ export const TILE_LABELS: Record<TileId, string> = {
[TileId.AI_CRAWLERS_TREND]: 'AI crawler activity over time',
[TileId.AI_CRAWLERS]: 'AI crawlers',
[TileId.AI_CRAWLED_PAGES]: 'Pages AI crawlers read',
- [TileId.PAGE_PERFORMANCE_TABLE]: 'Page performance',
+ [TileId.PAGE_PERFORMANCE_TABLE]: 'Pages by search & AI',
}
export interface BaseTile {
diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts
index 939cb1ca562b..33eb5077d501 100644
--- a/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.test.ts
@@ -6,6 +6,10 @@ import {
PagePerformanceWindow,
buildGoogleSearchConsoleQuery,
buildPagePerformanceTableQuery,
+ formatShare,
+ mergePagePerformanceSeries,
+ parsePagePerformanceOverviewResponse,
+ resolvePagePerformanceBucket,
resolvePagePerformanceWindow,
} from './pagePerformanceLogic'
import { DateFilterState } from './webAnalyticsLogic'
@@ -108,4 +112,112 @@ describe('pagePerformanceLogic', () => {
expect(query).toContain("toDate(date) <= toDate('2026-08-05 23:59:59')")
expect(query).not.toContain('ILIKE')
})
+
+ it.each([
+ { name: 'a small share keeps a decimal rather than rounding to zero', part: 2, whole: 1430, expected: '0.1%' },
+ { name: 'a share just under ten percent keeps a decimal', part: 137, whole: 1430, expected: '9.6%' },
+ { name: 'a large share drops the decimal', part: 172, whole: 1430, expected: '12%' },
+ { name: 'nothing to show when the part is zero', part: 0, whole: 1430, expected: null },
+ { name: 'nothing to show when the whole is zero', part: 12, whole: 0, expected: null },
+ ])('$name', ({ part, whole, expected }) => {
+ expect(formatShare(part, whole)).toBe(expected)
+ })
+
+ describe('overview series', () => {
+ const comparedWindow: PagePerformanceWindow = {
+ currentFrom: dayjs.tz('2026-08-03', timezone),
+ currentTo: dayjs.tz('2026-08-05', timezone).endOf('day'),
+ previousFrom: dayjs.tz('2026-08-01', timezone),
+ previousTo: dayjs.tz('2026-08-03', timezone),
+ timezone,
+ }
+ const humanColumns = ['bucket', 'visitors', 'visitors_previous', 'pages']
+
+ it('reads totals from the grouping-sets row instead of summing buckets', () => {
+ const parsed = parsePagePerformanceOverviewResponse(
+ humanColumns,
+ [
+ ['1970-01-01 00:00:00', 90, 40, 12],
+ ['2026-08-03 00:00:00', 50, 0, 7],
+ ['2026-08-04 00:00:00', 60, 0, 8],
+ ],
+ comparedWindow
+ )
+
+ // Summing the buckets would give 110 visitors — per-bucket uniques double-count returning people.
+ expect(parsed.totals.visitors).toBe(90)
+ expect(parsed.totals.visitors_previous).toBe(40)
+ expect(parsed.totals.pages).toBe(12)
+ expect(parsed.buckets).toHaveLength(2)
+ })
+
+ it('keeps comparison-period buckets out of the series', () => {
+ const parsed = parsePagePerformanceOverviewResponse(
+ humanColumns,
+ [
+ ['1970-01-01 00:00:00', 90, 40, 12],
+ ['2026-08-01 00:00:00', 0, 25, 0],
+ ['2026-08-02 00:00:00', 0, 15, 0],
+ ['2026-08-03 00:00:00', 50, 0, 7],
+ ],
+ comparedWindow
+ )
+
+ expect(parsed.buckets.map((point) => point.bucket.format('YYYY-MM-DD'))).toEqual(['2026-08-03'])
+ })
+
+ it('aligns crawler buckets onto the same axis when a query misses a bucket', () => {
+ const human = parsePagePerformanceOverviewResponse(
+ ['bucket', 'visitors', 'google', 'llm'],
+ [
+ ['1970-01-01 00:00:00', 90, 30, 5],
+ ['2026-08-03 00:00:00', 50, 20, 3],
+ ['2026-08-05 00:00:00', 40, 10, 2],
+ ],
+ comparedWindow
+ )
+ const crawler = parsePagePerformanceOverviewResponse(
+ ['bucket', 'crawls'],
+ [
+ ['1970-01-01 00:00:00', 700],
+ ['2026-08-04 00:00:00', 700],
+ ],
+ comparedWindow
+ )
+
+ expect(mergePagePerformanceSeries(human, crawler, 'day')).toEqual([
+ { label: 'Aug 3', visitors: 50, google: 20, llm: 3, crawls: 0 },
+ { label: 'Aug 4', visitors: 0, google: 0, llm: 0, crawls: 700 },
+ { label: 'Aug 5', visitors: 40, google: 10, llm: 2, crawls: 0 },
+ ])
+ })
+
+ it.each([
+ { name: 'a single day gets hourly buckets', dateFrom: '2026-08-05', expected: 'hour' },
+ { name: 'a week gets daily buckets', dateFrom: '2026-07-30', expected: 'day' },
+ { name: 'a year gets weekly buckets', dateFrom: '2025-08-06', expected: 'week' },
+ ])('$name', ({ dateFrom, expected }) => {
+ const window: PagePerformanceWindow = {
+ currentFrom: dayjs.tz(dateFrom, timezone),
+ currentTo: dayjs.tz('2026-08-06', timezone),
+ previousFrom: null,
+ previousTo: null,
+ timezone,
+ }
+
+ expect(resolvePagePerformanceBucket(window)).toBe(expected)
+ })
+
+ it('falls back to weekly buckets for an unbounded range', () => {
+ const window: PagePerformanceWindow = {
+ currentFrom: null,
+ currentTo: dayjs.tz('2026-08-06', timezone),
+ previousFrom: null,
+ previousTo: null,
+ timezone,
+ }
+
+ expect(resolvePagePerformanceBucket(window)).toBe('week')
+ })
+ })
})
diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
index 77199a0cbacb..686531ff2c4c 100644
--- a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
@@ -14,12 +14,13 @@ import { subscriptions } from 'kea-subscriptions'
import { dayjs } from 'lib/dayjs'
import { componentsToDayJs, dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'
+import { percentage } from 'lib/utils/numbers'
import { isAbortedRequest } from 'lib/utils/requests'
+import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { actionsModel } from '~/models/actionsModel'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
-import { OverviewItem } from '~/queries/nodes/OverviewGrid/OverviewGrid'
import { performQuery } from '~/queries/query'
import {
ActionConversionGoal,
@@ -113,6 +114,28 @@ export interface OverviewTotals {
pages: number
}
+export type PagePerformanceBucket = 'hour' | 'day' | 'week'
+
+export interface OverviewSeriesPoint {
+ label: string
+ visitors: number
+ google: number
+ llm: number
+ crawls: number
+}
+
+export type OverviewMetricKey = 'visitors' | 'google_search' | 'llm_referrals' | 'agent_crawls'
+
+export interface OverviewMetric {
+ key: OverviewMetricKey
+ label: string
+ value: number
+ previous: number | null
+ changeFromPreviousPct: number | null
+ sparkline: number[]
+ sparklineLabels: string[]
+}
+
export interface AiSectionQueries {
referralTrend: InsightVizNode
byEngine: DataTableNode
@@ -122,11 +145,53 @@ export interface AiSectionQueries {
crawledPages: DataTableNode
}
-export const OVERVIEW_CARD_LABELS: Record<string, string> = {
- visitors: 'Visitors',
- google_search: 'Google search',
- llm_referrals: 'LLM referrals',
- agent_crawls: 'Agent crawls',
+const OVERVIEW_METRICS: {
+ key: OverviewMetricKey
+ label: string
+ value: (totals: OverviewTotals) => number
+ previous: (totals: OverviewTotals) => number
+ series: (point: OverviewSeriesPoint) => number
+}[] = [
+ {
+ key: 'visitors',
+ label: 'Visitors',
+ value: (t) => t.visitors,
+ previous: (t) => t.visitorsPrevious,
+ series: (p) => p.visitors,
+ },
+ {
+ key: 'google_search',
+ label: 'Google search',
+ value: (t) => t.google,
+ previous: (t) => t.googlePrevious,
+ series: (p) => p.google,
+ },
+ {
+ key: 'llm_referrals',
+ label: 'LLM referrals',
+ value: (t) => t.llm,
+ previous: (t) => t.llmPrevious,
+ series: (p) => p.llm,
+ },
+ {
+ key: 'agent_crawls',
+ label: 'Agent crawls',
+ value: (t) => t.crawls,
+ previous: (t) => t.crawlsPrevious,
+ series: (p) => p.crawls,
+ },
+]
+
+const EMPTY_OVERVIEW_TOTALS: OverviewTotals = {
+ visitors: 0,
+ visitorsPrevious: 0,
+ google: 0,
+ googlePrevious: 0,
+ llm: 0,
+ llmPrevious: 0,
+ crawls: 0,
+ crawlsPrevious: 0,
+ pages: 0,
}
const tsLiteral = (date: dayjs.Dayjs, timezone: string): string => date.tz(timezone).format("'YYYY-MM-DD HH:mm:ss'")
@@ -190,6 +255,171 @@ export const resolvePagePerformanceWindow = (
return { currentFrom, currentTo, previousFrom, previousTo, timezone }
}
+export interface ParsedOverviewResponse {
+ totals: Record<string, number>
+ buckets: { bucket: dayjs.Dayjs; values: Record<string, number> }[]
+}
+
+/**
+ * Splits an overview response into its grand total and its per-bucket series. The queries group by
+ * `GROUPING SETS ((bucket), ())`, so one row carries the exact total over the whole window — summing
+ * the buckets would instead sum per-bucket uniques and overcount visitors.
+ */
+export const parsePagePerformanceOverviewResponse = (
+ columns: string[] | undefined,
+ results: unknown[][] | undefined,
+ window: PagePerformanceWindow
+): ParsedOverviewResponse => {
+ const cols = columns ?? []
+ const bucketIdx = cols.indexOf('bucket')
+ const totals: Record<string, number> = {}
+ const buckets: ParsedOverviewResponse['buckets'] = []
+
+ const readRow = (row: unknown[]): Record<string, number> => {
+ const values: Record<string, number> = {}
+ cols.forEach((name, idx) => {
+ if (name !== 'bucket') {
+ values[name] = Number(row[idx] ?? 0)
+ }
+ })
+ return values
+ }
+
+ for (const row of results ?? []) {
+ if (!Array.isArray(row)) {
+ continue
+ }
+ const rawBucket = bucketIdx >= 0 ? row[bucketIdx] : null
+ const bucket = rawBucket ? dayjs.tz(String(rawBucket), window.timezone) : null
+ // The grand-total row comes back with the DateTime default rather than a real bucket.
+ if (!bucket || !bucket.isValid() || bucket.year() <= 1970) {
+ Object.assign(totals, readRow(row))
+ continue
+ }
+ if (window.currentFrom && bucket.isBefore(window.currentFrom)) {
+ continue
+ }
+ buckets.push({ bucket, values: readRow(row) })
+ }
+
+ buckets.sort((a, b) => a.bucket.valueOf() - b.bucket.valueOf())
+ return { totals, buckets }
+}
+
+/** Aligns the human and crawler series onto one bucket axis — either query can miss a bucket entirely. */
+export const mergePagePerformanceSeries = (
+ human: ParsedOverviewResponse,
+ crawler: ParsedOverviewResponse,
+ bucketSize: PagePerformanceBucket
+): OverviewSeriesPoint[] => {
+ const byBucket = new Map<number, OverviewSeriesPoint>()
+
+ const upsert = (bucket: dayjs.Dayjs): OverviewSeriesPoint => {
+ const key = bucket.valueOf()
+ const existing = byBucket.get(key)
+ if (existing) {
+ return existing
+ }
+ const point: OverviewSeriesPoint = {
+ label: formatBucketLabel(bucket, bucketSize),
+ visitors: 0,
+ google: 0,
+ llm: 0,
+ crawls: 0,
+ }
+ byBucket.set(key, point)
+ return point
+ }
+
+ for (const { bucket, values } of human.buckets) {
+ const point = upsert(bucket)
+ point.visitors = values.visitors ?? 0
+ point.google = values.google ?? 0
+ point.llm = values.llm ?? 0
+ }
+ for (const { bucket, values } of crawler.buckets) {
+ upsert(bucket).crawls = values.crawls ?? 0
+ }
+
+ return [...byBucket.entries()].sort(([a], [b]) => a - b).map(([, point]) => point)
+}
+
+export const resolvePagePerformanceBucket = (window: PagePerformanceWindow): PagePerformanceBucket => {
+ if (!window.currentFrom) {
+ return 'week'
+ }
+ const days = window.currentTo.diff(window.currentFrom, 'day', true)
+ if (days <= 2) {
+ return 'hour'
+ }
+ if (days <= 120) {
+ return 'day'
+ }
+ return 'week'
+}
+
+const PAGE_TABLE_COLUMNS = [
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.google_search',
+ 'context.columns.llm_referrals',
+ 'context.columns.agent_crawls',
+ 'context.columns.conversions',
+ 'context.columns.avg_time',
+]
+
+const PAGE_TABLE_VISITORS_INDEX = PAGE_TABLE_COLUMNS.indexOf('context.columns.visitors')
+
+const BUCKET_HOGQL_FN: Record<PagePerformanceBucket, string> = {
+ hour: 'toStartOfHour',
+ day: 'toStartOfDay',
+ week: 'toStartOfWeek',
+}
+
+const BUCKET_LABEL_FORMAT: Record<PagePerformanceBucket, string> = {
+ hour: 'MMM D, HH:mm',
+ day: 'MMM D',
+ week: 'MMM D',
+}
+
+// The bucket is parsed with `dayjs.tz(..., timezone)`, so it already carries the target offset.
+const formatBucketLabel = (bucket: dayjs.Dayjs, bucketSize: PagePerformanceBucket): string =>
+ bucket.format(BUCKET_LABEL_FORMAT[bucketSize])
+
+export interface MetricCellValue {
+ current: number
+ previous: number
+}
+
+/** Every leaderboard metric column is `tuple(current, previous)`; agent crawls is `tuple(crawls, agents)`. */
+export const parseMetricCell = (value: unknown): MetricCellValue | null =>
+ Array.isArray(value) && value.length >= 2
+ ? { current: Number(value[0] ?? 0), previous: Number(value[1] ?? 0) }
+ : null
+
+/** The row's own human visitor count, which every other metric on that row is a share of. */
+export const pageVisitorsFromRecord = (record: unknown): number => {
+ const cell = Array.isArray(record) ? record[PAGE_TABLE_VISITORS_INDEX] : null
+ return Array.isArray(cell) ? Number(cell[0] ?? 0) : 0
+}
+
+/** Shares below 10% get a decimal, so a page holding 0.4% of site traffic doesn't read as 0%. */
+export const formatShare = (part: number, whole: number): string | null => {
+ if (whole <= 0 || part <= 0) {
+ return null
+ }
+ const fraction = part / whole
+ return percentage(fraction, fraction < 0.1 ? 1 : 0)
+}
+
+/** Percent change against the previous period, or null when there is no comparable baseline. */
+export const changeVsPrevious = (current: number, previous: number): number | null => {
+ if (previous === 0) {
+ return null
+ }
+ return current === previous ? 0 : current / previous - 1
+}
+
const SORTABLE_COLUMNS = new Set([
'breakdown_value',
'visitors',
@@ -237,9 +467,7 @@ export const buildPagePerformanceTableQuery = (
)
const match = conversionMatch(conversionGoal)
- const conversions = match
- ? `tuple(countIf((${match}) AND ${cur}), uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur}))`
- : 'tuple(0, 0)'
+ const conversions = match ? `tuple(countIf((${match}) AND ${cur}), countIf((${match}) AND ${prev}))` : 'tuple(0, 0)'
const orderExpr = orderByExpr(orderBy.column)
@@ -252,7 +480,7 @@ SELECT
) AS "context.columns.visitors",
tuple(
uniqIf(person_id, (${GOOGLE_VIEW}) AND ${cur}),
- uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur})
+ uniqIf(person_id, (${GOOGLE_VIEW}) AND ${prev})
) AS "context.columns.google_search",
tuple(
uniqIf(person_id, (${AI_VIEW}) AND ${cur}),
@@ -295,12 +523,17 @@ LIMIT ${PAGE_TABLE_LIMIT}
`
}
-const buildOverviewHumanQuery = (window: PagePerformanceWindow, pathExpr: string): string => {
+const buildOverviewHumanQuery = (
+ window: PagePerformanceWindow,
+ pathExpr: string,
+ bucketSize: PagePerformanceBucket
+): string => {
const { cur, prev, full } = windowPredicates(window)
const pageKey = pageKeyExpr(pathExpr)
return `
SELECT
+ ${BUCKET_HOGQL_FN[bucketSize]}(timestamp) AS bucket,
uniqIf(person_id, (${HUMAN_VIEW}) AND ${cur}) AS visitors,
uniqIf(person_id, (${HUMAN_VIEW}) AND ${prev}) AS visitors_previous,
uniqIf(person_id, (${GOOGLE_VIEW}) AND ${cur}) AS google,
@@ -316,14 +549,16 @@ WHERE and(
(${full}),
{filters}
)
+GROUP BY GROUPING SETS ((bucket), ())
`
}
-const buildOverviewCrawlerQuery = (window: PagePerformanceWindow): string => {
+const buildOverviewCrawlerQuery = (window: PagePerformanceWindow, bucketSize: PagePerformanceBucket): string => {
const { cur, prev, full } = windowPredicates(window)
return `
SELECT
+ ${BUCKET_HOGQL_FN[bucketSize]}(timestamp) AS bucket,
countIf((${CRAWLER}) AND ${cur}) AS crawls,
countIf((${CRAWLER}) AND ${prev}) AS crawls_previous
FROM events
@@ -334,6 +569,7 @@ WHERE and(
(${full}),
{filters}
)
+GROUP BY GROUPING SETS ((bucket), ())
`
}
@@ -415,12 +651,16 @@ export interface pagePerformanceLogicValues {
footerText: string
goalLabel: string | null
orderBy: PagePerformanceOrderBy
- overviewCards: OverviewItem[]
+ bucketSize: PagePerformanceBucket
+ comparePeriods: boolean
+ siteVisitors: number
overviewCrawlerQuery: string
overviewError: string | null
overviewHumanQuery: string
overviewInput: string
overviewLoading: boolean
+ overviewMetrics: OverviewMetric[]
+ overviewSeries: OverviewSeriesPoint[]
overviewTotals: OverviewTotals | null
pageCandidateQuery: WebStatsTableQuery
pageCandidates: string[] | null
@@ -441,8 +681,12 @@ export interface pagePerformanceLogicActions {
loadOverviewFailure: (error: string) => {
error: string
}
- loadOverviewSuccess: (overviewTotals: OverviewTotals) => {
+ loadOverviewSuccess: (
+ overviewTotals: OverviewTotals,
+ overviewSeries: OverviewSeriesPoint[]
+ ) => {
overviewTotals: OverviewTotals
+ overviewSeries: OverviewSeriesPoint[]
}
loadCandidates: () => {
value: true
@@ -490,8 +734,13 @@ export interface pagePerformanceLogicMeta {
conversionGoal: WebAnalyticsConversionGoal | null,
compareFilter: CompareFilter
) => AiSectionQueries
- overviewHumanQuery: (window: PagePerformanceWindow, pathExpr: string) => string
- overviewCrawlerQuery: (window: PagePerformanceWindow) => string
+ bucketSize: (window: PagePerformanceWindow) => PagePerformanceBucket
+ overviewHumanQuery: (
+ window: PagePerformanceWindow,
+ pathExpr: string,
+ bucketSize: PagePerformanceBucket
+ ) => string
+ overviewCrawlerQuery: (window: PagePerformanceWindow, bucketSize: PagePerformanceBucket) => string
overviewInput: (overviewHumanQuery: string, overviewCrawlerQuery: string, filterTestAccounts: boolean) => string
candidatesInput: (pageCandidateQuery: WebStatsTableQuery) => string
breakdownQuery: (
@@ -500,7 +749,13 @@ export interface pagePerformanceLogicMeta {
filterTestAccounts: boolean,
pathExpr: string
) => DataTableNode | null
- overviewCards: (overviewTotals: OverviewTotals | null, compareFilter: CompareFilter) => OverviewItem[]
+ comparePeriods: (compareFilter: CompareFilter) => boolean
+ siteVisitors: (overviewTotals: OverviewTotals | null) => number
+ overviewMetrics: (
+ overviewTotals: OverviewTotals | null,
+ overviewSeries: OverviewSeriesPoint[],
+ comparePeriods: boolean
+ ) => OverviewMetric[]
goalLabel: (conversionGoal: WebAnalyticsConversionGoal | null, allActions: ActionType[]) => string | null
footerText: (
overviewTotals: OverviewTotals | null,
@@ -542,7 +797,10 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
closeBreakdown: true,
loadOverview: true,
loadOverviewFailure: (error: string) => ({ error }),
- loadOverviewSuccess: (overviewTotals: OverviewTotals) => ({ overviewTotals }),
+ loadOverviewSuccess: (overviewTotals: OverviewTotals, overviewSeries: OverviewSeriesPoint[]) => ({
+ overviewTotals,
+ overviewSeries,
+ }),
loadCandidates: true,
loadCandidatesFailure: (error: string) => ({ error }),
loadCandidatesSuccess: (pageCandidates: string[]) => ({ pageCandidates }),
@@ -568,6 +826,13 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
loadOverviewSuccess: (_, { overviewTotals }) => overviewTotals,
},
],
+ overviewSeries: [
+ [] as OverviewSeriesPoint[],
+ {
+ loadOverview: () => [],
+ loadOverviewSuccess: (_, { overviewSeries }) => overviewSeries,
+ },
+ ],
overviewError: [
null as string | null,
{
@@ -843,13 +1108,28 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
}
},
],
+ bucketSize: [
+ (s) => [s.window],
+ (window: PagePerformanceWindow): PagePerformanceBucket => resolvePagePerformanceBucket(window),
+ ],
+ comparePeriods: [
+ (s) => [s.compareFilter],
+ (compareFilter: CompareFilter): boolean => compareFilter.compare !== false,
+ ],
+ // A number rather than the totals object, so a reload doesn't re-render every row on identity alone.
+ siteVisitors: [
+ (s) => [s.overviewTotals],
+ (overviewTotals: OverviewTotals | null): number => overviewTotals?.visitors ?? 0,
+ ],
overviewHumanQuery: [
- (s) => [s.window, s.pathExpr],
- (window: PagePerformanceWindow, pathExpr: string): string => buildOverviewHumanQuery(window, pathExpr),
+ (s) => [s.window, s.pathExpr, s.bucketSize],
+ (window: PagePerformanceWindow, pathExpr: string, bucketSize: PagePerformanceBucket): string =>
+ buildOverviewHumanQuery(window, pathExpr, bucketSize),
],
overviewCrawlerQuery: [
- (s) => [s.window],
- (window: PagePerformanceWindow): string => buildOverviewCrawlerQuery(window),
+ (s) => [s.window, s.bucketSize],
+ (window: PagePerformanceWindow, bucketSize: PagePerformanceBucket): string =>
+ buildOverviewCrawlerQuery(window, bucketSize),
],
overviewInput: [
(s) => [s.overviewHumanQuery, s.overviewCrawlerQuery, s.filterTestAccounts],
@@ -888,28 +1168,29 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
}
},
],
- overviewCards: [
- (s) => [s.overviewTotals, s.compareFilter],
- (overviewTotals: OverviewTotals | null, compareFilter: CompareFilter): OverviewItem[] => {
- const compare = compareFilter.compare !== false
- const card = (key: string, value: number, previous: number): OverviewItem => ({
- key,
- value,
- previous: compare ? previous : undefined,
- changeFromPreviousPct:
- compare && previous > 0 ? Math.round(((value - previous) / previous) * 100) : undefined,
- kind: 'unit',
+ overviewMetrics: [
+ (s) => [s.overviewTotals, s.overviewSeries, s.comparePeriods],
+ (
+ overviewTotals: OverviewTotals | null,
+ overviewSeries: OverviewSeriesPoint[],
+ comparePeriods: boolean
+ ): OverviewMetric[] => {
+ const totals = overviewTotals ?? EMPTY_OVERVIEW_TOTALS
+ const sparklineLabels = overviewSeries.map((point) => point.label)
+ return OVERVIEW_METRICS.map(({ key, label, value, previous, series }) => {
+ const current = value(totals)
+ const before = previous(totals)
+ return {
+ key,
+ label,
+ value: current,
+ previous: comparePeriods ? before : null,
+ changeFromPreviousPct:
+ comparePeriods && before > 0 ? Math.round(((current - before) / before) * 100) : null,
+ sparkline: overviewSeries.map(series),
+ sparklineLabels,
+ }
})
- const t = overviewTotals
- if (!t) {
- return []
- }
- return [
- card('visitors', t.visitors, t.visitorsPrevious),
- card('google_search', t.google, t.googlePrevious),
- card('llm_referrals', t.llm, t.llmPrevious),
- card('agent_crawls', t.crawls, t.crawlsPrevious),
- ]
},
],
goalLabel: [
@@ -931,103 +1212,100 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
goalLabel: string | null,
isPathCleaningEnabled: boolean
): string => {
- const pages = overviewTotals?.pages ?? 0
return [
- `${pages} ${pages === 1 ? 'page' : 'pages'}`,
+ pluralize(overviewTotals?.pages ?? 0, 'page'),
`conversion goal: ${goalLabel ?? 'not set'}`,
`path cleaning ${isPathCleaningEnabled ? 'on' : 'off'}`,
].join(' · ')
},
],
})),
- listeners(({ values, actions, cache }) => ({
- loadOverview: async (_, breakpoint) => {
- await breakpoint(300)
- cache.disposables.dispose('overviewRequest')
+ listeners(({ values, actions, cache }) => {
+ // Re-adding under the same key disposes the previous controller, aborting the request it owns.
+ const signalFor = (key: string): AbortSignal => {
const abortController = new AbortController()
- cache.disposables.add(() => () => abortController.abort(), 'overviewRequest', {
- pauseOnPageHidden: false,
- })
-
- const humanNode: HogQLQuery = {
- kind: NodeKind.HogQLQuery,
- query: values.overviewHumanQuery,
- filters: { filterTestAccounts: values.filterTestAccounts },
- tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
- }
- const crawlerNode: HogQLQuery = {
- kind: NodeKind.HogQLQuery,
- query: values.overviewCrawlerQuery,
- filters: { filterTestAccounts: values.filterTestAccounts },
- tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
- }
- try {
- const [humanResponse, crawlerResponse] = await Promise.all([
- performQuery(humanNode, { signal: abortController.signal }),
- performQuery(crawlerNode, { signal: abortController.signal }),
- ])
- breakpoint()
- const readColumn = (response: typeof humanResponse): ((name: string) => number) => {
- const row = response.results?.[0] ?? []
- const columns: string[] = response.columns ?? []
- return (name: string): number => {
- const idx = columns.indexOf(name)
- return idx >= 0 ? Number(row[idx] ?? 0) : 0
- }
- }
- const human = readColumn(humanResponse)
- const crawler = readColumn(crawlerResponse)
- actions.loadOverviewSuccess({
- visitors: human('visitors'),
- visitorsPrevious: human('visitors_previous'),
- google: human('google'),
- googlePrevious: human('google_previous'),
- llm: human('llm'),
- llmPrevious: human('llm_previous'),
- crawls: crawler('crawls'),
- crawlsPrevious: crawler('crawls_previous'),
- pages: human('pages'),
+ cache.disposables.add(() => () => abortController.abort(), key, { pauseOnPageHidden: false })
+ return abortController.signal
+ }
+ const isCancellation = (error: unknown): boolean =>
+ (error instanceof Error && isBreakpoint(error)) || isAbortedRequest(error)
+ const failureMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : 'Could not load search and AI data'
+
+ return {
+ loadOverview: async (_, breakpoint) => {
+ await breakpoint(300)
+ const signal = signalFor('overviewRequest')
+ const overviewNode = (query: string): HogQLQuery => ({
+ kind: NodeKind.HogQLQuery,
+ query,
+ filters: { filterTestAccounts: values.filterTestAccounts },
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
})
- } catch (error) {
- if ((error instanceof Error && isBreakpoint(error)) || isAbortedRequest(error)) {
- return
+ try {
+ const [humanResponse, crawlerResponse] = await Promise.all([
+ performQuery(overviewNode(values.overviewHumanQuery), { signal }),
+ performQuery(overviewNode(values.overviewCrawlerQuery), { signal }),
+ ])
+ breakpoint()
+ const { window: dateWindow, bucketSize } = values
+ const human = parsePagePerformanceOverviewResponse(
+ humanResponse.columns,
+ humanResponse.results,
+ dateWindow
+ )
+ const crawler = parsePagePerformanceOverviewResponse(
+ crawlerResponse.columns,
+ crawlerResponse.results,
+ dateWindow
+ )
+ actions.loadOverviewSuccess(
+ {
+ visitors: human.totals.visitors ?? 0,
+ visitorsPrevious: human.totals.visitors_previous ?? 0,
+ google: human.totals.google ?? 0,
+ googlePrevious: human.totals.google_previous ?? 0,
+ llm: human.totals.llm ?? 0,
+ llmPrevious: human.totals.llm_previous ?? 0,
+ crawls: crawler.totals.crawls ?? 0,
+ crawlsPrevious: crawler.totals.crawls_previous ?? 0,
+ pages: human.totals.pages ?? 0,
+ },
+ mergePagePerformanceSeries(human, crawler, bucketSize)
+ )
+ } catch (error) {
+ if (isCancellation(error)) {
+ return
+ }
+ actions.loadOverviewFailure(failureMessage(error))
}
- actions.loadOverviewFailure(error instanceof Error ? error.message : 'Could not load page performance')
- }
- },
- loadCandidates: async (_, breakpoint) => {
- await breakpoint(300)
- cache.disposables.dispose('candidatesRequest')
- const abortController = new AbortController()
- cache.disposables.add(() => () => abortController.abort(), 'candidatesRequest', {
- pauseOnPageHidden: false,
- })
- try {
- const candidatesResponse = await performQuery(values.pageCandidateQuery, {
- signal: abortController.signal,
- })
- breakpoint()
- const pageCandidates = (candidatesResponse.results ?? []).flatMap((candidate) => {
- if (!Array.isArray(candidate) || typeof candidate[0] !== 'string' || candidate[0] === '') {
- return []
+ },
+ loadCandidates: async (_, breakpoint) => {
+ await breakpoint(300)
+ const signal = signalFor('candidatesRequest')
+ try {
+ const candidatesResponse = await performQuery(values.pageCandidateQuery, { signal })
+ breakpoint()
+ const pageCandidates = (candidatesResponse.results ?? []).flatMap((candidate) => {
+ if (!Array.isArray(candidate) || typeof candidate[0] !== 'string' || candidate[0] === '') {
+ return []
+ }
+ return [candidate[0]]
+ })
+ actions.loadCandidatesSuccess(pageCandidates)
+ } catch (error) {
+ if (isCancellation(error)) {
+ return
}
- return [candidate[0]]
- })
- actions.loadCandidatesSuccess(pageCandidates)
- } catch (error) {
- if ((error instanceof Error && isBreakpoint(error)) || isAbortedRequest(error)) {
- return
+ actions.loadCandidatesFailure(failureMessage(error))
}
- actions.loadCandidatesFailure(
- error instanceof Error ? error.message : 'Could not load page performance'
- )
- }
- },
- reloadAll: () => {
- actions.loadOverview()
- actions.loadCandidates()
- },
- })),
+ },
+ reloadAll: () => {
+ actions.loadOverview()
+ actions.loadCandidates()
+ },
+ }
+ }),
subscriptions(({ actions }) => ({
overviewInput: () => {
actions.loadOverview()