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.

chore(web-analytics): Clean up search and ai page (#98735)

Jordan Mryyanc3a992cf1429
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8b1c1817c52f..6a7106085c40 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9677,25 +9677,25 @@ snapshots:
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
+ hash: v1.k794b7964.9b2656911ba7dcfe5be9679f5fce8bd6867a6d9742f4895e443b736d8f45534e.tNIfNHMaaZdgEijzWLIE53iHte-SYqwnDwMkAWflEjI
scenes-app-web-analytics-pageperformancemetriccard--loading--light:
- hash: v1.k794b7964.f443ef8e5973b74cf0be0f1ef3a918e06b6dcb725a7049ee3cc779fb7117345c.5hMKj4vx2ZkD5TueIzw5BXRuLxwD3LWJp8mN8Nj60Tw
+ hash: v1.k794b7964.f18b0d03d76151ce305d4093f06be3b7384d1d60b81f26317393d0eb1e0ea1f3.sujRlDAKtYfEkbRwmRqW4mpvGfw2GahmMYfddiawb9E
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
+ hash: v1.k794b7964.55240799900ad880b8e40b2f0a00936830f0547a88613cd476610d2e2e72947b.ihwaSOiLbve6MI_IKzxYoEn3CJjSC1-HkkNxAcZBGDU
scenes-app-web-analytics-pageperformancemetriccard--without-sparkline--light:
- hash: v1.k794b7964.27bbdd01e4451fe0fe7cfbf693975714907972cdef4cc9b74ab13f99c28f5c34.9VZtUj_jx6H9AXXqTTKz1uomaF3X9e8cENkeIs8iJ_I
+ hash: v1.k794b7964.e7ebd4a413d617f5c6e38419027f3affa40cd1da68af95d686ccc152860dbb5b.Fq3Sz8vrvMYKZQk1yKdN-t5SvImO0L7rvFjFf0ZyfFc
scenes-app-web-analytics-search-ai--web-analytics-page-performance--dark:
- hash: v1.k794b7964.60c001e801c861bd1b9a0dbfa7c3b87d6d5b8ed03af7cd145e88ce2dafa9df81.7dliypqCJeOXP_wCTJMeIxEW4urr1TjnnfKmp9T-fMM
+ hash: v1.k794b7964.68dca7f6cb1918fc9d2c5fd7382628ea8b7420354667f7d870c71317285afdba.ATRlxNrQzCTs0o8800vW-QDfwij5sum9pIg331-0jUA
scenes-app-web-analytics-search-ai--web-analytics-page-performance--light:
- hash: v1.k794b7964.6139f596e3f9ff7ba00323248dedc923bf4020b1c6f0ee4948628ed41228dfb3.gf2_OMHy67IGdywFrlPSzb1yjFe_Zc-550tBFTCqSJE
+ hash: v1.k794b7964.5102d8c456b1b54b149d2dc93d65495de58273ff633fb94e20d0ae993693545a.0Zyz6slZi94bN3k8kGQN4fBD9GSXaX7sdAhuW-DE2_U
scenes-app-web-analytics-search-ai--web-analytics-page-performance-no-ai-traffic--dark:
- hash: v1.k794b7964.ff693d29af19c34091c70dc0e5a22853d7f35b01ab3459f6a2bf1f2b06c57536.rM7sS7EbyqrDzgeTX1Nz6Xu63xYhT9KbpNi97rJzsmQ
+ hash: v1.k794b7964.5610802f8d3d5be68c322aa3b9e08517be29765c172162e0e23ffece580016e8.GJ6Kyir0y2PzZlhzYBJAjts-d-MgUB8rcWbRw4tngHE
scenes-app-web-analytics-search-ai--web-analytics-page-performance-no-ai-traffic--light:
- hash: v1.k794b7964.d28c10ae27c8ddbee128184c1555e0aa6aefc81ac5c6702a0721d84ca9811c46.TEn8Vcq05e1uAqQ_zoQfOvYYsE9BXU9Y0ev2W5QDSro
+ hash: v1.k794b7964.2a2f7e3ddb87d638638be1ad9977a3ef41f84d03a0429ce1dd2aab61035a0e4b.8BY7FUKBDiyiQtNnl_fZblkDCz8OSkKgHcDPmNu4jNo
scenes-app-workflows-createaitaskconnectors--no-approved-tools--dark:
hash: v1.k794b7964.21192b03ef6f65ad46bd4fc88738669fc7b2902dcbce0db252a3d2417e10172b.lhKBZM-VPET3_AhQCAUubBUu7qAu8KlducA4WUsWhOM
scenes-app-workflows-createaitaskconnectors--no-approved-tools--light:
diff --git a/frontend/src/scenes/web-analytics/PagePerformance.tsx b/frontend/src/scenes/web-analytics/PagePerformance.tsx
index cb1aed25b21a..9c3f99479ea8 100644
--- a/frontend/src/scenes/web-analytics/PagePerformance.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformance.tsx
@@ -1,24 +1,21 @@
-import clsx from 'clsx'
import { useActions, useMountedLogic, useValues } from 'kea'
-import { forwardRef, useMemo } from 'react'
+import { useMemo } from 'react'
-import { IconInfo, IconTrending } from '@posthog/icons'
-import { LemonBanner, LemonButton, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
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 { urls } from 'scenes/urls'
-import { Query } from '~/queries/Query/Query'
-import { DataTableNode, ProductKey } from '~/queries/schema/schema-general'
-import { QueryContext, QueryContextColumnComponent, QueryContextColumnTitleComponent } from '~/queries/types'
+import { DataTableNode, InsightVizNode, ProductKey } from '~/queries/schema/schema-general'
+import { QueryContext } from '~/queries/types'
import { OnboardingStepKey } from '~/types'
+import { SearchAndAiLoading } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiLoading'
+import { SearchAndAiQuery } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiQuery'
+import { SearchAndAiTable } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiTable'
+import { SearchAndAiTrendHeader } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiTrendHeader'
+
import { TileId } from './common'
import { PagePerformanceBreakdownModal } from './PagePerformanceBreakdownModal'
import { PagePerformanceCard } from './PagePerformanceCard'
@@ -26,283 +23,17 @@ import { PagePerformanceCardHeader } from './PagePerformanceCardHeader'
import { PagePerformanceEmptyState } from './PagePerformanceEmptyState'
import {
PagePerformanceCrawlerState,
- PagePerformanceMetric,
PagePerformanceTabState,
- changeVsPrevious,
createPagePerformanceInsightProps,
- formatShare,
- pageVisitorsFromRecord,
pagePerformanceLogic,
- parseMetricCell,
} from './pagePerformanceLogic'
import { PagePerformanceMetricCard } from './PagePerformanceMetricCard'
import { WebQuery, webAnalyticsDataTableQueryContext } from './tiles/WebAnalyticsTile'
import { webAnalyticsLogic } from './webAnalyticsLogic'
-const formatCount = (value: unknown): string =>
- typeof value === 'number' ? value.toLocaleString() : String(value ?? 0)
-
-type TrendIndicator = {
- Icon: typeof IconTrending | typeof IconTrendingDown | typeof IconTrendingFlat
- className: string
-}
-
-// 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, className: 'text-secondary' }
- }
- if (pctChange > 0) {
- return { Icon: IconTrending, className: 'text-success' }
- }
- return { Icon: IconTrendingDown, className: 'text-danger' }
-}
-
-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 trend = pctChange === null ? null : trendIndicator(pctChange)
- return (
- <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 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,
- record,
- children,
-}: {
- metric: PagePerformanceMetric
- record: unknown
- children: React.ReactNode
-}): JSX.Element => {
- const { openBreakdown } = useActions(pagePerformanceLogic)
- const page = Array.isArray(record) ? String(record[0] ?? '') : ''
- return (
- <LemonButton
- type="tertiary"
- size="small"
- noPadding
- fullWidth
- center
- className="hover:underline"
- onClick={() => openBreakdown({ page, metric })}
- >
- {children}
- </LemonButton>
- )
-}
-
-const PageCell: QueryContextColumnComponent = ({ value }) => {
- if (typeof value !== 'string') {
- return <span className="text-secondary italic">(none)</span>
- }
- const decoded = tryDecodeURIComponent(value)
- return (
- <Tooltip title={decoded}>
- <span className="font-medium">{decoded}</span>
- </Tooltip>
- )
-}
-
-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 cell = parseMetricCell(value)
- const visitors = pageVisitorsFromRecord(record)
- return (
- <BreakdownLink metric="google_search" 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 came from Google search`}
- />
- </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 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}>
- <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, record }) => {
- const { conversionGoal } = useValues(pagePerformanceLogic)
- const cell = parseMetricCell(value)
- const visitors = pageVisitorsFromRecord(record)
- if (!conversionGoal) {
- return <span className="text-secondary">-</span>
- }
- 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 }) => (
- <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 =>
- function SortableTitle() {
- const { orderBy } = useValues(pagePerformanceLogic)
- const { setOrderBy } = useActions(pagePerformanceLogic)
- const active = orderBy.column === column
- const ascending = active && orderBy.direction === 'ASC'
- return (
- <LemonButton
- type="tertiary"
- size="small"
- noPadding
- // `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'}`}
- >
- {label}
- <IconTrending
- className={clsx('ml-1 opacity-0 group-hover:opacity-100', {
- 'text-primary opacity-100': active,
- 'rotate-180': ascending,
- })}
- />
- </LemonButton>
- )
- }
-
const CRAWLER_CAVEAT =
"AI crawlers don't run JavaScript, so the browser SDK never sees them. Forward your server access logs to count them."
-const AgentCrawlsSortableTitle = sortableTitle('Agent crawls', 'agent_crawls')
-
-/** An empty crawler feed still renders as a hard zero, so the header says when that zero means "not measured". */
-const AgentCrawlsTitle: QueryContextColumnTitleComponent = (props) => {
- const { dataState } = useValues(pagePerformanceLogic)
- if (dataState.crawlers !== 'needs-server-logs') {
- return <AgentCrawlsSortableTitle {...props} />
- }
- return (
- <span className="inline-flex items-center gap-1">
- <AgentCrawlsSortableTitle {...props} />
- <Tooltip title={CRAWLER_CAVEAT}>
- <IconInfo className="shrink-0" />
- </Tooltip>
- </span>
- )
-}
-
const SectionHeading = ({
children,
description,
@@ -406,69 +137,70 @@ const AiTableCard = ({
...webAnalyticsDataTableQueryContext,
insightProps: createPagePerformanceInsightProps(tileId, 'table'),
showLoadNextButton: true,
+ tableLayout: 'fixed',
+ suppressSlowQuerySuggestions: true,
}),
[tileId]
)
return (
- <PagePerformanceCard title={title} className="flex-1">
- <Query uniqueKey={`page-performance-${tileId}`} query={query} readOnly context={context} />
+ <PagePerformanceCard className="flex-1 min-w-0">
+ <SearchAndAiQuery
+ uniqueKey={`page-performance-${tileId}`}
+ query={query}
+ insightProps={context.insightProps!}
+ context={context}
+ header={<PagePerformanceCardHeader title={title} />}
+ />
</PagePerformanceCard>
)
}
+const AiTrendCard = ({
+ title,
+ query,
+ tileId,
+ uniqueKey,
+}: {
+ title: string
+ query: InsightVizNode
+ tileId: TileId
+ uniqueKey: string
+}): JSX.Element => (
+ <div className="@min-[48rem]/search-ai:col-span-2 min-h-88 min-w-0 flex flex-col">
+ <SearchAndAiQuery
+ uniqueKey={uniqueKey}
+ query={query}
+ insightProps={createPagePerformanceInsightProps(tileId)}
+ renderQuery={(insightProps) => (
+ <WebQuery
+ attachTo={webAnalyticsLogic}
+ uniqueKey={uniqueKey}
+ query={query}
+ insightProps={insightProps}
+ tileId={tileId}
+ headerSlot={<SearchAndAiTrendHeader title={title} />}
+ />
+ )}
+ />
+ </div>
+)
+
export const PagePerformance = (): JSX.Element => {
useMountedLogic(pagePerformanceLogic)
const {
- pageTableQuery,
pageCandidates,
candidatesError,
candidatesLoading,
+ overviewTotals,
overviewMetrics,
overviewError,
overviewLoading,
- footerText,
aiSectionQueries,
dataState,
} = 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: 'center' },
- google_search: {
- renderTitle: sortableTitle('Google search', 'google_search'),
- render: GoogleSearchCell,
- align: 'center',
- },
- llm_referrals: {
- renderTitle: sortableTitle('LLM referrals', 'llm_referrals'),
- render: LlmReferralsCell,
- align: 'center',
- },
- agent_crawls: {
- renderTitle: AgentCrawlsTitle,
- render: AgentCrawlsCell,
- align: 'center',
- },
- conversions: {
- renderTitle: sortableTitle('Conversions', 'conversions'),
- render: ConversionsCell,
- align: 'center',
- },
- avg_time: {
- renderTitle: sortableTitle('Avg. time', 'avg_time'),
- render: AvgTimeCell,
- align: 'center',
- },
- },
- }),
- []
- )
-
const feedbackBanner = (
<LemonBanner
type="info"
@@ -479,74 +211,84 @@ export const PagePerformance = (): JSX.Element => {
</LemonBanner>
)
+ const overviewErrorBanner = overviewError && (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: () => loadOverview(), loading: overviewLoading }}
+ >
+ {overviewTotals
+ ? 'Could not update the summary metrics. Showing the previous results. Try again to refresh.'
+ : 'Could not load the summary metrics. Try again to reload.'}
+ </LemonBanner>
+ )
+
if (dataState.tab === 'no-events' || dataState.tab === 'no-traffic-in-range') {
return (
- <div className="flex flex-col gap-4">
+ <div className="SearchAndAiDashboard @container/search-ai flex flex-col gap-5 min-w-0">
{feedbackBanner}
- <TabEmptyState state={dataState.tab} />
+ {overviewErrorBanner}
+ <SearchAndAiLoading loading={overviewLoading}>
+ <TabEmptyState state={dataState.tab} />
+ </SearchAndAiLoading>
</div>
)
}
return (
- <div className="flex flex-col gap-4">
+ <div className="SearchAndAiDashboard @container/search-ai flex flex-col gap-5 min-w-0">
{feedbackBanner}
<section>
<SectionHeading>Key metrics</SectionHeading>
- {overviewError ? (
- <LemonBanner
- type="error"
- action={{ children: 'Try again', onClick: loadOverview, loading: overviewLoading }}
- >
- Could not load the summary metrics. Try again to reload.
- </LemonBanner>
- ) : (
- <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}
- caveat={
- key === 'agent_crawls' && dataState.crawlers === 'needs-server-logs'
- ? CRAWLER_CAVEAT
- : undefined
- }
- />
- ))}
+ {overviewErrorBanner}
+ {(!overviewError || overviewTotals) && (
+ <SearchAndAiLoading loading={overviewLoading && !!overviewTotals}>
+ <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={!overviewTotals && !overviewError}
+ caveat={
+ key === 'agent_crawls' && dataState.crawlers === 'needs-server-logs'
+ ? CRAWLER_CAVEAT
+ : undefined
+ }
+ />
+ ))}
+ </div>
</div>
- </div>
+ </SearchAndAiLoading>
)}
</section>
<section>
<SectionHeading description="How each page earns its traffic, from search engines through to AI crawlers.">
Pages
</SectionHeading>
- <PagePerformanceCard footer={footerText}>
- {candidatesError ? (
+ <PagePerformanceCard>
+ {candidatesError && (
<LemonBanner
type="error"
className="m-3"
- action={{ children: 'Try again', onClick: loadCandidates, loading: candidatesLoading }}
+ action={{
+ children: 'Try again',
+ onClick: () => loadCandidates(),
+ loading: candidatesLoading,
+ }}
>
- Could not load the page leaderboard. Try again to reload it.
+ {pageCandidates
+ ? 'Could not update the page list. Showing the previous results. Try again to refresh.'
+ : 'Could not load the page list. Try again to reload.'}
</LemonBanner>
- ) : candidatesLoading && pageCandidates === null ? (
- <div className="flex items-center justify-center py-12">
- <Spinner className="text-2xl" />
- </div>
+ )}
+
+ {pageCandidates === null ? (
+ !candidatesError && <SearchAndAiLoading loading label="Loading pages" className="min-h-64" />
) : (
- <Query
- uniqueKey="page-performance-table"
- query={pageTableQuery}
- readOnly
- context={context}
- dataAttr="page-performance-table"
- />
+ <SearchAndAiTable />
)}
</PagePerformanceCard>
</section>
@@ -554,21 +296,19 @@ export const PagePerformance = (): JSX.Element => {
<SectionHeading description="People who landed on your site from an AI assistant such as ChatGPT, Claude, or Perplexity.">
Traffic from AI
</SectionHeading>
+
{dataState.aiTraffic === 'empty' ? (
- <AiTrafficEmptyState />
+ <SearchAndAiLoading loading={overviewLoading}>
+ <AiTrafficEmptyState />
+ </SearchAndAiLoading>
) : (
- <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
- attachTo={webAnalyticsLogic}
- uniqueKey="page-performance-ai-referrals-trend"
- query={aiSectionQueries.referralTrend}
- insightProps={createPagePerformanceInsightProps(TileId.AI_REFERRALS_TREND)}
- showIntervalSelect
- tileId={TileId.AI_REFERRALS_TREND}
- headerSlot={<PagePerformanceCardHeader title="Referrals over time" />}
- />
- </div>
+ <div className="grid grid-cols-1 @min-[48rem]/search-ai:grid-cols-2 gap-4">
+ <AiTrendCard
+ title="Referrals over time"
+ query={aiSectionQueries.referralTrend}
+ tileId={TileId.AI_REFERRALS_TREND}
+ uniqueKey="page-performance-ai-referrals-trend"
+ />
<AiTableCard
title="By engine"
query={aiSectionQueries.byEngine}
@@ -586,21 +326,19 @@ export const PagePerformance = (): JSX.Element => {
<SectionHeading description="Bots that read your pages to train a model or to answer someone's question about you.">
AI crawlers
</SectionHeading>
+
{dataState.crawlers === 'empty' || dataState.crawlers === 'needs-server-logs' ? (
- <CrawlersEmptyState state={dataState.crawlers} />
+ <SearchAndAiLoading loading={overviewLoading}>
+ <CrawlersEmptyState state={dataState.crawlers} />
+ </SearchAndAiLoading>
) : (
- <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
- attachTo={webAnalyticsLogic}
- uniqueKey="page-performance-ai-crawler-trend"
- query={aiSectionQueries.crawlerTrend}
- insightProps={createPagePerformanceInsightProps(TileId.AI_CRAWLERS_TREND)}
- showIntervalSelect
- tileId={TileId.AI_CRAWLERS_TREND}
- headerSlot={<PagePerformanceCardHeader title="Crawler activity over time" />}
- />
- </div>
+ <div className="grid grid-cols-1 @min-[48rem]/search-ai:grid-cols-2 gap-4">
+ <AiTrendCard
+ title="Crawler activity over time"
+ query={aiSectionQueries.crawlerTrend}
+ tileId={TileId.AI_CRAWLERS_TREND}
+ uniqueKey="page-performance-ai-crawler-trend"
+ />
<AiTableCard
title="By crawler"
query={aiSectionQueries.byCrawler}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx b/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx
index 76a5bc8a611a..81f7cb7cb40e 100644
--- a/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformanceBreakdownModal.tsx
@@ -1,15 +1,17 @@
import { useActions, useValues } from 'kea'
-import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
-import { Query } from '~/queries/Query/Query'
import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
import { InsightLogicProps } from '~/types'
+import { SearchAndAiLoading } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiLoading'
+import { SearchAndAiQuery } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiQuery'
+
import { TileId, WEB_ANALYTICS_DEFAULT_QUERY_TAGS } from './common'
import {
PagePerformanceMetric,
@@ -22,8 +24,8 @@ const GSC_DOCS_URL = 'https://posthog.com/docs/cdp/sources/google-search-console
const GSC_TABLE_NAME = 'search_analytics_by_query_page'
const MODAL_TITLE: Record<PagePerformanceMetric, string> = {
- llm_referrals: 'LLM referrals',
- agent_crawls: 'Agent crawls',
+ llm_referrals: 'AI referrals',
+ agent_crawls: 'AI crawls',
google_search: 'Google search',
}
@@ -47,22 +49,22 @@ const GoogleBreakdown = ({ page, insightProps }: { page: string; insightProps: I
const gscTable = dataWarehouseTables.find((t) => t.name.includes(GSC_TABLE_NAME))
if (!gscTable) {
- if (databaseLoadError) {
+ if (databaseLoadError && !databaseLoading) {
return (
<LemonBanner
type="error"
- action={{ children: 'Try again', onClick: () => loadDatabase({ force: true }) }}
+ action={{
+ children: 'Try again',
+ onClick: () => loadDatabase({ force: true }),
+ loading: databaseLoading,
+ }}
>
Could not load data warehouse tables. Try again to check for your Google Search Console source.
</LemonBanner>
)
}
if (databaseLoading || !database) {
- return (
- <div className="flex items-center justify-center py-8">
- <Spinner className="text-2xl" />
- </div>
- )
+ return <SearchAndAiLoading loading label="Checking Google Search Console" className="min-h-64" />
}
return (
<div className="flex flex-col items-center gap-3 py-8 text-center">
@@ -93,7 +95,7 @@ const GoogleBreakdown = ({ page, insightProps }: { page: string; insightProps: I
embedded: true,
showActions: false,
}
- return <Query uniqueKey="page-performance-gsc-breakdown" query={query} readOnly context={{ insightProps }} />
+ return <SearchAndAiQuery uniqueKey="page-performance-gsc-breakdown" query={query} insightProps={insightProps} />
}
export const PagePerformanceBreakdownModal = (): JSX.Element => {
@@ -110,11 +112,10 @@ export const PagePerformanceBreakdownModal = (): JSX.Element => {
body = <GoogleBreakdown page={page} insightProps={insightProps} />
} else if (breakdownQuery) {
body = (
- <Query
+ <SearchAndAiQuery
uniqueKey={`page-performance-${metric}-breakdown`}
query={breakdownQuery}
- readOnly
- context={{ insightProps }}
+ insightProps={insightProps}
/>
)
}
@@ -123,14 +124,14 @@ export const PagePerformanceBreakdownModal = (): JSX.Element => {
<LemonModal
isOpen={isOpen}
onClose={closeBreakdown}
- title={`${MODAL_TITLE[metric]}: ${page || 'this page'}`}
+ title={<span className="break-words">{`${MODAL_TITLE[metric]}: ${page || 'this page'}`}</span>}
description={MODAL_SUBTITLE[metric]}
width={640}
>
{metric === 'llm_referrals' && (
<LemonBanner type="info" className="mb-3">
These are people who arrived from an AI assistant, not the assistants' crawlers. Open{' '}
- <strong>Agent crawls</strong> for the machines reading this page.
+ <strong>AI crawls</strong> for the machines reading this page.
</LemonBanner>
)}
{body}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx b/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx
index e209ba5d0c34..ebfaa641c0af 100644
--- a/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformanceCardHeader.tsx
@@ -1,7 +1,10 @@
-export function PagePerformanceCardHeader({ title }: { title: string }): JSX.Element {
+import { ReactNode } from 'react'
+
+export function PagePerformanceCardHeader({ title, actions }: { title: string; actions?: ReactNode }): JSX.Element {
return (
- <div className="flex items-baseline gap-2 border-b px-3 py-2">
+ <div className="flex flex-wrap items-center justify-between gap-2 border-b px-3 py-2">
<h3 className="m-0 text-sm font-semibold">{title}</h3>
+ {actions}
</div>
)
}
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx b/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx
index 6165b393e21d..9da7ebe5c0bd 100644
--- a/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformanceFilters.tsx
@@ -10,18 +10,19 @@ import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
+import { SearchAndAiFiltersPopover } from 'products/web_analytics/frontend/searchAndAi/SearchAndAiFiltersPopover'
+
import { WEB_ANALYTICS_DATA_COLLECTION_NODE_ID } from './common'
import { webAnalyticsDateMapping } from './constants'
import { pagePerformanceLogic } from './pagePerformanceLogic'
import { PathCleaningToggle } from './PathCleaningToggle'
-import { WebAnalyticsDeviceToggle, WebAnalyticsDomainSelector } from './WebAnalyticsFilters'
+import { WebAnalyticsDomainSelector } from './WebAnalyticsFilters'
import { webAnalyticsLogic } from './webAnalyticsLogic'
import { WebConversionGoal } from './WebConversionGoal'
-import { WebPropertyFilters } from './WebPropertyFilters'
/**
* Country and referrer narrow this tab's queries and round-trip through its URL, but neither has a
- * control of its own here the way the domain and device selections do. A shared link that carries
+ * control of its own here the way the domain selection does. A shared link that carries
* one would otherwise filter the numbers with nothing on screen to explain it. Renders nothing when
* neither is set, which is the usual case.
*/
@@ -72,7 +73,7 @@ export const PagePerformanceFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Ele
onClick={reloadAll}
icon={isReloading ? <Spinner textColored /> : <IconRefresh />}
disabledReason={isReloading ? 'Loading' : undefined}
- aria-label="Reload page performance"
+ aria-label="Reload Search & AI"
/>
<DateFilter
dateOptions={webAnalyticsDateMapping}
@@ -82,16 +83,11 @@ export const PagePerformanceFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Ele
onChange={setDates}
/>
<WebAnalyticsDomainSelector />
- <WebAnalyticsDeviceToggle />
<ActiveDrillDownFilters />
<CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />
<PathCleaningToggle value={isPathCleaningEnabled} onChange={setIsPathCleaningEnabled} />
- </>
- }
- right={
- <>
<WebConversionGoal value={conversionGoal} onChange={setConversionGoal} />
- <WebPropertyFilters />
+ <SearchAndAiFiltersPopover />
</>
}
/>
diff --git a/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx
index a9353dd4af18..a90e90bc510a 100644
--- a/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformanceMetricCard.tsx
@@ -1,7 +1,7 @@
import { memo } from 'react'
import { IconInfo, IconTrending } from '@posthog/icons'
-import { LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { LemonTag, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
import { Sparkline } from '@posthog/quill-charts'
import type { ChartTheme } from '@posthog/quill-charts'
@@ -63,7 +63,13 @@ export const PagePerformanceMetricCard = memo(function PagePerformanceMetricCard
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="relative isolate border rounded bg-surface-primary flex flex-col overflow-hidden"
+ data-attr={dataAttr}
+ aria-busy={loading}
+ role={loading ? 'status' : undefined}
+ aria-label={loading ? `Loading ${label}` : undefined}
+ >
<div className="flex flex-col gap-1 px-3 pt-3">
<div className="flex items-center justify-between gap-2">
<span className="flex items-center gap-1 text-xs font-medium text-secondary truncate">
@@ -79,14 +85,14 @@ export const PagePerformanceMetricCard = memo(function PagePerformanceMetricCard
)}
</div>
{loading ? (
- <LemonSkeleton className="h-8 w-20 my-0.5" />
+ <div className="h-8 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">
+ <div className="mt-2 h-11">
+ {!loading && hasSparkline ? (
<Sparkline
data={sparkline}
labels={sparklineLabels}
@@ -95,8 +101,9 @@ export const PagePerformanceMetricCard = memo(function PagePerformanceMetricCard
type="line"
height={SPARKLINE_HEIGHT}
/>
- </div>
- )}
+ ) : null}
+ </div>
+ {loading && <SpinnerOverlay />}
</div>
)
})
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
index a501edb9aa8d..58aeda175d19 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
@@ -441,7 +441,7 @@ export const WebAnalyticsLiveReferrerSelector = ({ suggestions = [] }: { suggest
)
}
-export const WebAnalyticsDeviceToggle = (): JSX.Element => {
+export const WebAnalyticsDeviceToggle = ({ variant }: { variant?: 'select' } = {}): JSX.Element => {
const { deviceTypeFilter } = useValues(webAnalyticsLogic)
const { setDeviceTypeFilter } = useActions(webAnalyticsLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -464,12 +464,17 @@ export const WebAnalyticsDeviceToggle = (): JSX.Element => {
scope: Scene.WebAnalytics,
})
- if (featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_FILTERS_V2] || featureFlags[FEATURE_FLAGS.CONDENSED_FILTER_BAR]) {
+ if (
+ variant === 'select' ||
+ featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_FILTERS_V2] ||
+ featureFlags[FEATURE_FLAGS.CONDENSED_FILTER_BAR]
+ ) {
return (
<LemonSelect
size="small"
value={deviceTypeFilter ?? undefined}
allowClear={true}
+ placeholder="All devices"
onChange={(value) => setDeviceTypeFilter(value !== deviceTypeFilter ? value : null)}
options={DEVICE_TYPE_SELECT_OPTIONS}
/>
diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
index 78f2e3ffb0d3..57232a12c382 100644
--- a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
@@ -170,14 +170,14 @@ const OVERVIEW_METRICS: {
},
{
key: 'llm_referrals',
- label: 'LLM referrals',
+ label: 'AI referrals',
value: (t) => t.llm,
previous: (t) => t.llmPrevious,
series: (p) => p.llm,
},
{
key: 'agent_crawls',
- label: 'Agent crawls',
+ label: 'AI crawls',
value: (t) => t.crawls,
previous: (t) => t.crawlsPrevious,
series: (p) => p.crawls,
@@ -399,18 +399,6 @@ export const resolvePagePerformanceBucket = (window: PagePerformanceWindow): Pag
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',
@@ -428,12 +416,6 @@ export const parseMetricCell = (value: unknown): MetricCellValue | null =>
? { 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) {
@@ -704,6 +686,7 @@ export interface pagePerformanceLogicValues {
pageCandidateQuery: WebStatsTableQuery
pageCandidates: string[] | null
pageTableQuery: DataTableNode
+ pageTableInput: string
pathExpr: string
previousPathExpr: string
window: PagePerformanceWindow
@@ -714,9 +697,7 @@ export interface pagePerformanceLogicActions {
closeBreakdown: () => {
value: true
}
- loadOverview: () => {
- value: true
- }
+ loadOverview: (reset?: boolean) => { reset: boolean }
loadOverviewFailure: (error: string) => {
error: string
}
@@ -727,9 +708,7 @@ export interface pagePerformanceLogicActions {
overviewTotals: OverviewTotals
overviewSeries: OverviewSeriesPoint[]
}
- loadCandidates: () => {
- value: true
- }
+ loadCandidates: (reset?: boolean) => { reset: boolean }
loadCandidatesFailure: (error: string) => {
error: string
}
@@ -852,13 +831,13 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
setOrderBy: (column: string, direction: 'ASC' | 'DESC') => ({ column, direction }),
openBreakdown: (breakdown: PagePerformanceBreakdownState) => ({ breakdown }),
closeBreakdown: true,
- loadOverview: true,
+ loadOverview: (reset: boolean = false) => ({ reset }),
loadOverviewFailure: (error: string) => ({ error }),
loadOverviewSuccess: (overviewTotals: OverviewTotals, overviewSeries: OverviewSeriesPoint[]) => ({
overviewTotals,
overviewSeries,
}),
- loadCandidates: true,
+ loadCandidates: (reset: boolean = false) => ({ reset }),
loadCandidatesFailure: (error: string) => ({ error }),
loadCandidatesSuccess: (pageCandidates: string[]) => ({ pageCandidates }),
}),
@@ -879,14 +858,14 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
overviewTotals: [
null as OverviewTotals | null,
{
- loadOverview: () => null,
+ loadOverview: (state, { reset }) => (reset ? null : state),
loadOverviewSuccess: (_, { overviewTotals }) => overviewTotals,
},
],
overviewSeries: [
[] as OverviewSeriesPoint[],
{
- loadOverview: () => [],
+ loadOverview: (state, { reset }) => (reset ? [] : state),
loadOverviewSuccess: (_, { overviewSeries }) => overviewSeries,
},
],
@@ -908,8 +887,13 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
pageCandidates: [
null as string[] | null,
{
- loadCandidates: () => null,
- loadCandidatesSuccess: (_, { pageCandidates }) => pageCandidates,
+ loadCandidates: (state, { reset }) => (reset ? null : state),
+ loadCandidatesSuccess: (state, { pageCandidates }) =>
+ state &&
+ state.length === pageCandidates.length &&
+ state.every((page, index) => page === pageCandidates[index])
+ ? state
+ : pageCandidates,
},
],
candidatesError: [
@@ -1219,6 +1203,14 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
): string =>
JSON.stringify([overviewHumanQuery, overviewCrawlerQuery, filterTestAccounts, webAnalyticsFilters]),
],
+ pageTableInput: [
+ (s) => [s.overviewInput, s.orderBy, s.conversionGoal],
+ (
+ overviewInput: string,
+ orderBy: PagePerformanceOrderBy,
+ conversionGoal: WebAnalyticsConversionGoal | null
+ ): string => JSON.stringify([overviewInput, orderBy, conversionGoal]),
+ ],
candidatesInput: [
(s) => [s.pageCandidateQuery],
(pageCandidateQuery: WebStatsTableQuery): string => JSON.stringify(pageCandidateQuery),
@@ -1297,10 +1289,12 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
isPathCleaningEnabled: boolean
): string => {
return [
- pluralize(overviewTotals?.pages ?? 0, 'page'),
+ overviewTotals ? pluralize(overviewTotals.pages, 'page') : null,
`conversion goal: ${goalLabel ?? 'not set'}`,
`path cleaning ${isPathCleaningEnabled ? 'on' : 'off'}`,
- ].join(' · ')
+ ]
+ .filter(Boolean)
+ .join(' · ')
},
],
})),
@@ -1317,7 +1311,7 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
error instanceof Error ? error.message : 'Could not load search and AI data'
return {
- loadOverview: async (_, breakpoint) => {
+ loadOverview: async ({ reset }, breakpoint) => {
await breakpoint(300)
const signal = signalFor('overviewRequest')
const overviewNode = (query: string): HogQLQuery => ({
@@ -1331,8 +1325,16 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
})
try {
const [humanResponse, crawlerResponse] = await Promise.all([
- performQuery(overviewNode(values.overviewHumanQuery), { signal }),
- performQuery(overviewNode(values.overviewCrawlerQuery), { signal }),
+ performQuery(
+ overviewNode(values.overviewHumanQuery),
+ { signal },
+ reset ? 'blocking' : 'force_blocking'
+ ),
+ performQuery(
+ overviewNode(values.overviewCrawlerQuery),
+ { signal },
+ reset ? 'blocking' : 'force_blocking'
+ ),
])
breakpoint()
const { window: dateWindow } = values
@@ -1362,17 +1364,22 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
mergePagePerformanceSeries(human, crawler)
)
} catch (error) {
- if (isCancellation(error)) {
+ if (isCancellation(error) || cache.disposables.isDisposed) {
return
}
+ breakpoint()
actions.loadOverviewFailure(failureMessage(error))
}
},
- loadCandidates: async (_, breakpoint) => {
+ loadCandidates: async ({ reset }, breakpoint) => {
await breakpoint(300)
const signal = signalFor('candidatesRequest')
try {
- const candidatesResponse = await performQuery(values.pageCandidateQuery, { signal })
+ const candidatesResponse = await performQuery(
+ values.pageCandidateQuery,
+ { signal },
+ reset ? 'blocking' : 'force_blocking'
+ )
breakpoint()
const pageCandidates = (candidatesResponse.results ?? []).flatMap((candidate) => {
if (!Array.isArray(candidate) || typeof candidate[0] !== 'string' || candidate[0] === '') {
@@ -1382,9 +1389,10 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
})
actions.loadCandidatesSuccess(pageCandidates)
} catch (error) {
- if (isCancellation(error)) {
+ if (isCancellation(error) || cache.disposables.isDisposed) {
return
}
+ breakpoint()
actions.loadCandidatesFailure(failureMessage(error))
}
},
@@ -1396,15 +1404,15 @@ export const pagePerformanceLogic = kea<pagePerformanceLogicType>([
}),
subscriptions(({ actions }) => ({
overviewInput: () => {
- actions.loadOverview()
+ actions.loadOverview(true)
},
candidatesInput: () => {
- actions.loadCandidates()
+ actions.loadCandidates(true)
},
})),
afterMount(({ actions }) => {
- actions.loadOverview()
- actions.loadCandidates()
+ actions.loadOverview(true)
+ actions.loadCandidates(true)
}),
])
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiFiltersPopover.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiFiltersPopover.tsx
new file mode 100644
index 000000000000..8ae2820fd85b
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiFiltersPopover.tsx
@@ -0,0 +1,71 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconFilter } from '@posthog/icons'
+import { LemonButton, LemonDivider, Popover } from '@posthog/lemon-ui'
+
+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { isWebAnalyticsPropertyFilter } from 'lib/components/PropertyFilters/utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { IconWithCount } from 'lib/lemon-ui/icons'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { WebAnalyticsDeviceToggle } from 'scenes/web-analytics/WebAnalyticsFilters'
+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
+import {
+ WEB_ANALYTICS_PROPERTY_ALLOW_LIST,
+ getWebAnalyticsTaxonomicGroupTypes,
+} from 'scenes/web-analytics/WebPropertyFilters'
+
+export function SearchAndAiFiltersPopover(): JSX.Element {
+ const [visible, setVisible] = useState(false)
+ const { rawWebAnalyticsFilters, deviceTypeFilter, preAggregatedEnabled, hasIncompatibleFilters } =
+ useValues(webAnalyticsLogic)
+ const { setWebAnalyticsFilters } = useActions(webAnalyticsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ return (
+ <Popover
+ visible={visible}
+ onClickOutside={() => setVisible(false)}
+ placement="bottom-end"
+ overlay={
+ <div className="p-3 w-96 max-w-full space-y-3">
+ <div className="font-semibold">Property filters</div>
+ <PropertyFilters
+ disablePopover
+ propertyFilters={rawWebAnalyticsFilters}
+ onChange={(filters) => setWebAnalyticsFilters(filters.filter(isWebAnalyticsPropertyFilter))}
+ propertyAllowList={preAggregatedEnabled ? WEB_ANALYTICS_PROPERTY_ALLOW_LIST : undefined}
+ taxonomicGroupTypes={getWebAnalyticsTaxonomicGroupTypes(
+ preAggregatedEnabled ?? false,
+ !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_FILTERS_V2]
+ )}
+ pageKey="web-analytics"
+ eventNames={['$pageview']}
+ />
+ <LemonDivider />
+ <div className="font-semibold">Device</div>
+ <WebAnalyticsDeviceToggle variant="select" />
+ </div>
+ }
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ tooltip={
+ hasIncompatibleFilters ? 'Some filters are not supported by the optimized query engine' : undefined
+ }
+ data-attr="show-web-analytics-filters"
+ onClick={() => setVisible(!visible)}
+ aria-expanded={visible}
+ icon={
+ <IconWithCount count={rawWebAnalyticsFilters.length + (deviceTypeFilter ? 1 : 0)} showZero={false}>
+ <IconFilter />
+ </IconWithCount>
+ }
+ >
+ Filters
+ </LemonButton>
+ </Popover>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiLoading.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiLoading.tsx
new file mode 100644
index 000000000000..86b6999704be
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiLoading.tsx
@@ -0,0 +1,35 @@
+import clsx from 'clsx'
+import { ReactNode } from 'react'
+
+import { SpinnerOverlay } from '@posthog/lemon-ui'
+
+export function SearchAndAiLoading({
+ loading,
+ label = 'Updating…',
+ className,
+ children,
+}: {
+ loading: boolean
+ label?: string
+ className?: string
+ children?: ReactNode
+}): JSX.Element {
+ return (
+ <div
+ className={clsx(
+ 'SearchAndAiLoading relative isolate min-w-0 flex flex-col flex-1',
+ loading && 'SearchAndAiLoading--active',
+ className
+ )}
+ aria-busy={loading}
+ >
+ {children}
+ {loading && (
+ <div role="status" aria-label={label}>
+ <SpinnerOverlay />
+ <span className="sr-only">{label}</span>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx
new file mode 100644
index 000000000000..d9063defe76f
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiMetricCell.tsx
@@ -0,0 +1,131 @@
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+
+import { IconTrending } from '@posthog/icons'
+import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+
+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 {
+ changeVsPrevious,
+ formatShare,
+ PagePerformanceMetric,
+ pagePerformanceLogic,
+ parseMetricCell,
+} from 'scenes/web-analytics/pagePerformanceLogic'
+
+export type SearchAndAiMetric =
+ | 'visitors'
+ | 'google_search'
+ | 'llm_referrals'
+ | 'agent_crawls'
+ | 'conversions'
+ | 'avg_time'
+
+const METRIC_INDEX: Record<SearchAndAiMetric, number> = {
+ visitors: 1,
+ google_search: 2,
+ llm_referrals: 3,
+ agent_crawls: 4,
+ conversions: 5,
+ avg_time: 6,
+}
+
+const isBreakdownMetric = (metric: SearchAndAiMetric): metric is PagePerformanceMetric =>
+ metric === 'google_search' || metric === 'llm_referrals' || metric === 'agent_crawls'
+
+export function SearchAndAiMetricCell({ metric, record }: { metric: SearchAndAiMetric; record: unknown }): JSX.Element {
+ const { comparePeriods, siteVisitors, conversionGoal, dataState } = useValues(pagePerformanceLogic)
+ const { openBreakdown } = useActions(pagePerformanceLogic)
+ const row = Array.isArray(record) ? record : []
+ const value = row[METRIC_INDEX[metric]]
+ const cell = parseMetricCell(value)
+ const current = cell?.current ?? 0
+ const previous = cell?.previous ?? 0
+ const visitors = parseMetricCell(row[1])?.current ?? 0
+ const share = formatShare(current, metric === 'visitors' ? siteVisitors : visitors)
+ const isCrawler = metric === 'agent_crawls'
+
+ if (metric === 'avg_time') {
+ return (
+ <Tooltip title="The 90th percentile time visitors spent on this page before moving on. A following pageview is needed, so the last page of a visit is not counted.">
+ <span>{value ? humanFriendlyDuration(Number(value)) : 'No timing yet'}</span>
+ </Tooltip>
+ )
+ }
+ if (metric === 'conversions' && !conversionGoal) {
+ return (
+ <Tooltip title="Choose a conversion goal to see conversions for each page.">
+ <span className="text-secondary">Not set</span>
+ </Tooltip>
+ )
+ }
+ if (isCrawler && dataState.crawlers === 'needs-server-logs') {
+ return (
+ <Tooltip title="Forward your server access logs to measure AI crawlers. Crawlers do not run the browser SDK.">
+ <span className="text-secondary">Not measured</span>
+ </Tooltip>
+ )
+ }
+
+ const change = comparePeriods && !isCrawler ? changeVsPrevious(current, previous) : null
+ const TrendIcon = change === 0 ? IconTrendingFlat : (change ?? 0) > 0 ? IconTrending : IconTrendingDown
+
+ const tooltip = {
+ visitors: `${share ?? '0%'} of the ${siteVisitors.toLocaleString()} visitors to your site this period`,
+ google_search: `${current.toLocaleString()} of this page's ${visitors.toLocaleString()} visitors came from Google search`,
+ llm_referrals: `${current.toLocaleString()} of this page's ${visitors.toLocaleString()} visitors arrived from an AI assistant. This is a lower bound: some assistants strip the referrer, so those visits land in Direct`,
+ agent_crawls: `${current.toLocaleString()} crawls by ${pluralize(previous, 'agent')}. Crawls count every bot hit, not unique visitors`,
+ conversions: `${current.toLocaleString()} conversions from this page's ${visitors.toLocaleString()} visitors`,
+ }[metric]
+ const content = (
+ <span className="flex flex-col items-center leading-tight tabular-nums">
+ <span className="whitespace-nowrap">{current.toLocaleString()}</span>
+ <span className="inline-flex items-center gap-1 text-xs text-secondary whitespace-nowrap">
+ {isCrawler ? <span>{current > 0 ? pluralize(previous, 'agent') : null}</span> : <span>{share}</span>}
+ {change !== null && (
+ <span
+ className={clsx(
+ 'inline-flex items-center',
+ change === 0 ? 'text-secondary' : change > 0 ? 'text-success' : 'text-danger'
+ )}
+ >
+ <TrendIcon />
+ <span>{percentage(Math.abs(change), 0)}</span>
+ </span>
+ )}
+ </span>
+ </span>
+ )
+ const title = [
+ tooltip,
+ change === null
+ ? null
+ : `${change > 0 ? 'Increased' : change < 0 ? 'Decreased' : 'Changed'} by ${percentage(Math.abs(change), 0)} vs previous period`,
+ ]
+ .filter(Boolean)
+ .join('. ')
+
+ return (
+ <Tooltip title={title}>
+ {isBreakdownMetric(metric) ? (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ noPadding
+ fullWidth
+ center
+ className="hover:underline"
+ onClick={() => openBreakdown({ page: String(row[0] ?? ''), metric })}
+ data-attr={`page-performance-breakdown-${metric}`}
+ >
+ {content}
+ </LemonButton>
+ ) : (
+ <span className="inline-block">{content}</span>
+ )}
+ </Tooltip>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiQuery.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiQuery.tsx
new file mode 100644
index 000000000000..2accdbb25fc6
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiQuery.tsx
@@ -0,0 +1,127 @@
+import { useActions, useValues } from 'kea'
+import { ReactNode, useMemo } from 'react'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import {
+ buildDataTableTileDataNodeLogicProps,
+ buildInsightVizTileDataNodeLogicProps,
+} from 'scenes/web-analytics/tiles/skeletons/useTileSkeletonLoading'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { Query } from '~/queries/Query/Query'
+import { DataTableNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
+import { QueryContext } from '~/queries/types'
+import { InsightLogicProps } from '~/types'
+
+import { SearchAndAiLoading } from './SearchAndAiLoading'
+import { searchAndAiQueryLogic } from './searchAndAiQueryLogic'
+
+export function SearchAndAiQuery({
+ query,
+ insightProps,
+ context,
+ renderQuery,
+ uniqueKey,
+ footer,
+ dataAttr,
+ pending = false,
+ header,
+ resultsKey,
+}: {
+ query: DataTableNode | InsightVizNode
+ insightProps: InsightLogicProps
+ context?: QueryContext
+ renderQuery?: (insightProps: InsightLogicProps) => ReactNode
+ uniqueKey: string
+ footer?: ReactNode
+ dataAttr?: string
+ pending?: boolean
+ header?: ReactNode
+ resultsKey?: string
+}): JSX.Element {
+ const dataNodeLogicProps = useMemo(
+ () =>
+ query.kind === NodeKind.DataTableNode
+ ? buildDataTableTileDataNodeLogicProps({ query, insightProps, context: { ...context, insightProps } })
+ : buildInsightVizTileDataNodeLogicProps({ query, insightProps }),
+ [query, insightProps, context]
+ )
+ const logic = dataNodeLogic(dataNodeLogicProps)
+ const { response, responseLoading, responseError, nextDataLoading } = useValues(logic)
+ const { loadData } = useActions(logic)
+ const { hasCurrentResponse, lastResponse } = useValues(searchAndAiQueryLogic({ dataNodeLogicProps, resultsKey }))
+ const loading = responseLoading || (!hasCurrentResponse && !responseError)
+ const initialLoading = loading && !hasCurrentResponse
+ const showPreviousResults = hasCurrentResponse && (!!responseError || !response)
+ const previousInsightProps: InsightLogicProps = useMemo(
+ () => ({
+ ...insightProps,
+ dashboardItemId: `new-previous-${insightProps.dashboardItemId}`,
+ doNotLoad: true,
+ cachedInsight: {
+ query,
+ result: lastResponse && 'results' in lastResponse ? lastResponse.results : undefined,
+ },
+ }),
+ [insightProps, query, lastResponse]
+ )
+ const liveContext = useMemo(() => ({ ...context, insightProps }), [context, insightProps])
+ const previousContext = useMemo(
+ () => ({ ...context, insightProps: previousInsightProps }),
+ [context, previousInsightProps]
+ )
+
+ return (
+ <SearchAndAiLoading
+ className="SearchAndAiQuery"
+ loading={loading || pending}
+ label={!hasCurrentResponse ? 'Loading results' : nextDataLoading ? 'Loading more…' : 'Updating…'}
+ >
+ {header}
+ {responseError && !responseLoading && (
+ <LemonBanner
+ type="error"
+ className="m-3"
+ action={{
+ children: 'Try again',
+ onClick: () => loadData('force_async'),
+ loading: responseLoading,
+ }}
+ >
+ {hasCurrentResponse
+ ? 'Could not update this section. Showing the previous results. Try again to refresh.'
+ : 'Could not load this section. Try again to reload.'}
+ </LemonBanner>
+ )}
+ {initialLoading && <div className={query.kind === NodeKind.DataTableNode ? 'min-h-64' : 'min-h-88'} />}
+
+ {showPreviousResults &&
+ (renderQuery ? (
+ renderQuery(previousInsightProps)
+ ) : (
+ <Query
+ query={query}
+ dataAttr={dataAttr}
+ cachedResults={lastResponse ?? undefined}
+ readOnly
+ context={previousContext}
+ />
+ ))}
+ <div
+ className={
+ initialLoading || !!responseError || showPreviousResults ? 'hidden' : 'min-w-0 flex flex-col flex-1'
+ }
+ >
+ {renderQuery ? (
+ renderQuery(insightProps)
+ ) : (
+ <Query uniqueKey={uniqueKey} query={query} readOnly context={liveContext} dataAttr={dataAttr} />
+ )}
+ </div>
+ {hasCurrentResponse && footer ? (
+ <div className="border-t px-3 py-2 text-xs text-secondary">{footer}</div>
+ ) : null}
+ </SearchAndAiLoading>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiTable.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiTable.tsx
new file mode 100644
index 000000000000..8abac18d66b3
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiTable.tsx
@@ -0,0 +1,94 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+
+import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'
+import { tryDecodeURIComponent } from 'lib/utils/url'
+import { TileId } from 'scenes/web-analytics/common'
+import { createPagePerformanceInsightProps, pagePerformanceLogic } from 'scenes/web-analytics/pagePerformanceLogic'
+
+import { QueryContext, QueryContextColumnTitleComponent } from '~/queries/types'
+
+import { SearchAndAiMetric, SearchAndAiMetricCell } from './SearchAndAiMetricCell'
+import { SearchAndAiQuery } from './SearchAndAiQuery'
+
+const METRIC_COLUMNS: { value: SearchAndAiMetric; label: string }[] = [
+ { value: 'visitors', label: 'Visitors' },
+ { value: 'google_search', label: 'Google search' },
+ { value: 'llm_referrals', label: 'AI referrals' },
+ { value: 'agent_crawls', label: 'AI crawls' },
+ { value: 'conversions', label: 'Conversions' },
+ { value: 'avg_time', label: 'Time on page (P90)' },
+]
+
+const sortableTitle = (label: string, column: string): QueryContextColumnTitleComponent =>
+ function SortableTitle(): JSX.Element {
+ const { orderBy } = useValues(pagePerformanceLogic)
+ const { setOrderBy } = useActions(pagePerformanceLogic)
+ const active = orderBy.column === column
+ return (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ noPadding
+ fullWidth
+ center
+ onClick={() => setOrderBy(column, active && orderBy.direction === 'DESC' ? 'ASC' : 'DESC')}
+ aria-label={`Sort by ${label} ${active && orderBy.direction === 'DESC' ? 'ascending' : 'descending'}`}
+ >
+ <span className="whitespace-normal">{label}</span>
+ {active && (orderBy.direction === 'ASC' ? <IconArrowUp /> : <IconArrowDown />)}
+ </LemonButton>
+ )
+ }
+
+const insightProps = createPagePerformanceInsightProps(TileId.PAGE_PERFORMANCE_TABLE, 'table')
+const context: QueryContext = {
+ insightProps,
+ tableLayout: 'fixed',
+ columns: {
+ breakdown_value: {
+ title: 'Page',
+ width: '28%',
+ render: ({ value }) => {
+ const page = typeof value === 'string' ? tryDecodeURIComponent(value) : '(none)'
+ return (
+ <Tooltip title={page}>
+ <span className="block truncate font-medium">{page}</span>
+ </Tooltip>
+ )
+ },
+ },
+ ...Object.fromEntries(
+ METRIC_COLUMNS.map(({ value, label }) => [
+ value,
+ {
+ renderTitle: sortableTitle(label, value),
+ render: ({ record }: { record: unknown }) => (
+ <SearchAndAiMetricCell metric={value} record={record} />
+ ),
+ align: 'center',
+ },
+ ])
+ ),
+ },
+}
+
+export function SearchAndAiTable(): JSX.Element {
+ const { pageTableQuery, pageTableInput, candidatesLoading, footerText } = useValues(pagePerformanceLogic)
+
+ return (
+ <div className="min-w-0">
+ <SearchAndAiQuery
+ uniqueKey="page-performance-table"
+ pending={candidatesLoading}
+ resultsKey={pageTableInput}
+ query={pageTableQuery}
+ insightProps={insightProps}
+ context={context}
+ footer={footerText}
+ dataAttr="page-performance-table"
+ />
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/SearchAndAiTrendHeader.tsx b/products/web_analytics/frontend/searchAndAi/SearchAndAiTrendHeader.tsx
new file mode 100644
index 000000000000..913a57b946a3
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/SearchAndAiTrendHeader.tsx
@@ -0,0 +1,24 @@
+import { useActions, useValues } from 'kea'
+
+import { IntervalFilterStandalone } from 'lib/components/IntervalFilter'
+import { PagePerformanceCardHeader } from 'scenes/web-analytics/PagePerformanceCardHeader'
+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
+
+export function SearchAndAiTrendHeader({ title }: { title: string }): JSX.Element {
+ const {
+ dateFilter: { interval },
+ } = useValues(webAnalyticsLogic)
+ const { setDateInterval } = useActions(webAnalyticsLogic)
+
+ return (
+ <PagePerformanceCardHeader
+ title={title}
+ actions={
+ <div className="flex items-center gap-2">
+ <span className="text-secondary">Group by</span>
+ <IntervalFilterStandalone interval={interval} onIntervalChange={setDateInterval} />
+ </div>
+ }
+ />
+ )
+}
diff --git a/products/web_analytics/frontend/searchAndAi/searchAndAiQueryLogic.ts b/products/web_analytics/frontend/searchAndAi/searchAndAiQueryLogic.ts
new file mode 100644
index 000000000000..6b11a4b0d619
--- /dev/null
+++ b/products/web_analytics/frontend/searchAndAi/searchAndAiQueryLogic.ts
@@ -0,0 +1,102 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+ selectors,
+} from 'kea'
+
+import {
+ DataNodeLogicProps,
+ dataNodeLogic,
+ dataNodeLogicType,
+ dataNodeLogicActions,
+} from '~/queries/nodes/DataNode/dataNodeLogic'
+
+export interface SearchAndAiQueryLogicProps {
+ dataNodeLogicProps: DataNodeLogicProps
+ resultsKey?: string
+}
+
+export interface searchAndAiQueryLogicValues {
+ response: dataNodeLogicType['values']['response']
+ responseLoading: boolean
+ dataQuery: dataNodeLogicType['values']['query']
+ responseInput: string | null
+ resultsKey: string | null
+ lastResponse: dataNodeLogicType['values']['response']
+ queryInput: string
+ hasCurrentResponse: boolean
+}
+
+export interface searchAndAiQueryLogicActions {
+ setResultsKey: (resultsKey: string | null) => { resultsKey: string | null }
+ loadDataSuccess: dataNodeLogicActions['loadDataSuccess']
+ loadNextDataSuccess: dataNodeLogicActions['loadNextDataSuccess']
+ rememberResponse: (
+ response: dataNodeLogicType['values']['response'],
+ input: string
+ ) => { response: dataNodeLogicType['values']['response']; input: string }
+}
+
+export type searchAndAiQueryLogicType = MakeLogicType<
+ searchAndAiQueryLogicValues,
+ searchAndAiQueryLogicActions,
+ SearchAndAiQueryLogicProps
+>
+
+export const searchAndAiQueryLogic: LogicWrapper<searchAndAiQueryLogicType> = kea<searchAndAiQueryLogicType>([
+ props({} as SearchAndAiQueryLogicProps),
+ key(({ dataNodeLogicProps }) => dataNodeLogicProps.key),
+ path((key) => ['products', 'web_analytics', 'searchAndAiQueryLogic', key]),
+ connect(({ dataNodeLogicProps }: SearchAndAiQueryLogicProps) => ({
+ values: [dataNodeLogic(dataNodeLogicProps), ['response', 'responseLoading', 'query as dataQuery']],
+ actions: [dataNodeLogic(dataNodeLogicProps), ['loadDataSuccess', 'loadNextDataSuccess']],
+ })),
+ actions({
+ setResultsKey: (resultsKey: string | null) => ({ resultsKey }),
+ rememberResponse: (response: dataNodeLogicType['values']['response'], input: string) => ({ response, input }),
+ }),
+ reducers(({ props }) => ({
+ resultsKey: [props.resultsKey ?? null, { setResultsKey: (_, { resultsKey }) => resultsKey }],
+ responseInput: [null as string | null, { rememberResponse: (_, { input }) => input }],
+ lastResponse: [
+ null as dataNodeLogicType['values']['response'],
+ {
+ rememberResponse: (_, { response }) => response,
+ },
+ ],
+ })),
+ propsChanged(({ props, actions }, oldProps) => {
+ if (props.resultsKey !== oldProps.resultsKey) {
+ actions.setResultsKey(props.resultsKey ?? null)
+ }
+ }),
+ selectors({
+ queryInput: [
+ (s) => [s.dataQuery, s.resultsKey],
+ (query, resultsKey): string => resultsKey ?? JSON.stringify(query),
+ ],
+ hasCurrentResponse: [
+ (s) => [s.queryInput, s.responseInput, s.lastResponse],
+ (queryInput, responseInput, response): boolean => !!response && queryInput === responseInput,
+ ],
+ }),
+ listeners(({ values, actions }) => ({
+ loadDataSuccess: ({ response }) => actions.rememberResponse(response ?? null, values.queryInput),
+ loadNextDataSuccess: ({ response }) => actions.rememberResponse(response ?? null, values.queryInput),
+ })),
+ afterMount(({ values, actions }) => {
+ if (values.response && !values.responseLoading) {
+ actions.rememberResponse(values.response, values.queryInput)
+ }
+ }),
+])