Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(heatmaps): overlay a clickmap in recording-mode heatmaps (#68191)

Paul D'Ambrae42c67f1f8c0
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 495a352f20ec..7ed42428312c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -207,6 +207,7 @@ export const FEATURE_FLAGS = {
EXPERIMENTAL_DASHBOARD_ITEM_RENDERING: 'experimental-dashboard-item-rendering', // owner: @thmsobrmlr #team-product-analytics
GATEWAY_PERSONAL_API_KEY: 'gateway-personal-api-key', // owner: #team-platform-features
HEATMAPS_COHORT_FILTER: 'heatmaps-cohort-filter', // owner: #team-web-analytics
+ HEATMAPS_RECORDING_CLICKMAP: 'heatmaps-recording-clickmap', // owner: #team-web-analytics
IMPROVED_COOKIELESS_MODE: 'improved-cookieless-mode', // owner: #team-web-analytics
LINEAGE_DEPENDENCY_VIEW: 'lineage-dependency-view', // owner: #team-data-modeling
MEMBERS_CAN_USE_PERSONAL_API_KEYS: 'members-can-use-personal-api-keys', // owner: @yasen-posthog #team-platform-features
diff --git a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx
index 4b04495002ec..cf815612d0c0 100644
--- a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx
+++ b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useEffect, useState } from 'react'
import { IconGear, IconLaptop, IconPhone, IconTabletLandscape, IconTabletPortrait } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
@@ -121,9 +121,13 @@ export function ViewportChooser(): JSX.Element {
export function FilterPanel({
captureMethod,
onCaptureMethodChange,
+ clickmapEnabled,
+ onClickmapEnabledChange,
}: {
captureMethod?: HeatmapType
onCaptureMethodChange?: (type: HeatmapType) => void
+ clickmapEnabled?: boolean
+ onClickmapEnabledChange?: (enabled: boolean) => void
}): JSX.Element {
const [isSettingsOpen, setIsSettingsOpen] = useState(false)
const {
@@ -219,6 +223,19 @@ export function FilterPanel({
/>
</SectionSetting>
)}
+ {clickmapEnabled !== undefined && onClickmapEnabledChange && (
+ <SectionSetting
+ title="Clickmap"
+ info="Overlay click counts on the elements users actually clicked"
+ >
+ <LemonSwitch
+ checked={clickmapEnabled}
+ onChange={onClickmapEnabledChange}
+ label="Show clickmap"
+ size="small"
+ />
+ </SectionSetting>
+ )}
<SectionSetting
title="Internal and test users filter"
info="Filter out internal and test users"
diff --git a/frontend/src/scenes/heatmaps/components/FixedReplayHeatmapBrowser.tsx b/frontend/src/scenes/heatmaps/components/FixedReplayHeatmapBrowser.tsx
index 330a8bcada16..2406a6c29388 100644
--- a/frontend/src/scenes/heatmaps/components/FixedReplayHeatmapBrowser.tsx
+++ b/frontend/src/scenes/heatmaps/components/FixedReplayHeatmapBrowser.tsx
@@ -3,6 +3,7 @@ import React from 'react'
import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
import { heatmapsBrowserLogic } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
+import { RecordingClickmapOverlay } from 'scenes/heatmaps/components/RecordingClickmapOverlay'
export function FixedReplayHeatmapBrowser({
iframeRef,
@@ -24,6 +25,7 @@ export function FixedReplayHeatmapBrowser({
style={{ width: widthOverride, height: heightOverride }}
>
<HeatmapCanvas positioning="absolute" widthOverride={widthOverride} context="in-app" />
+ <RecordingClickmapOverlay iframeRef={iframeRef} />
<iframe
id="heatmap-iframe"
ref={iframeRef}
@@ -32,7 +34,11 @@ export function FixedReplayHeatmapBrowser({
// eslint-disable-next-line react/forbid-dom-props
style={{ width: widthOverride, height: heightOverride }}
srcDoc={replayIframeData?.html}
- sandbox=""
+ // allow-same-origin lets the app measure the snapshot's elements for the
+ // clickmap overlay. NEVER add allow-scripts: combined with allow-same-origin
+ // that would let recorded customer-page content run script on the app origin.
+ // The app only ever reads geometry from the snapshot, never its content.
+ sandbox="allow-same-origin"
onLoad={onIframeLoad}
allow=""
/>
diff --git a/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx b/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx
index 3247eead306b..d112b3e4f9ac 100644
--- a/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx
+++ b/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx
@@ -3,12 +3,23 @@ import { useActions, useValues } from 'kea'
import { LemonBanner, LemonButton, LemonInput, LemonLabel } from '@posthog/lemon-ui'
import { HeatmapAdvancedSettings } from 'scenes/heatmaps/components/HeatmapAdvancedSettings'
+import { HeatmapRecordingFallback } from 'scenes/heatmaps/components/HeatmapRecordingFallback'
+import { heatmapsBrowserLogic } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
import { HeatmapsInvalidURL } from 'scenes/heatmaps/components/HeatmapsInvalidURL'
import { heatmapLogic } from 'scenes/heatmaps/scenes/heatmap/heatmapLogic'
export function HeatmapHeader(): JSX.Element {
- const { pageUrlDraft, isPageUrlDraftValid, pageUrlDraftIsPattern, loading, screenshotError } =
- useValues(heatmapLogic)
+ const {
+ pageUrlDraft,
+ isPageUrlDraftValid,
+ pageUrlDraftIsPattern,
+ loading,
+ screenshotError,
+ displayUrl,
+ displayUrlIsPattern,
+ type,
+ } = useValues(heatmapLogic)
+ const { iframeBanner } = useValues(heatmapsBrowserLogic)
const { setPageUrlDraft, applyPageUrlDraft, regenerateScreenshot } = useActions(heatmapLogic)
const draftIsEmpty = pageUrlDraft.trim() === ''
@@ -55,8 +66,8 @@ export function HeatmapHeader(): JSX.Element {
)
) : null}
</div>
- {screenshotError && (
- <div>
+ {type === 'screenshot' && screenshotError && (
+ <div className="flex flex-col gap-2">
<LemonBanner
type="error"
action={{
@@ -66,6 +77,15 @@ export function HeatmapHeader(): JSX.Element {
>
{screenshotError}
</LemonBanner>
+ {displayUrl && !displayUrlIsPattern ? <HeatmapRecordingFallback url={displayUrl} /> : null}
+ </div>
+ )}
+ {type === 'iframe' && iframeBanner?.level === 'error' && (
+ <div className="flex flex-col gap-2">
+ <LemonBanner type="error">
+ The page failed to load in an iframe (or is very slow). Some sites block being embedded.
+ </LemonBanner>
+ {displayUrl && !displayUrlIsPattern ? <HeatmapRecordingFallback url={displayUrl} /> : null}
</div>
)}
<HeatmapAdvancedSettings
diff --git a/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx b/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx
index e1c4c923dd19..bf19ad8dbb70 100644
--- a/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx
+++ b/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx
@@ -11,6 +11,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { FilterPanel } from './FilterPanel'
import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'
+import { recordingClickmapLogic } from './recordingClickmapLogic'
function UrlSearchHeader(): JSX.Element {
const logic = heatmapsBrowserLogic()
@@ -47,8 +48,11 @@ export function HeatmapRecording(): JSX.Element {
const logicProps = { ref: iframeRef }
const logic = heatmapsBrowserLogic({ iframeRef })
+ const clickmapLogic = recordingClickmapLogic({ iframeRef })
const { hasValidReplayIframeData } = useValues(logic)
+ const { clickmapEnabled, clickmapAvailable } = useValues(clickmapLogic)
+ const { setClickmapEnabled } = useActions(clickmapLogic)
if (!hasValidReplayIframeData) {
return (
@@ -68,7 +72,10 @@ export function HeatmapRecording(): JSX.Element {
<div className="overflow-hidden w-full min-h-screen">
<UrlSearchHeader />
<LemonDivider className="my-4" />
- <FilterPanel />
+ <FilterPanel
+ clickmapEnabled={clickmapAvailable ? clickmapEnabled : undefined}
+ onClickmapEnabledChange={clickmapAvailable ? setClickmapEnabled : undefined}
+ />
<LemonDivider className="my-4" />
<div className="relative flex flex-1 overflow-hidden min-h-screen">
<FixedReplayHeatmapBrowser iframeRef={iframeRef} />
diff --git a/frontend/src/scenes/heatmaps/components/HeatmapRecordingFallback.tsx b/frontend/src/scenes/heatmaps/components/HeatmapRecordingFallback.tsx
new file mode 100644
index 000000000000..e85958167ec2
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/components/HeatmapRecordingFallback.tsx
@@ -0,0 +1,52 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRewindPlay } from '@posthog/icons'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { colonDelimitedDuration } from 'lib/utils/durations'
+
+import { heatmapRecordingFallbackLogic } from './heatmapRecordingFallbackLogic'
+
+export function HeatmapRecordingFallback({ url }: { url: string }): JSX.Element | null {
+ const logic = heatmapRecordingFallbackLogic({ url })
+ const { matchingRecordings } = useValues(logic)
+ const { openRecording } = useActions(logic)
+
+ if (!matchingRecordings?.length) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="info">
+ <div className="flex flex-col gap-2">
+ <p className="mb-0">
+ We found recent recordings of sessions that visited this page. You can build the heatmap from a
+ recording instead: open one, scrub to the page you want as the background, then choose "View
+ heatmap" in the player.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {matchingRecordings.map((recording) => (
+ <LemonButton
+ key={recording.id}
+ data-attr="heatmap-recording-fallback-open-recording"
+ type="secondary"
+ size="small"
+ icon={<IconRewindPlay />}
+ onClick={() => openRecording(recording.id)}
+ >
+ <span className="flex items-center gap-1">
+ <TZLabel time={recording.start_time} />
+ {recording.recording_duration ? (
+ <span className="text-muted">
+ · {colonDelimitedDuration(recording.recording_duration)}
+ </span>
+ ) : null}
+ </span>
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx b/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx
index 458c56ba9052..651c7604dbbd 100644
--- a/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx
+++ b/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx
@@ -23,6 +23,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { FilterPanel } from './FilterPanel'
import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'
import { IframeHeatmapBrowser } from './IframeHeatmapBrowser'
+import { recordingClickmapLogic } from './recordingClickmapLogic'
function ExportButton({
iframeRef,
@@ -345,8 +346,11 @@ export function HeatmapsBrowser(): JSX.Element {
const logicProps = { ref: iframeRef }
const logic = heatmapsBrowserLogic({ iframeRef })
+ const clickmapLogic = recordingClickmapLogic({ iframeRef })
const { displayUrl, isBrowserUrlAuthorized, hasValidReplayIframeData, isBrowserUrlValid } = useValues(logic)
+ const { clickmapEnabled, clickmapAvailable } = useValues(clickmapLogic)
+ const { setClickmapEnabled } = useActions(clickmapLogic)
return (
<BindLogic logic={heatmapsBrowserLogic} props={logicProps}>
@@ -355,7 +359,12 @@ export function HeatmapsBrowser(): JSX.Element {
<div className="w-full">
<UrlSearchHeader iframeRef={iframeRef} />
<LemonDivider className="my-4" />
- <FilterPanel />
+ <FilterPanel
+ clickmapEnabled={hasValidReplayIframeData && clickmapAvailable ? clickmapEnabled : undefined}
+ onClickmapEnabledChange={
+ hasValidReplayIframeData && clickmapAvailable ? setClickmapEnabled : undefined
+ }
+ />
<LemonDivider className="my-4" />
<div className="relative border">
{hasValidReplayIframeData ? (
diff --git a/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsx b/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsx
new file mode 100644
index 000000000000..74cefd2bd992
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsx
@@ -0,0 +1,96 @@
+import { useValues } from 'kea'
+import React, { useEffect, useRef } from 'react'
+
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import { recordingClickmapLogic } from './recordingClickmapLogic'
+
+function useSnapshotScrollTransform(
+ enabled: boolean,
+ iframeRef?: React.MutableRefObject<HTMLIFrameElement | null>
+): React.RefObject<HTMLDivElement> {
+ const innerRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!enabled) {
+ return
+ }
+
+ let rafId: number | undefined
+ let lastX = -1
+ let lastY = -1
+
+ // polling like useScrollSync does, because a scroll listener would need
+ // re-binding every time the srcDoc document is replaced
+ const onFrame = (): void => {
+ let scrollX = 0
+ let scrollY = 0
+ try {
+ const snapshotWindow = iframeRef?.current?.contentWindow
+ scrollX = snapshotWindow?.scrollX ?? 0
+ scrollY = snapshotWindow?.scrollY ?? 0
+ } catch {
+ // the frame navigated cross-origin; keep the overlay where it was
+ }
+ if (scrollX !== lastX || scrollY !== lastY) {
+ lastX = scrollX
+ lastY = scrollY
+ if (innerRef.current) {
+ innerRef.current.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`
+ }
+ }
+ rafId = requestAnimationFrame(onFrame)
+ }
+
+ rafId = requestAnimationFrame(onFrame)
+ return () => {
+ if (rafId !== undefined) {
+ cancelAnimationFrame(rafId)
+ }
+ }
+ }, [enabled, iframeRef])
+
+ return innerRef
+}
+
+export function RecordingClickmapOverlay({
+ iframeRef,
+}: {
+ iframeRef?: React.MutableRefObject<HTMLIFrameElement | null>
+}): JSX.Element | null {
+ const logic = recordingClickmapLogic({ iframeRef })
+ const { clickmapActive, clickmapBoxes, highestClickCount } = useValues(logic)
+ const showClickmap = clickmapActive && clickmapBoxes.length > 0
+ const innerRef = useSnapshotScrollTransform(showClickmap, iframeRef)
+
+ if (!showClickmap) {
+ return null
+ }
+
+ return (
+ <div className="absolute inset-0 overflow-hidden pointer-events-none z-10" data-attr="heatmap-clickmap-overlay">
+ <div ref={innerRef} className="absolute inset-0">
+ {clickmapBoxes.map((box, index) => (
+ <div
+ key={`${box.top}:${box.left}:${index}`}
+ className="absolute rounded-sm border border-danger"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ top: box.top,
+ left: box.left,
+ width: box.width,
+ height: box.height,
+ backgroundColor: `rgba(245, 78, 0, ${
+ 0.1 + 0.4 * (highestClickCount ? box.count / highestClickCount : 0)
+ })`,
+ }}
+ >
+ <div className="absolute -top-2 -left-2 rounded-full bg-danger text-white text-xs px-1 whitespace-nowrap">
+ {humanFriendlyLargeNumber(box.count)}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/heatmaps/components/heatmapRecordingFallbackLogic.test.ts b/frontend/src/scenes/heatmaps/components/heatmapRecordingFallbackLogic.test.ts
new file mode 100644
index 000000000000..5e23bb18377a
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/components/heatmapRecordingFallbackLogic.test.ts
@@ -0,0 +1,20 @@
+import { buildRecordingsQueryForUrl } from './heatmapRecordingFallbackLogic'
+
+describe('heatmapRecordingFallbackLogic', () => {
+ it('searches recordings by pages actually visited during the session, not just session start', () => {
+ const query = buildRecordingsQueryForUrl('https://example.com/pricing')
+ expect(query.properties).toEqual([
+ {
+ type: 'recording',
+ key: 'visited_page',
+ operator: 'icontains',
+ value: ['https://example.com/pricing'],
+ },
+ ])
+ expect(query.order).toBe('start_time')
+ expect(query.order_direction).toBe('DESC')
+ expect(query.kind).toBe('RecordingsQuery')
+ expect(query.limit).toBe(3)
+ expect(query.date_from).toBe('-30d')
+ })
+})
diff --git a/frontend/src/scenes/heatmaps/components/heatmapRecordingFallbackLogic.ts b/frontend/src/scenes/heatmaps/components/heatmapRecordingFallbackLogic.ts
new file mode 100644
index 000000000000..1a4d855cc39e
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/components/heatmapRecordingFallbackLogic.ts
@@ -0,0 +1,75 @@
+import { actions, afterMount, connect, kea, key, listeners, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
+
+import { NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'
+import { PropertyFilterType, PropertyOperator, SessionRecordingType } from '~/types'
+
+import type { heatmapRecordingFallbackLogicType } from './heatmapRecordingFallbackLogicType'
+
+export type HeatmapRecordingFallbackLogicProps = {
+ url: string
+}
+
+const RECORDING_FALLBACK_LOOKBACK = '-30d'
+
+export function buildRecordingsQueryForUrl(url: string): RecordingsQuery {
+ return {
+ kind: NodeKind.RecordingsQuery,
+ order: 'start_time',
+ order_direction: 'DESC',
+ date_from: RECORDING_FALLBACK_LOOKBACK,
+ limit: 3,
+ properties: [
+ {
+ type: PropertyFilterType.Recording,
+ key: 'visited_page',
+ operator: PropertyOperator.IContains,
+ value: [url],
+ },
+ ],
+ }
+}
+
+export const heatmapRecordingFallbackLogic = kea<heatmapRecordingFallbackLogicType>([
+ path(['scenes', 'heatmaps', 'components', 'heatmapRecordingFallbackLogic']),
+ props({} as HeatmapRecordingFallbackLogicProps),
+ key((props) => props.url),
+ connect(() => ({
+ actions: [sessionPlayerModalLogic, ['openSessionPlayer']],
+ })),
+ actions({
+ loadMatchingRecordings: true,
+ openRecording: (recordingId: string) => ({ recordingId }),
+ }),
+ loaders(({ props }) => ({
+ matchingRecordings: [
+ null as SessionRecordingType[] | null,
+ {
+ loadMatchingRecordings: async (_, breakpoint) => {
+ await breakpoint(100)
+ const response = await api.recordings.list(buildRecordingsQueryForUrl(props.url))
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
+ })),
+ listeners(({ actions }) => ({
+ loadMatchingRecordingsSuccess: ({ matchingRecordings }) => {
+ posthog.capture('in-app heatmap recording fallback searched', {
+ matching_recordings: matchingRecordings?.length ?? 0,
+ })
+ },
+ openRecording: ({ recordingId }) => {
+ posthog.capture('in-app heatmap recording fallback recording opened')
+ actions.openSessionPlayer({ id: recordingId })
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadMatchingRecordings()
+ }),
+])
diff --git a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
index c66ee86efe29..47f7da82a6fa 100644
--- a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
+++ b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts
@@ -277,12 +277,17 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
],
}),
- listeners(({ actions, props, values, cache }) => ({
- setDisplayUrl: ({ url }) => {
+ listeners(({ actions, props, values, cache, selectors }) => ({
+ setDisplayUrl: ({ url }, _, __, previousState) => {
// Don't clobber a separately edited data URL when the page URL changes.
if (!values.userTouchedDataUrl) {
actions.setDataUrl(url?.trim() ?? null)
}
+ // the iframe loads displayUrl, so only an actual change produces a load
+ // event; arming on anything else leaves a timer nothing can cancel
+ if (url?.trim().length && url !== selectors.displayUrl(previousState)) {
+ actions.startTrackingLoading()
+ }
},
setReplayIframeData: ({ replayIframeData }) => {
if (replayIframeData && replayIframeData.url) {
@@ -358,8 +363,6 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
setDataUrl: ({ url }) => {
actions.maybeLoadTopUrls()
if (url?.trim().length) {
- actions.startTrackingLoading()
-
let normalizedUrl = url.trim()
const isPattern = isUrlPattern(normalizedUrl)
@@ -379,10 +382,13 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([
cache.disposables.add(() => {
const timerId = setTimeout(() => {
// this timer also runs on scenes that never mount an iframe
- // (screenshot detail, the new-heatmap form), so only capture when one exists
- if (document.getElementById('heatmap-iframe')) {
- posthog.capture('in-app heatmap load failed')
+ // (screenshot detail, the new-heatmap form), where a load-failure
+ // banner would be a false positive
+ if (!document.getElementById('heatmap-iframe')) {
+ actions.stopTrackingLoading()
+ return
}
+ posthog.capture('in-app heatmap load failed')
actions.setIframeBanner({
level: 'error',
message: 'The heatmap failed to load (or is very slow).',
diff --git a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.ts b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.ts
new file mode 100644
index 000000000000..52a38125d424
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.ts
@@ -0,0 +1,135 @@
+import type { ElementStatsApi } from 'products/product_analytics/frontend/generated/api.schemas'
+
+import { buildElementStatsParams, computeClickmapBoxes } from './recordingClickmapLogic'
+
+function statsRow(overrides: Partial<ElementStatsApi>): ElementStatsApi {
+ return {
+ count: 1,
+ hash: null,
+ type: '$autocapture',
+ elements: [{ tag_name: 'button', attr_id: 'cta', nth_child: 1, nth_of_type: 1, attributes: {} }],
+ ...overrides,
+ }
+}
+
+describe('recordingClickmapLogic', () => {
+ describe('buildElementStatsParams', () => {
+ it.each([
+ {
+ name: 'filters stats to the exact page URL',
+ href: 'https://example.com/pricing',
+ isPattern: false,
+ expectedProperty: {
+ key: '$current_url',
+ value: 'https://example.com/pricing',
+ operator: 'exact',
+ type: 'event',
+ },
+ },
+ {
+ name: 'converts * wildcards to an anchored regex',
+ href: 'https://example.com/blog/*',
+ isPattern: true,
+ expectedProperty: {
+ key: '$current_url',
+ value: '^https\\:\\/\\/example\\.com\\/blog\\/.*$',
+ operator: 'regex',
+ type: 'event',
+ },
+ },
+ ])('$name', ({ href, isPattern, expectedProperty }) => {
+ const params = buildElementStatsParams(href, isPattern, { date_from: '-7d' }, ['data-attr'])
+ expect(JSON.parse((params as { properties?: string }).properties ?? '[]')).toEqual([expectedProperty])
+ })
+ })
+
+ describe('computeClickmapBoxes', () => {
+ let snapshotDocument: Document
+
+ beforeEach(() => {
+ snapshotDocument = document.implementation.createHTMLDocument()
+ snapshotDocument.body.innerHTML = `
+ <main>
+ <button id="cta">Sign up</button>
+ <a id="docs-link" href="/docs">Docs</a>
+ </main>
+ `
+ jest.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({
+ top: 10,
+ left: 20,
+ width: 100,
+ height: 40,
+ right: 120,
+ bottom: 50,
+ x: 20,
+ y: 10,
+ toJSON: () => ({}),
+ })
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('aggregates counts from multiple chains resolving to the same element into one box', () => {
+ const boxes = computeClickmapBoxes(
+ [statsRow({ count: 10 }), statsRow({ count: 3, hash: 'other-chain-same-element' })],
+ snapshotDocument,
+ null,
+ ['data-attr']
+ )
+ expect(boxes).toHaveLength(1)
+ expect(boxes[0].count).toBe(13)
+ })
+
+ it('produces one box per matched element, sorted by count descending', () => {
+ const boxes = computeClickmapBoxes(
+ [
+ statsRow({ count: 2 }),
+ statsRow({
+ count: 9,
+ elements: [
+ {
+ tag_name: 'a',
+ attr_id: 'docs-link',
+ href: '/docs',
+ nth_child: 2,
+ nth_of_type: 1,
+ attributes: {},
+ },
+ ],
+ }),
+ ],
+ snapshotDocument,
+ null,
+ ['data-attr']
+ )
+ expect(boxes.map((box) => box.count)).toEqual([9, 2])
+ })
+
+ it('drops chains that match nothing in the snapshot', () => {
+ const boxes = computeClickmapBoxes(
+ [
+ statsRow({
+ count: 5,
+ elements: [{ tag_name: 'select', attr_id: 'not-in-snapshot', attributes: {} }],
+ }),
+ ],
+ snapshotDocument,
+ null,
+ ['data-attr']
+ )
+ expect(boxes).toHaveLength(0)
+ })
+
+ it('offsets boxes by the snapshot scroll position', () => {
+ const boxes = computeClickmapBoxes(
+ [statsRow({ count: 1 })],
+ snapshotDocument,
+ { scrollX: 5, scrollY: 200 },
+ ['data-attr']
+ )
+ expect(boxes[0]).toMatchObject({ top: 210, left: 25 })
+ })
+ })
+})
diff --git a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts
new file mode 100644
index 000000000000..b3c985a04bd5
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts
@@ -0,0 +1,276 @@
+import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+import { collectAllElementsDeep } from 'query-selector-shadow-dom'
+import { RefObject } from 'react'
+
+import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { buildDOMIndex, matchEventToElementUsingIndex } from '~/toolbar/elements/domElementIndex'
+import { escapeUnescapedRegex } from '~/toolbar/elements/heatmapToolbarMenuLogic'
+import { ElementsEventType } from '~/toolbar/types'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { elementsStatsRetrieve } from 'products/product_analytics/frontend/generated/api'
+import type {
+ ElementStatsResponseApi,
+ ElementsStatsRetrieveParams,
+} from 'products/product_analytics/frontend/generated/api.schemas'
+
+import { heatmapsBrowserLogic, isUrlPattern } from './heatmapsBrowserLogic'
+import type { recordingClickmapLogicType } from './recordingClickmapLogicType'
+
+export interface ClickmapBox {
+ top: number
+ left: number
+ width: number
+ height: number
+ count: number
+}
+
+export type RecordingClickmapLogicProps = {
+ iframeRef?: RefObject<HTMLIFrameElement | null>
+}
+
+const CLICKMAP_STATS_LIMIT = 500
+
+function currentUrlProperty(href: string, isPattern: boolean): Record<string, unknown> {
+ return isPattern
+ ? {
+ key: '$current_url',
+ value: `^${href.split('*').map(escapeUnescapedRegex).join('.*')}$`,
+ operator: PropertyOperator.Regex,
+ type: PropertyFilterType.Event,
+ }
+ : {
+ key: '$current_url',
+ value: href,
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ }
+}
+
+export function buildElementStatsParams(
+ href: string,
+ isPattern: boolean,
+ commonFilters: {
+ date_from?: string | null
+ date_to?: string | null
+ filter_test_accounts?: boolean
+ cohort_ids?: number[]
+ },
+ dataAttributes: string[]
+): ElementsStatsRetrieveParams {
+ const properties: Record<string, unknown>[] = [currentUrlProperty(href, isPattern)]
+ for (const cohortId of commonFilters.cohort_ids ?? []) {
+ properties.push({
+ type: PropertyFilterType.Cohort,
+ key: 'id',
+ value: cohortId,
+ operator: PropertyOperator.In,
+ })
+ }
+ // properties and filter_test_accounts are parsed by the endpoint but missing from its
+ // generated schema, hence the widening cast - see the stats action in posthog/api/element.py
+ return {
+ properties: JSON.stringify(properties),
+ date_from: commonFilters.date_from,
+ date_to: commonFilters.date_to,
+ filter_test_accounts: commonFilters.filter_test_accounts,
+ include: ['$autocapture'],
+ limit: CLICKMAP_STATS_LIMIT,
+ data_attributes: dataAttributes.join(','),
+ } as unknown as ElementsStatsRetrieveParams
+}
+
+export function computeClickmapBoxes(
+ statsRows: ElementStatsResponseApi['results'],
+ snapshotDocument: Document,
+ snapshotWindow: { scrollX: number; scrollY: number } | null,
+ dataAttributes: string[]
+): ClickmapBox[] {
+ const pageElements = collectAllElementsDeep('*', snapshotDocument) as HTMLElement[]
+ const domIndex = buildDOMIndex(pageElements)
+ const countsByElement = new Map<HTMLElement, number>()
+ for (const row of statsRows) {
+ const match = matchEventToElementUsingIndex(
+ row as unknown as ElementsEventType,
+ dataAttributes,
+ false,
+ domIndex
+ )
+ if (match) {
+ countsByElement.set(match.element, (countsByElement.get(match.element) ?? 0) + row.count)
+ }
+ }
+
+ const scrollX = snapshotWindow?.scrollX ?? 0
+ const scrollY = snapshotWindow?.scrollY ?? 0
+ const boxes: ClickmapBox[] = []
+ countsByElement.forEach((count, element) => {
+ const rect = element.getBoundingClientRect()
+ if (rect.width > 0 && rect.height > 0) {
+ boxes.push({
+ top: rect.top + scrollY,
+ left: rect.left + scrollX,
+ width: rect.width,
+ height: rect.height,
+ count,
+ })
+ }
+ })
+ return boxes.sort((a, b) => b.count - a.count)
+}
+
+export const recordingClickmapLogic = kea<recordingClickmapLogicType>([
+ path(['scenes', 'heatmaps', 'components', 'recordingClickmapLogic']),
+ props({} as RecordingClickmapLogicProps),
+ connect(() => ({
+ values: [
+ heatmapDataLogic({ context: 'in-app' }),
+ ['commonFilters'],
+ heatmapsBrowserLogic,
+ ['replayIframeData'],
+ teamLogic,
+ ['currentTeam'],
+ projectLogic,
+ ['currentProjectId'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
+ actions: [
+ heatmapsBrowserLogic,
+ ['onIframeLoad', 'setReplayIframeData', 'setReplayIframeDataURL'],
+ heatmapDataLogic({ context: 'in-app' }),
+ ['setCommonFilters', 'setWindowWidthOverride'],
+ ],
+ })),
+ actions({
+ setClickmapEnabled: (enabled: boolean) => ({ enabled }),
+ loadElementStats: true,
+ maybeLoadElementStats: true,
+ recomputeClickmap: true,
+ setClickmapBoxes: (boxes: ClickmapBox[]) => ({ boxes }),
+ }),
+ reducers({
+ clickmapEnabled: [
+ true,
+ {
+ setClickmapEnabled: (_, { enabled }) => enabled,
+ },
+ ],
+ clickmapBoxes: [
+ [] as ClickmapBox[],
+ {
+ setClickmapBoxes: (_, { boxes }) => boxes,
+ setClickmapEnabled: (state, { enabled }) => (enabled ? state : []),
+ setReplayIframeData: () => [],
+ setReplayIframeDataURL: () => [],
+ },
+ ],
+ // the loader keeps stale stats across recording changes otherwise, and
+ // onIframeLoad would repaint the old recording's counts onto the new snapshot
+ elementStats: {
+ setReplayIframeData: () => null,
+ setReplayIframeDataURL: () => null,
+ },
+ }),
+ loaders(({ values }) => ({
+ elementStats: [
+ null as ElementStatsResponseApi | null,
+ {
+ loadElementStats: async (_, breakpoint) => {
+ await breakpoint(150)
+ // heatmapDataLogic's href gets clobbered to '' by onIframeLoad in this scene,
+ // so the replay payload's URL is the stable source of truth here
+ const url = values.replayIframeData?.url?.trim()
+ if (!url) {
+ return null
+ }
+ const params = buildElementStatsParams(
+ url,
+ isUrlPattern(url),
+ values.commonFilters,
+ values.wantedDataAttributes
+ )
+ const response = await elementsStatsRetrieve(String(values.currentProjectId), params)
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ })),
+ selectors({
+ clickmapAvailable: [
+ (s) => [s.featureFlags],
+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.HEATMAPS_RECORDING_CLICKMAP],
+ ],
+ clickmapActive: [
+ (s) => [s.clickmapAvailable, s.clickmapEnabled],
+ (clickmapAvailable, clickmapEnabled): boolean => clickmapAvailable && clickmapEnabled,
+ ],
+ wantedDataAttributes: [
+ (s) => [s.currentTeam],
+ (currentTeam): string[] => Array.from(new Set(['data-attr', ...(currentTeam?.data_attributes ?? [])])),
+ ],
+ highestClickCount: [
+ (s) => [s.clickmapBoxes],
+ (clickmapBoxes) => clickmapBoxes.reduce((max, box) => Math.max(max, box.count), 0),
+ ],
+ }),
+ listeners(({ actions, values, props }) => ({
+ setClickmapEnabled: ({ enabled }) => {
+ posthog.capture('in-app heatmap clickmap toggled', { enabled })
+ if (enabled) {
+ actions.maybeLoadElementStats()
+ }
+ },
+ maybeLoadElementStats: () => {
+ if (values.clickmapActive && values.replayIframeData?.url?.trim()) {
+ actions.loadElementStats()
+ }
+ },
+ setReplayIframeData: () => actions.maybeLoadElementStats(),
+ setReplayIframeDataURL: () => actions.maybeLoadElementStats(),
+ setCommonFilters: () => actions.maybeLoadElementStats(),
+ setWindowWidthOverride: () => actions.recomputeClickmap(),
+ onIframeLoad: () => {
+ if (values.elementStats) {
+ actions.recomputeClickmap()
+ } else {
+ actions.maybeLoadElementStats()
+ }
+ },
+ loadElementStatsSuccess: () => actions.recomputeClickmap(),
+ recomputeClickmap: async (_, breakpoint) => {
+ if (!values.clickmapActive || !values.replayIframeData?.url?.trim()) {
+ return
+ }
+ await breakpoint(50)
+ const iframe = props.iframeRef?.current
+ const snapshotDocument = iframe?.contentDocument
+ const statsRows = values.elementStats?.results
+ if (!snapshotDocument?.body || !statsRows?.length) {
+ actions.setClickmapBoxes([])
+ return
+ }
+
+ const boxes = computeClickmapBoxes(
+ statsRows,
+ snapshotDocument,
+ iframe?.contentWindow ?? null,
+ values.wantedDataAttributes
+ )
+ posthog.capture('in-app heatmap clickmap rendered', {
+ stats_rows: statsRows.length,
+ matched_elements: boxes.length,
+ has_more: !!values.elementStats?.next,
+ })
+ actions.setClickmapBoxes(boxes)
+ },
+ })),
+])
diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapRecordingScene.stories.tsx b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapRecordingScene.stories.tsx
new file mode 100644
index 000000000000..9a3d64e33cce
--- /dev/null
+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapRecordingScene.stories.tsx
@@ -0,0 +1,137 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+const STORAGE_KEY = 'ph_replay_fixed_heatmap_storybook'
+
+const snapshotHtml = `<!DOCTYPE html><html><head><style>
+* { margin: 0; box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; }
+body { width: 1024px; background: #fff; }
+header { display: flex; gap: 24px; padding: 18px 32px; background: #1d1f27; }
+header a { color: #f7f7f7; font-size: 14px; text-decoration: none; }
+main { padding: 48px 32px; }
+h1 { font-size: 28px; margin-bottom: 12px; color: #111; }
+p { color: #4b4b52; margin-bottom: 28px; max-width: 480px; font-size: 15px; }
+#signup-cta { background: #f54e00; color: #fff; border: none; padding: 14px 28px; font-size: 16px; border-radius: 6px; }
+#docs-link { display: inline-block; margin-left: 20px; color: #f54e00; font-size: 16px; }
+</style></head><body>
+<header><a id="nav-home" href="/">Home</a><a id="nav-pricing" href="/pricing">Pricing</a><a id="nav-docs" href="/docs">Docs</a></header>
+<main><h1>Simple, usage-based pricing</h1>
+<p>Pay only for what you use. Every product has a generous free tier, and you can set billing limits so there are no surprises.</p>
+<button id="signup-cta">Get started - free</button>
+<a id="docs-link" href="/docs">Read the docs</a></main>
+</body></html>`
+
+const replayIframeData = {
+ html: snapshotHtml,
+ width: 1024,
+ height: 640,
+ startDateTime: '2024-01-01T00:00:00Z',
+ url: 'https://example.com/pricing',
+}
+
+const elementStatsResults = [
+ {
+ count: 128,
+ hash: 'story-cta',
+ type: '$autocapture',
+ elements: [
+ {
+ text: 'Get started - free',
+ tag_name: 'button',
+ attr_id: 'signup-cta',
+ nth_child: 3,
+ nth_of_type: 1,
+ attributes: {},
+ },
+ { tag_name: 'main', nth_child: 2, nth_of_type: 1, attributes: {} },
+ ],
+ },
+ {
+ count: 46,
+ hash: 'story-docs',
+ type: '$autocapture',
+ elements: [
+ {
+ text: 'Read the docs',
+ tag_name: 'a',
+ attr_id: 'docs-link',
+ href: '/docs',
+ nth_child: 4,
+ nth_of_type: 1,
+ attributes: {},
+ },
+ { tag_name: 'main', nth_child: 2, nth_of_type: 1, attributes: {} },
+ ],
+ },
+ {
+ count: 19,
+ hash: 'story-nav',
+ type: '$autocapture',
+ elements: [
+ {
+ text: 'Pricing',
+ tag_name: 'a',
+ attr_id: 'nav-pricing',
+ href: '/pricing',
+ nth_child: 2,
+ nth_of_type: 2,
+ attributes: {},
+ },
+ { tag_name: 'header', nth_child: 1, nth_of_type: 1, attributes: {} },
+ ],
+ },
+]
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Heatmap Recording',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ pageUrl: urls.heatmapRecording(`iframeStorage=${STORAGE_KEY}`),
+ featureFlags: [FEATURE_FLAGS.HEATMAPS_RECORDING_CLICKMAP],
+ testOptions: {
+ waitForSelector: '[data-attr="heatmap-clickmap-overlay"]',
+ waitForLoadersToDisappear: true,
+ },
+ },
+ decorators: [
+ (Story) => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(replayIframeData))
+ return <Story />
+ },
+ mswDecorator({
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ get: {
+ '/api/projects/:team_id/elements/stats/': () => [200, { results: elementStatsResults, next: null }],
+ '/api/projects/:team_id/heatmaps/': () => [
+ 200,
+ {
+ results: [
+ { pointer_relative_x: 0.12, pointer_target_fixed: false, pointer_y: 210, count: 90 },
+ { pointer_relative_x: 0.14, pointer_target_fixed: false, pointer_y: 214, count: 42 },
+ { pointer_relative_x: 0.3, pointer_target_fixed: false, pointer_y: 212, count: 24 },
+ { pointer_relative_x: 0.1, pointer_target_fixed: false, pointer_y: 28, count: 16 },
+ { pointer_relative_x: 0.18, pointer_target_fixed: false, pointer_y: 28, count: 11 },
+ ],
+ count: 5,
+ next: null,
+ previous: null,
+ },
+ ],
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+export const RecordingModeWithClickmap: Story = {}
diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts
index ff32116b4901..717bc49914a2 100644
--- a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts
+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts
@@ -127,6 +127,9 @@ export const heatmapLogic = kea<heatmapLogicType>([
listeners(({ actions, values, props }) => ({
changeCaptureMethod: async ({ type }) => {
actions.setType(type)
+ if (type !== 'screenshot') {
+ actions.setScreenshotError(null)
+ }
if (!values.heatmapId) {
return
}
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
index 9c75a3fb57c2..9521d5924639 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
@@ -42,6 +42,7 @@ import { openBillingPopupModal } from 'scenes/billing/BillingPopup'
import { ReplayIframeData } from 'scenes/heatmaps/components/heatmapsBrowserLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { playerCommentModel } from 'scenes/session-recordings/player/commenting/playerCommentModel'
+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
import {
isWithinIngestionGracePeriod,
SessionRecordingDataCoordinatorLogicProps,
@@ -2373,6 +2374,9 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
url: values.currentURL,
}
localStorage.setItem(key, JSON.stringify(data))
+ // the player may be open in the global modal (e.g. from the heatmap recording
+ // fallback); close it or the heatmap scene renders hidden beneath it
+ sessionPlayerModalLogic.findMounted()?.actions.closeSessionPlayer()
router.actions.push(urls.heatmapRecording(`iframeStorage=${key}`))
},