:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(heatmaps): explain empty heatmaps and show where the data is (#103148)
Jordan Mryyan36948ed026c0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3e444081624f..39650810766f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8796,6 +8796,14 @@ snapshots:hash: v1.k794b7964.37cf7e1adca49250d4f897857db29d76a66dc7cbb760544ef25f61bc6130b3b7.TF_emc4uFiR_iOQdgadWVFwc-SBVaHUQ9beOf8dPyV0scenes-app-heatmap--blocked-preview-narrow--light:hash: v1.k794b7964.2a26b4a7919f380c0652a40336fe0f6c081591c723a175fd9c6e27fb871a5af7.aENTH12b6uQfQpI_sKhhhrS4c0qSPPlY61EmZEdj7Uo+ scenes-app-heatmap--empty-with-data-at-another-width--dark:+ hash: v1.k794b7964.ceb0ee9e077303c6859f2d5ef31cb974b2db546fe3ae736b40c025cdd9dd5ce1.IvEDL1NkmIslYJ8V5j6XsEK9k1P5ORPA-e0SlDcmIKk+ scenes-app-heatmap--empty-with-data-at-another-width--light:+ hash: v1.k794b7964.773927ab6dee60e47a84f30de223effb52dc3f57f7f7153d24807fcee0c92d1d.i0y3P_e1EoOCI3hd8nynrNVGRFMcCdJTNusJPiOzyew+ scenes-app-heatmap--empty-with-similar-urls--dark:+ hash: v1.k794b7964.8b492692a483806a22e9fa2c676490faf557a7245134dddd868fec57bc0af21f.GB2J4ik1aoCgKvh5KH573sYMBv1bGxGmuzYpKnyAIrQ+ scenes-app-heatmap--empty-with-similar-urls--light:+ hash: v1.k794b7964.cef018c7859bdc01e51614500656027d816a6db8b48dff269951b2d4e9caab5e.g2wPXw79i47pOxKOsUWC_kyeEqw-QyLkC_0g5Iy6sFsscenes-app-heatmap--generating--dark:hash: v1.k794b7964.9d4260c0f995e7dab1dce843dea2bb4d65cde7985de37c3d9c22bc1076e99222.0K0DVWC3ZQ2Azz6yFsqNOS-6TDOAzN1irTWpegrFNksscenes-app-heatmap--generating--light:@@ -8881,7 +8889,7 @@ snapshots:scenes-app-heatmap-new--unauthorized-iframe--light:hash: v1.k794b7964.8e355023754bf9c2c1dc31cbadba79e6b524ad9a66528c649ab150f7eaf0cc05.yqUC0NlgolBVjXQsucJcRfdlu5npQvynKZSy7oAnd_8scenes-app-heatmap-recording--recording-mode-with-clickmap--dark:- hash: v1.k794b7964.5391a9fc4891c9c7ae154895493807ff0e569a5a1d7bdef43ca0f48b878a59cc.JaAh4Zz4E8c0ompabfRmWhcN-VsLNhZd3607c4RPJAw+ hash: v1.k794b7964.690a738ccf7c2d51783f90674de9f2d820c1425f7bad5ac08ef5b3d05c050c77.aNuqccZzEnE0mSzQaTa_fC4qBWKrgD95UTP6SJ8q7rEscenes-app-heatmap-recording--recording-mode-with-clickmap--light:hash: v1.k794b7964.b971c6a8c3c44007c4b2de5797ac84541c34cef1ec16e0b6d760908b4d804302.DIupEQcozzEHDmS1urKBQx7LPhToY6N0FGgL2osOcUwscenes-app-heatmaps-saved--list--dark:diff --git a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsxindex a5065f1b26ed..057d316ba715 100644--- a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx+++ b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx@@ -16,6 +16,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { Popover } from 'lib/lemon-ui/Popover'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'+import { percentage } from 'lib/utils/numbers'import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'@@ -23,6 +24,10 @@ import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'import { AnyPropertyFilter, CohortPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'+import { HEATMAP_PRESET_WIDTHS } from './heatmapCoverage'+import { heatmapCoverageLogic } from './heatmapCoverageLogic'+import { HeatmapEmptyState } from './HeatmapEmptyState'+const cohortIdsToPropertyFilters = (ids: number[]): AnyPropertyFilter[] =>ids.map((id) => ({type: PropertyFilterType.Cohort,@@ -39,38 +44,20 @@ const propertyFiltersToCohortIds = (filters: AnyPropertyFilter[]): number[] =>export function ViewportChooser({ lockedWidth }: { lockedWidth?: number }): JSX.Element {const { widthOverride } = useValues(heatmapDataLogic({ context: 'in-app' }))+ const { widthShares } = useValues(heatmapCoverageLogic)const { setWindowWidthOverride } = useActions(heatmapDataLogic({ context: 'in-app' }))- const options = [- {- value: 320,- icon: <IconPhone />,- },- {- value: 375,- icon: <IconPhone />,- },- {- value: 425,- icon: <IconPhone />,- },- {- value: 768,- icon: <IconTabletPortrait />,- },- {- value: 1024,- icon: <IconTabletLandscape />,- },- {- value: 1440,- icon: <IconLaptop />,- },- {- value: 1920,- icon: <IconLaptop />,- },- ]+ const iconForWidth = (width: number): JSX.Element =>+ width < 768 ? (+ <IconPhone />+ ) : width < 1024 ? (+ <IconTabletPortrait />+ ) : width < 1440 ? (+ <IconTabletLandscape />+ ) : (+ <IconLaptop />+ )+ const options = HEATMAP_PRESET_WIDTHS.map((value) => ({ value, icon: iconForWidth(value) }))const allOptions = lockedWidth ? [{ value: lockedWidth, icon: <IconLaptop /> }] : [...options]if (!lockedWidth && widthOverride && !options.some((option) => option.value === widthOverride)) {@@ -95,6 +82,9 @@ export function ViewportChooser({ lockedWidth }: { lockedWidth?: number }): JSX.<div className="flex items-center gap-1">{icon}<div className="text-xs">{value} px</div>+ {widthShares?.[value] !== undefined ? (+ <div className="text-xs text-muted">{percentage(widthShares[value], 0)}</div>+ ) : null}</div>),}))}@@ -288,11 +278,7 @@ export function FilterPanel({<ViewportChooser lockedWidth={lockedWidth} /></div>{heatmapEmpty && !rawHeatmapLoading && !previewUnavailable ? (- <p className="text-sm text-muted mt-2 mb-0">- {lockedWidth- ? 'No interactions found at this screen width. Try a different date range, or adjust your filters in Heatmap settings.'- : 'No interactions found at this screen width. Try another screen width, a different date range, or adjust your filters in Heatmap settings.'}- </p>+ <HeatmapEmptyState lockedWidth={lockedWidth} />) : null}</div>)diff --git a/products/web_analytics/frontend/heatmaps/components/HeatmapEmptyState.tsx b/products/web_analytics/frontend/heatmaps/components/HeatmapEmptyState.tsxnew file mode 100644index 000000000000..434d3455c923--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/components/HeatmapEmptyState.tsx@@ -0,0 +1,148 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, Link, Spinner } from '@posthog/lemon-ui'++import { HEATMAP_TYPES, heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'+import type { HeatmapKind } from 'lib/components/heatmaps/types'+import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import type { HeatmapEmptyDiagnosis } from './heatmapCoverage'+import { heatmapCoverageLogic } from './heatmapCoverageLogic'++const interactionNoun = (type: HeatmapKind): string => HEATMAP_TYPES[type].label.toLowerCase()++function DiagnosisMessage({+ diagnosis,+ noun,+ width,+ canMatchPage,+}: {+ diagnosis: HeatmapEmptyDiagnosis+ noun: string+ width: number+ canMatchPage: boolean+}): JSX.Element {+ const { applySuggestion } = useActions(heatmapCoverageLogic)+ const { rawHeatmapLoading } = useValues(heatmapDataLogic({ context: 'in-app' }))++ const suggestionButton = (label: string, dataAttr: string, url?: string): JSX.Element => (+ <LemonButton+ type="secondary"+ size="xsmall"+ loading={rawHeatmapLoading}+ onClick={() => applySuggestion(url)}+ data-attr={dataAttr}+ >+ {label}+ </LemonButton>+ )++ switch (diagnosis.reason) {+ case 'capture_off':+ return (+ <span>+ Heatmap capture is turned off for this project, so there is no data to show.{' '}+ <Link to={urls.settings('environment-heatmaps')}>Turn it on in settings</Link>.+ </span>+ )+ case 'other_widths':+ return (+ <div className="flex flex-wrap items-center gap-2">+ <span>+ No {noun} at {width}px. {percentage(diagnosis.share, 0)} of this page's {noun} are at about{' '}+ {diagnosis.width}px.+ </span>+ {suggestionButton(`Show ${diagnosis.width}px`, 'heatmap-empty-show-width')}+ </div>+ )+ case 'other_types':+ return (+ <div className="flex flex-wrap items-center gap-2">+ <span>+ No {noun} for this page, but it has {humanFriendlyLargeNumber(diagnosis.count)}{' '}+ {interactionNoun(diagnosis.type)}.+ </span>+ {suggestionButton(`Show ${interactionNoun(diagnosis.type)}`, 'heatmap-empty-show-type')}+ </div>+ )+ case 'other_dates':+ return (+ <span>+ No data for this page in the selected dates. It has {humanFriendlyLargeNumber(diagnosis.count)}{' '}+ interactions in the last 90 days, so try a longer date range.+ </span>+ )+ case 'other_query_strings':+ return (+ <div className="flex flex-wrap items-center gap-2">+ <span>+ No data for this exact URL. {humanFriendlyLargeNumber(diagnosis.count)} interactions match this+ page with a different query string.+ {canMatchPage ? '' : ' Add * to the end of the heatmap data URL to include them.'}+ </span>+ {canMatchPage ? suggestionButton('Match this page', 'heatmap-empty-match-page') : null}+ </div>+ )+ case 'similar_urls':+ return (+ <div className="flex flex-col gap-1">+ <span>No data for this URL. These similar URLs have data:</span>+ <div className="flex flex-wrap gap-1">+ {diagnosis.urls.map(({ url }) => (+ <span key={url} className="max-w-full truncate">+ {suggestionButton(url, 'heatmap-empty-similar-url', url)}+ </span>+ ))}+ </div>+ </div>+ )+ case 'other_filters':+ return (+ <span>+ This page has {noun} at {width}px, but none match your filters. Try removing the test account,+ cohort or event filters.+ </span>+ )+ case 'no_data':+ return (+ <span>+ No heatmap data for this URL in the last 90 days. Check that the URL matches what your visitors see+ and that heatmap capture runs on this page.+ </span>+ )+ }+}++export function HeatmapEmptyState({ lockedWidth }: { lockedWidth?: number }): JSX.Element {+ const { emptyDiagnosis, emptyDiagnosisLoading, hasValidReplayIframeData, recordingUrlMatchMode } =+ useValues(heatmapCoverageLogic)+ const { heatmapFilters, analysisWidth } = useValues(heatmapDataLogic({ context: 'in-app' }))++ if (emptyDiagnosisLoading) {+ return (+ <p className="text-sm text-muted mt-2 mb-0 flex items-center gap-1">+ <Spinner /> No interactions found. Checking where this page's data is.+ </p>+ )+ }+ if (!emptyDiagnosis) {+ return (+ <p className="text-sm text-muted mt-2 mb-0">+ {lockedWidth+ ? 'No interactions found at this screen width. Try a different date range, or adjust your filters in Heatmap settings.'+ : 'No interactions found at this screen width. Try another screen width, a different date range, or adjust your filters in Heatmap settings.'}+ </p>+ )+ }+ return (+ <LemonBanner type="info" className="mt-2">+ <DiagnosisMessage+ diagnosis={emptyDiagnosis}+ noun={interactionNoun(heatmapFilters.type ?? 'click')}+ width={analysisWidth}+ canMatchPage={hasValidReplayIframeData && recordingUrlMatchMode !== 'page'}+ />+ </LemonBanner>+ )+}diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapCoverage.test.ts b/products/web_analytics/frontend/heatmaps/components/heatmapCoverage.test.tsnew file mode 100644index 000000000000..4530da1c0b9f--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/components/heatmapCoverage.test.ts@@ -0,0 +1,80 @@+import type { HeatmapFilters } from 'lib/components/heatmaps/types'++import { HeatmapCoverageRow, HeatmapUrlDiagnosis, diagnoseEmptyHeatmap } from './heatmapCoverage'++const FILTERS: HeatmapFilters = { enabled: true, type: 'click', viewportAccuracy: 0.9 }+const NO_URL_DATA: HeatmapUrlDiagnosis = { sameUrlAnyDateCount: 0, pageAnyQueryCount: 0, similarUrls: [] }++describe('heatmapCoverage', () => {+ it.each<{+ name: string+ rows: HeatmapCoverageRow[]+ captureEnabled?: boolean+ urlDiagnosis?: HeatmapUrlDiagnosis | null+ expected: Record<string, unknown>+ }>([+ {+ name: 'points at the busiest preset when the data sits at a narrower width',+ rows: [+ { type: 'click', width: 384, count: 60 },+ { type: 'click', width: 400, count: 30 },+ { type: 'click', width: 1920, count: 10 },+ ],+ expected: { reason: 'other_widths', width: 375, share: 0.9 },+ },+ {+ name: 'blames the other filters when the selected width has data',+ rows: [{ type: 'click', width: 1000, count: 5 }],+ expected: { reason: 'other_filters' },+ },+ {+ name: 'suggests the interaction type that has data',+ rows: [+ { type: 'mousemove', width: 400, count: 40 },+ { type: 'rageclick', width: 400, count: 2 },+ ],+ expected: { reason: 'other_types', type: 'mousemove', count: 40 },+ },+ {+ name: 'suggests a longer date range before anything about the URL',+ rows: [],+ urlDiagnosis: { sameUrlAnyDateCount: 12, pageAnyQueryCount: 500, similarUrls: [] },+ expected: { reason: 'other_dates', count: 12 },+ },+ {+ name: 'finds the page under other query strings',+ rows: [],+ urlDiagnosis: { sameUrlAnyDateCount: 0, pageAnyQueryCount: 500, similarUrls: [] },+ expected: { reason: 'other_query_strings', count: 500 },+ },+ {+ name: 'lists similar URLs when the page itself has nothing',+ rows: [],+ urlDiagnosis: { ...NO_URL_DATA, similarUrls: [{ url: 'https://example.com/pricing/teams', count: 9 }] },+ expected: { reason: 'similar_urls', urls: [{ url: 'https://example.com/pricing/teams', count: 9 }] },+ },+ {+ name: 'reports no data when nothing matches anywhere',+ rows: [],+ urlDiagnosis: NO_URL_DATA,+ expected: { reason: 'no_data' },+ },+ {+ name: 'reports capture being off ahead of every other reason',+ rows: [{ type: 'click', width: 384, count: 60 }],+ captureEnabled: false,+ expected: { reason: 'capture_off' },+ },+ ])('$name', ({ rows, captureEnabled = true, urlDiagnosis = null, expected }) => {+ expect(+ diagnoseEmptyHeatmap({+ captureEnabled,+ rows,+ type: 'click',+ heatmapFilters: FILTERS,+ analysisWidth: 1024,+ urlDiagnosis,+ })+ ).toEqual(expected)+ })+})diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapCoverage.ts b/products/web_analytics/frontend/heatmaps/components/heatmapCoverage.tsnew file mode 100644index 000000000000..a5a7a2385eff--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/components/heatmapCoverage.ts@@ -0,0 +1,97 @@+import type { HeatmapFilters, HeatmapKind } from 'lib/components/heatmaps/types'+import { calculateViewportRange } from 'lib/components/IframedToolbarBrowser/utils'++export const HEATMAP_PRESET_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920]++export interface HeatmapCoverageRow {+ type: HeatmapKind+ width: number+ count: number+}++export interface HeatmapUrlDiagnosis {+ sameUrlAnyDateCount: number+ pageAnyQueryCount: number+ similarUrls: { url: string; count: number }[]+}++export type HeatmapEmptyDiagnosis =+ | { reason: 'capture_off' }+ | { reason: 'other_widths'; width: number; share: number }+ | { reason: 'other_types'; type: HeatmapKind; count: number }+ | { reason: 'other_dates'; count: number }+ | { reason: 'other_query_strings'; count: number }+ | { reason: 'similar_urls'; urls: { url: string; count: number }[] }+ | { reason: 'other_filters' }+ | { reason: 'no_data' }++export const computeWidthShares = (+ rows: HeatmapCoverageRow[],+ type: HeatmapKind,+ heatmapFilters: HeatmapFilters,+ widths: number[]+): Record<number, number> => {+ const typeRows = rows.filter((row) => row.type === type)+ const total = typeRows.reduce((sum, row) => sum + row.count, 0)+ const shares: Record<number, number> = {}+ for (const width of widths) {+ const { min, max } = calculateViewportRange(heatmapFilters, width)+ const inBand = typeRows.reduce((sum, row) => (row.width >= min && row.width <= max ? sum + row.count : sum), 0)+ shares[width] = total > 0 ? inBand / total : 0+ }+ return shares+}++export const diagnoseEmptyHeatmap = ({+ captureEnabled,+ rows,+ type,+ heatmapFilters,+ analysisWidth,+ urlDiagnosis,+}: {+ captureEnabled: boolean+ rows: HeatmapCoverageRow[]+ type: HeatmapKind+ heatmapFilters: HeatmapFilters+ analysisWidth: number+ urlDiagnosis: HeatmapUrlDiagnosis | null+}): HeatmapEmptyDiagnosis => {+ if (!captureEnabled) {+ return { reason: 'capture_off' }+ }+ const widths = Array.from(new Set([...HEATMAP_PRESET_WIDTHS, analysisWidth]))+ const shares = computeWidthShares(rows, type, heatmapFilters, widths)+ if ((shares[analysisWidth] ?? 0) > 0) {+ return { reason: 'other_filters' }+ }+ const [bestWidth, bestShare] = HEATMAP_PRESET_WIDTHS.map((width): [number, number] => [width, shares[width]]).sort(+ (a, b) => b[1] - a[1]+ )[0]+ if (bestShare > 0) {+ return { reason: 'other_widths', width: bestWidth, share: bestShare }+ }+ const countsByType = new Map<HeatmapKind, number>()+ for (const row of rows) {+ if (row.type !== type) {+ countsByType.set(row.type, (countsByType.get(row.type) ?? 0) + row.count)+ }+ }+ const [otherType, otherCount] = Array.from(countsByType.entries()).sort((a, b) => b[1] - a[1])[0] ?? [null, 0]+ if (otherType && otherCount > 0) {+ return { reason: 'other_types', type: otherType, count: otherCount }+ }+ if (!urlDiagnosis) {+ return { reason: 'no_data' }+ }+ if (urlDiagnosis.sameUrlAnyDateCount > 0) {+ return { reason: 'other_dates', count: urlDiagnosis.sameUrlAnyDateCount }+ }+ if (urlDiagnosis.pageAnyQueryCount > 0) {+ return { reason: 'other_query_strings', count: urlDiagnosis.pageAnyQueryCount }+ }+ if (urlDiagnosis.similarUrls.length > 0) {+ return { reason: 'similar_urls', urls: urlDiagnosis.similarUrls }+ }+ return { reason: 'no_data' }+}diff --git a/products/web_analytics/frontend/heatmaps/components/heatmapCoverageLogic.ts b/products/web_analytics/frontend/heatmaps/components/heatmapCoverageLogic.tsnew file mode 100644index 000000000000..ca1e3cee6356--- /dev/null+++ b/products/web_analytics/frontend/heatmaps/components/heatmapCoverageLogic.ts@@ -0,0 +1,524 @@+import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import api from 'lib/api'+import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'+import { hasWildcard, heatmapPageUrl, heatmapUrlPatternToRegex } from 'lib/components/heatmaps/heatmapUrlMatch'+import type { HeatmapKind } from 'lib/components/heatmaps/types'+import { teamLogic } from 'scenes/teamLogic'++import { hogql } from '~/queries/utils'++import type { HrefMatchType } from '../../../../../frontend/src/lib/components/heatmaps/heatmapDataLogic'+import type { HeatmapUrlMatchMode } from '../../../../../frontend/src/lib/components/heatmaps/heatmapUrlMatch'+import type { CommonFilters, HeatmapFilters } from '../../../../../frontend/src/lib/components/heatmaps/types'+import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'+import type { ReplayIframeData } from '../replayIframeData'+import {+ HEATMAP_PRESET_WIDTHS,+ HeatmapCoverageRow,+ HeatmapEmptyDiagnosis,+ HeatmapUrlDiagnosis,+ computeWidthShares,+ diagnoseEmptyHeatmap,+} from './heatmapCoverage'+import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'++const QUERY_TAGS = { scene: 'Heatmaps', productKey: 'heatmaps' } as const++const urlPredicate = (href: string, matchType: 'exact' | 'pattern'): string =>+ matchType === 'pattern'+ ? hogql`match(current_url, ${heatmapUrlPatternToRegex(href)})`+ : hogql`trimRight(current_url, '/') = trimRight(${href}, '/')`++const relatedUrlPredicate = (sourceUrl: string, page: string | null): string => {+ if (hasWildcard(sourceUrl)) {+ return hogql`startsWith(current_url, ${sourceUrl.split('*')[0]})`+ }+ if (!page) {+ return hogql`startsWith(current_url, ${sourceUrl})`+ }+ return hogql`(current_url = ${page} OR startsWith(current_url, ${`${page}/`}) OR startsWith(current_url, ${`${page}?`}) OR startsWith(current_url, ${`${page}#`}))`+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface heatmapCoverageLogicValues {+ analysisWidth: number // heatmapDataLogic+ commonFilters: CommonFilters // heatmapDataLogic+ heatmapEmpty: boolean // heatmapDataLogic+ heatmapFilters: HeatmapFilters // heatmapDataLogic+ href: string | null // heatmapDataLogic+ hrefMatchType: HrefMatchType // heatmapDataLogic+ dataUrl: string | null // heatmapsBrowserLogic+ hasValidReplayIframeData: boolean // heatmapsBrowserLogic+ recordingUrlMatchMode: HeatmapUrlMatchMode // heatmapsBrowserLogic+ replayIframeData: ReplayIframeData | null // heatmapsBrowserLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null+ coverageIsCurrent: boolean+ coverageKey: string | null+ coverageLoading: boolean+ emptyDiagnosis: HeatmapEmptyDiagnosis | null+ emptyDiagnosisLoading: boolean+ needsUrlDiagnosis: boolean+ sourceUrl: string | null+ urlDiagnosis:+ | (HeatmapUrlDiagnosis & {+ key: string+ })+ | null+ urlDiagnosisKey: string | null+ urlDiagnosisLoading: boolean+ widthShares: Record<number, number> | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface heatmapCoverageLogicActions {+ loadHeatmapSuccess: (+ rawHeatmap: null | import('~/toolbar/types').HeatmapResponseType,+ payload?:+ | {+ value: true+ }+ | undefined+ ) => {+ payload?: {+ value: true+ }+ rawHeatmap: null | import('~/toolbar/types').HeatmapResponseType+ } // heatmapDataLogic+ patchHeatmapFilters: (filters: Partial<HeatmapFilters>) => {+ filters: Partial<HeatmapFilters>+ } // heatmapDataLogic+ setWindowWidthOverride: (widthOverride: number | null) => {+ widthOverride: number | null+ } // heatmapDataLogic+ setDataUrl: (url: string | null) => {+ url: string | null+ } // heatmapsBrowserLogic+ setRecordingUrlMatchMode: (mode: HeatmapUrlMatchMode) => {+ mode: HeatmapUrlMatchMode+ } // heatmapsBrowserLogic+ setReplayIframeDataURL: (url: string | null) => {+ url: string | null+ } // heatmapsBrowserLogic+ applySuggestion: (url?: string) => {+ url: string | undefined+ }+ loadCoverage: (_: any) => any+ loadCoverageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCoverageSuccess: (+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ payload?: any+ ) => {+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null+ payload?: any+ }+ loadUrlDiagnosis: (_: any) => any+ loadUrlDiagnosisFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadUrlDiagnosisSuccess: (+ urlDiagnosis:+ | (HeatmapUrlDiagnosis & {+ key: string+ })+ | null,+ payload?: any+ ) => {+ urlDiagnosis:+ | (HeatmapUrlDiagnosis & {+ key: string+ })+ | null+ payload?: any+ }+ reportEmptyDiagnosis: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface heatmapCoverageLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ sourceUrl: (+ hasValidReplayIframeData: boolean,+ replayIframeData: ReplayIframeData | null,+ dataUrl: string | null+ ) => string | null+ coverageKey: (href: string | null, hrefMatchType: HrefMatchType, commonFilters: CommonFilters) => string | null+ urlDiagnosisKey: (href: string | null, hrefMatchType: HrefMatchType, sourceUrl: string | null) => string | null+ coverageIsCurrent: (+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageKey: string | null+ ) => boolean+ widthShares: (+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageIsCurrent: boolean,+ heatmapFilters: HeatmapFilters+ ) => Record<number, number> | null+ needsUrlDiagnosis: (+ heatmapEmpty: boolean,+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageIsCurrent: boolean+ ) => boolean+ emptyDiagnosisLoading: (+ heatmapEmpty: boolean,+ coverageLoading: boolean,+ needsUrlDiagnosis: boolean,+ urlDiagnosisLoading: boolean+ ) => boolean+ emptyDiagnosis: (+ heatmapEmpty: boolean,+ emptyDiagnosisLoading: boolean,+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageIsCurrent: boolean,+ needsUrlDiagnosis: boolean,+ urlDiagnosis:+ | (HeatmapUrlDiagnosis & {+ key: string+ })+ | null,+ urlDiagnosisKey: string | null,+ heatmapFilters: HeatmapFilters,+ analysisWidth: number,+ currentTeam: TeamPublicType | TeamType | null+ ) => HeatmapEmptyDiagnosis | null+ }+}++export type heatmapCoverageLogicType = MakeLogicType<+ heatmapCoverageLogicValues,+ heatmapCoverageLogicActions,+ Record<string, any>,+ heatmapCoverageLogicMeta+>++export const heatmapCoverageLogic = kea<heatmapCoverageLogicType>([+ path(['products', 'web_analytics', 'frontend', 'heatmaps', 'components', 'heatmapCoverageLogic']),+ connect(() => ({+ values: [+ heatmapDataLogic({ context: 'in-app' }),+ ['href', 'hrefMatchType', 'commonFilters', 'heatmapFilters', 'analysisWidth', 'heatmapEmpty'],+ heatmapsBrowserLogic,+ ['hasValidReplayIframeData', 'recordingUrlMatchMode', 'replayIframeData', 'dataUrl'],+ teamLogic,+ ['currentTeam'],+ ],+ actions: [+ heatmapDataLogic({ context: 'in-app' }),+ ['loadHeatmapSuccess', 'setWindowWidthOverride', 'patchHeatmapFilters'],+ heatmapsBrowserLogic,+ ['setRecordingUrlMatchMode', 'setReplayIframeDataURL', 'setDataUrl'],+ ],+ })),+ actions({+ applySuggestion: (url?: string) => ({ url }),+ reportEmptyDiagnosis: true,+ }),+ loaders(({ values }) => ({+ coverage: [+ null as { key: string; rows: HeatmapCoverageRow[] } | null,+ {+ loadCoverage: async (_, breakpoint) => {+ const { href, hrefMatchType, commonFilters, coverageKey } = values+ if (!href?.trim() || !coverageKey) {+ return null+ }+ if (values.coverage?.key === coverageKey) {+ return values.coverage+ }+ await breakpoint(300)+ const query = hogql`+ SELECT type, toInt(viewport_width * scale_factor) AS width, count() AS count+ FROM heatmaps+ WHERE ${hogql.raw(urlPredicate(href, hrefMatchType))} AND {filters(timestamp AS timestamp)}+ GROUP BY type, width+ ORDER BY count DESC+ LIMIT 2000`+ const response = await api.queryHogQL(query, QUERY_TAGS, {+ queryParams: {+ filters: {+ dateRange: {+ date_from: commonFilters.date_from ?? '-7d',+ date_to: commonFilters.date_to ?? null,+ },+ },+ },+ })+ breakpoint()+ return {+ key: coverageKey,+ rows: (response.results ?? []).map(([type, width, count]: [HeatmapKind, number, number]) => ({+ type,+ width,+ count,+ })),+ }+ },+ },+ ],+ urlDiagnosis: [+ null as (HeatmapUrlDiagnosis & { key: string }) | null,+ {+ loadUrlDiagnosis: async (_, breakpoint) => {+ const { href, hrefMatchType, sourceUrl, urlDiagnosisKey } = values+ if (!href?.trim() || !sourceUrl || !urlDiagnosisKey) {+ return null+ }+ if (values.urlDiagnosis?.key === urlDiagnosisKey) {+ return values.urlDiagnosis+ }+ await breakpoint(300)+ const page = heatmapPageUrl(sourceUrl)+ const pageCondition = page+ ? hogql`trimRight(cutQueryStringAndFragment(current_url), '/') = ${page}`+ : hogql`0`+ const sameUrl = urlPredicate(href, hrefMatchType)+ const inScope = hogql`timestamp >= now() - INTERVAL 90 DAY AND ${hogql.raw(relatedUrlPredicate(sourceUrl, page))}`+ const totalsQuery = hogql`+ SELECT countIf(${hogql.raw(sameUrl)}), countIf(${hogql.raw(pageCondition)})+ FROM heatmaps+ WHERE ${hogql.raw(inScope)}`+ const similarUrlsQuery = hogql`+ SELECT current_url, count() AS count+ FROM heatmaps+ WHERE ${hogql.raw(inScope)} AND NOT (${hogql.raw(sameUrl)}) AND NOT (${hogql.raw(pageCondition)})+ GROUP BY current_url+ ORDER BY count DESC+ LIMIT 5`+ const [totals, similar] = await Promise.all([+ api.queryHogQL(totalsQuery, QUERY_TAGS),+ api.queryHogQL(similarUrlsQuery, QUERY_TAGS),+ ])+ breakpoint()+ const [sameUrlAnyDateCount, pageAnyQueryCount]: [number, number] = totals.results?.[0] ?? [0, 0]+ return {+ key: urlDiagnosisKey,+ sameUrlAnyDateCount,+ pageAnyQueryCount,+ similarUrls: (similar.results ?? []).map(([url, count]: [string, number]) => ({ url, count })),+ }+ },+ },+ ],+ })),+ selectors({+ sourceUrl: [+ (s) => [s.hasValidReplayIframeData, s.replayIframeData, s.dataUrl],+ (+ hasValidReplayIframeData: boolean,+ replayIframeData: ReplayIframeData | null,+ dataUrl: string | null+ ): string | null => (hasValidReplayIframeData ? replayIframeData?.url : dataUrl) ?? null,+ ],+ coverageKey: [+ (s) => [s.href, s.hrefMatchType, s.commonFilters],+ (href: string | null, hrefMatchType: HrefMatchType, commonFilters: CommonFilters): string | null =>+ href?.trim()+ ? JSON.stringify([+ href,+ hrefMatchType,+ commonFilters.date_from ?? null,+ commonFilters.date_to ?? null,+ ])+ : null,+ ],+ urlDiagnosisKey: [+ (s) => [s.href, s.hrefMatchType, s.sourceUrl],+ (href: string | null, hrefMatchType: HrefMatchType, sourceUrl: string | null): string | null =>+ href?.trim() && sourceUrl ? JSON.stringify([href, hrefMatchType, sourceUrl]) : null,+ ],+ coverageIsCurrent: [+ (s) => [s.coverage, s.coverageKey],+ (+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageKey: string | null+ ): boolean => !!coverage && coverage.key === coverageKey,+ ],+ widthShares: [+ (s) => [s.coverage, s.coverageIsCurrent, s.heatmapFilters],+ (+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageIsCurrent: boolean,+ heatmapFilters: HeatmapFilters+ ): Record<number, number> | null =>+ coverage &&+ coverageIsCurrent &&+ coverage.rows.some((row) => row.type === (heatmapFilters.type ?? 'click'))+ ? computeWidthShares(+ coverage.rows,+ heatmapFilters.type ?? 'click',+ heatmapFilters,+ HEATMAP_PRESET_WIDTHS+ )+ : null,+ ],+ needsUrlDiagnosis: [+ (s) => [s.heatmapEmpty, s.coverage, s.coverageIsCurrent],+ (+ heatmapEmpty: boolean,+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageIsCurrent: boolean+ ): boolean => heatmapEmpty && coverageIsCurrent && coverage?.rows.length === 0,+ ],+ emptyDiagnosisLoading: [+ (s) => [s.heatmapEmpty, s.coverageLoading, s.needsUrlDiagnosis, s.urlDiagnosisLoading],+ (+ heatmapEmpty: boolean,+ coverageLoading: boolean,+ needsUrlDiagnosis: boolean,+ urlDiagnosisLoading: boolean+ ): boolean => heatmapEmpty && (coverageLoading || (needsUrlDiagnosis && urlDiagnosisLoading)),+ ],+ emptyDiagnosis: [+ (s) => [+ s.heatmapEmpty,+ s.emptyDiagnosisLoading,+ s.coverage,+ s.coverageIsCurrent,+ s.needsUrlDiagnosis,+ s.urlDiagnosis,+ s.urlDiagnosisKey,+ s.heatmapFilters,+ s.analysisWidth,+ s.currentTeam,+ ],+ (+ heatmapEmpty: boolean,+ emptyDiagnosisLoading: boolean,+ coverage: {+ key: string+ rows: HeatmapCoverageRow[]+ } | null,+ coverageIsCurrent: boolean,+ needsUrlDiagnosis: boolean,+ urlDiagnosis: (HeatmapUrlDiagnosis & { key: string }) | null,+ urlDiagnosisKey: string | null,+ heatmapFilters: HeatmapFilters,+ analysisWidth: number,+ currentTeam: TeamPublicType | TeamType | null+ ): HeatmapEmptyDiagnosis | null => {+ const urlDiagnosisIsCurrent = !!urlDiagnosis && urlDiagnosis.key === urlDiagnosisKey+ if (+ !heatmapEmpty ||+ emptyDiagnosisLoading ||+ !coverage ||+ !coverageIsCurrent ||+ (needsUrlDiagnosis && !urlDiagnosisIsCurrent)+ ) {+ return null+ }+ return diagnoseEmptyHeatmap({+ captureEnabled: currentTeam?.heatmaps_opt_in !== false,+ rows: coverage.rows,+ type: heatmapFilters.type ?? 'click',+ heatmapFilters,+ analysisWidth,+ urlDiagnosis: urlDiagnosisIsCurrent ? urlDiagnosis : null,+ })+ },+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ loadHeatmapSuccess: () => {+ actions.loadCoverage(null)+ },+ loadCoverageSuccess: () => {+ if (values.needsUrlDiagnosis) {+ actions.loadUrlDiagnosis(null)+ return+ }+ actions.reportEmptyDiagnosis()+ },+ loadUrlDiagnosisSuccess: () => {+ actions.reportEmptyDiagnosis()+ },+ reportEmptyDiagnosis: () => {+ const diagnosis = values.emptyDiagnosis+ if (!diagnosis) {+ return+ }+ const reportKey = JSON.stringify([+ values.coverageKey,+ diagnosis.reason,+ values.analysisWidth,+ values.heatmapFilters.type,+ ])+ if (cache.lastReportKey === reportKey) {+ return+ }+ cache.lastReportKey = reportKey+ posthog.capture('in-app heatmap empty result', {+ empty_reason: diagnosis.reason,+ match_type: values.hrefMatchType,+ url_match_mode: values.hasValidReplayIframeData ? values.recordingUrlMatchMode : null,+ analysis_width: values.analysisWidth,+ heatmap_type: values.heatmapFilters.type ?? 'click',+ has_query_string: !!values.sourceUrl?.includes('?'),+ from_recording: values.hasValidReplayIframeData,+ })+ },+ applySuggestion: ({ url }) => {+ const diagnosis = values.emptyDiagnosis+ if (!diagnosis) {+ return+ }+ posthog.capture('in-app heatmap empty suggestion applied', { suggestion: diagnosis.reason })+ if (diagnosis.reason === 'other_widths') {+ actions.setWindowWidthOverride(diagnosis.width)+ } else if (diagnosis.reason === 'other_types') {+ actions.patchHeatmapFilters({ type: diagnosis.type })+ } else if (diagnosis.reason === 'other_query_strings' && values.hasValidReplayIframeData) {+ actions.setRecordingUrlMatchMode('page')+ } else if (diagnosis.reason === 'similar_urls' && url) {+ if (values.hasValidReplayIframeData) {+ actions.setReplayIframeDataURL(url)+ } else {+ actions.setDataUrl(url)+ }+ }+ },+ })),+])diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsxindex 0c20113ea76e..65c1696b2452 100644--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx@@ -330,3 +330,55 @@ export const PageSettingsDialogNarrow: Story = {</Narrow>),}++const emptyHeatmapMocks = (queryResults: (query: string) => unknown[]): Mocks => ({+ get: {+ '/api/projects/:team_id/saved/hm_iframe/': () => [200, makeIframeSaved()],+ '/api/projects/:team_id/heatmaps/': () => [200, { results: [], count: 0, next: null, previous: null }],+ },+ post: {+ '/api/projects/:team_id/query/:query_kind/': async (info) => {+ const body = JSON.stringify(await info.request.clone().json())+ return [200, { results: queryResults(body) }]+ },+ },+})++const emptyHeatmapParameters = (waitForSelector: string): Story['parameters'] => ({+ ...IframeExample.parameters,+ testOptions: { ...IframeExample.parameters?.testOptions, waitForSelector },+})++export const EmptyWithDataAtAnotherWidth: Story = {+ parameters: emptyHeatmapParameters('[data-attr="heatmap-empty-show-width"]'),+ decorators: [+ mswDecorator(+ emptyHeatmapMocks((query) =>+ query.includes('GROUP BY type, width')+ ? [+ ['click', 390, 60],+ ['click', 400, 30],+ ]+ : []+ )+ ),+ ],+}++export const EmptyWithSimilarUrls: Story = {+ parameters: emptyHeatmapParameters('[data-attr="heatmap-empty-similar-url"]'),+ decorators: [+ mswDecorator(+ emptyHeatmapMocks((query) =>+ query.includes('GROUP BY current_url')+ ? [+ [`${window.location.origin}/mock-page.html?utm_source=newsletter`, 42],+ [`${window.location.origin}/mock-page.html/pricing`, 9],+ ]+ : query.includes('countIf')+ ? [[0, 0]]+ : []+ )+ ),+ ],+}