: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): show element details on clickmap hover (#68422)
Paul D'Ambrad9c6fc347fb5
diff --git a/frontend/src/lib/components/heatmaps/ElementClickStats.tsx b/frontend/src/lib/components/heatmaps/ElementClickStats.tsxnew file mode 100644index 000000000000..165a25bb19d7--- /dev/null+++ b/frontend/src/lib/components/heatmaps/ElementClickStats.tsx@@ -0,0 +1,64 @@+import { IconCalendar } from '@posthog/icons'++type ElementStatisticProps = {+ title: string+ value: string | number+ prefix?: string+ suffix?: string+}++function ElementStatistic({ title, value, prefix, suffix }: ElementStatisticProps): JSX.Element {+ return (+ <div className="flex flex-col">+ <div>{title}</div>+ <div className="text-2xl">+ {prefix}+ {value}+ {suffix}+ </div>+ </div>+ )+}++interface ElementClickStatsProps {+ count: number+ totalCount: number+ rank?: number+ clickCount?: number+ rageclickCount?: number+ deadclickCount?: number+ dateRange?: string | JSX.Element+}++export function ElementClickStats({+ count,+ totalCount,+ rank,+ clickCount,+ rageclickCount,+ deadclickCount,+ dateRange,+}: ElementClickStatsProps): JSX.Element {+ return (+ <>+ {dateRange ? (+ <p>+ <IconCalendar /> <u>{dateRange}</u>+ </p>+ ) : null}+ <div className="grid grid-cols-[auto_1fr] gap-4">+ <ElementStatistic+ title="Clicks"+ value={count}+ suffix={`/${totalCount} (${+ totalCount === 0 ? '?' : Math.round((count / totalCount) * 10000) / 100+ }%)`}+ />+ {rank !== undefined ? <ElementStatistic title="Ranking" prefix="#" value={rank} /> : null}+ {clickCount !== undefined ? <ElementStatistic title="Autocapture clicks" value={clickCount} /> : null}+ {rageclickCount !== undefined ? <ElementStatistic title="Rageclicks" value={rageclickCount} /> : null}+ {deadclickCount !== undefined ? <ElementStatistic title="Deadclicks" value={deadclickCount} /> : null}+ </div>+ </>+ )+}diff --git a/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx b/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsxindex e1018d538e36..5b3cb1a1c800 100644--- a/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx+++ b/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx@@ -35,13 +35,15 @@ function HeatmapMouseInfo({onHasValue?: (hasValue: boolean) => void}): JSX.Element | null {const shiftPressed = useShiftKeyPressed()- const { heatmapTooltipLabel, rawHeatmapLoading } = useValues(heatmapDataLogic({ context }))+ const { heatmapTooltipLabel, rawHeatmapLoading, heatmapTooltipSuppressed } = useValues(+ heatmapDataLogic({ context })+ )const containerMousePosition = useMousePosition(containerRef?.current)const viewportMousePosition = useMousePosition()const value = heatmapJsRef.current?.getValueAt(containerMousePosition)- const hasValue = !!(containerMousePosition && (value || shiftPressed))+ const hasValue = !!(containerMousePosition && (value || shiftPressed)) && !heatmapTooltipSuppresseduseEffect(() => {onHasValue?.(hasValue)diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.tsindex 321f5858019d..f6e5944e8ba2 100644--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts@@ -109,6 +109,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([patchHeatmapFilters: (filters: Partial<HeatmapFilters>) => ({ filters }),setHeatmapFixedPositionMode: (mode: HeatmapFixedPositionMode) => ({ mode }),setHeatmapColorPalette: (palette: string | null) => ({ palette }),+ setHeatmapTooltipSuppressed: (suppressed: boolean) => ({ suppressed }),setHref: (href: string) => ({ href }),setHrefMatchType: (matchType: HrefMatchType) => ({ matchType }),setWindowWidthOverride: (widthOverride: number | null) => ({ widthOverride }),@@ -161,6 +162,13 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([setHeatmapColorPalette: (_, { palette }) => palette,},],+ // e.g. while the clickmap overlay shows its own element tooltip+ heatmapTooltipSuppressed: [+ false,+ {+ setHeatmapTooltipSuppressed: (_, { suppressed }) => suppressed,+ },+ ],href: [null as string | null,{diff --git a/frontend/src/scenes/heatmaps/components/ClickmapSettings.tsx b/frontend/src/scenes/heatmaps/components/ClickmapSettings.tsxnew file mode 100644index 000000000000..9b5747c52823--- /dev/null+++ b/frontend/src/scenes/heatmaps/components/ClickmapSettings.tsx@@ -0,0 +1,84 @@+import { useActions, useValues } from 'kea'+import React, { useState } from 'react'++import { IconCursorClick } from '@posthog/icons'+import { LemonButton, LemonSwitch, Spinner, Tooltip } from '@posthog/lemon-ui'++import { Popover } from 'lib/lemon-ui/Popover'+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'++import { recordingClickmapLogic } from './recordingClickmapLogic'++export function ClickmapSettings({+ iframeRef,+}: {+ iframeRef?: React.MutableRefObject<HTMLIFrameElement | null>+}): JSX.Element {+ const [isOpen, setIsOpen] = useState(false)+ const logic = recordingClickmapLogic({ iframeRef })+ const { clickmapEnabled, matchLinksByHref, clickmapBoxes, totalClickCount, elementStatsLoading, elementStats } =+ useValues(logic)+ const { setClickmapEnabled, setMatchLinksByHref } = useActions(logic)++ const elementWord = clickmapBoxes.length === 1 ? 'element' : 'elements'+ const clickWord = totalClickCount === 1 ? 'click' : 'clicks'++ return (+ <Popover+ overlay={+ <div className="p-2 w-80 flex flex-col gap-2">+ <LemonSwitch+ checked={clickmapEnabled}+ onChange={setClickmapEnabled}+ label="Show clickmap"+ size="small"+ fullWidth+ bordered+ />+ <div className="text-xs text-muted">+ Overlay click counts on the elements users actually clicked.+ </div>+ <Tooltip title="Links whose target URL differs per user (e.g. contains IDs) may not match any element in the snapshot.">+ <LemonSwitch+ checked={matchLinksByHref}+ onChange={setMatchLinksByHref}+ label="Match links by their target URL"+ size="small"+ fullWidth+ bordered+ />+ </Tooltip>+ {clickmapEnabled && (+ <div className="text-xs text-muted flex items-center gap-1">+ {elementStatsLoading ? (+ <>+ <Spinner /> Loading...+ </>+ ) : elementStats !== null && clickmapBoxes.length === 0 ? (+ 'No elements matched.'+ ) : elementStats !== null ? (+ <>+ Found: {clickmapBoxes.length} {elementWord} /{' '}+ {humanFriendlyLargeNumber(totalClickCount)} {clickWord}+ </>+ ) : null}+ </div>+ )}+ </div>+ }+ visible={isOpen}+ onClickOutside={() => setIsOpen(false)}+ placement="bottom"+ >+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setIsOpen(!isOpen)}+ icon={<IconCursorClick />}+ data-attr="clickmap-settings"+ >+ Clickmap settings+ </LemonButton>+ </Popover>+ )+}diff --git a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx b/frontend/src/scenes/heatmaps/components/FilterPanel.tsxindex cfb56a16f2df..873d66e0ed8c 100644--- a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx+++ b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx@@ -1,15 +1,8 @@import { useActions, useValues } from 'kea'import { useEffect, useState } from 'react'-import {- IconCursorClick,- IconGear,- IconLaptop,- IconPhone,- IconTabletLandscape,- IconTabletPortrait,-} from '@posthog/icons'-import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'+import { IconGear, IconLaptop, IconPhone, IconTabletLandscape, IconTabletPortrait } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'@@ -128,16 +121,13 @@ export function ViewportChooser(): JSX.Element {export function FilterPanel({captureMethod,onCaptureMethodChange,- clickmapEnabled,- onClickmapEnabledChange,+ clickmapSettings,}: {captureMethod?: HeatmapTypeonCaptureMethodChange?: (type: HeatmapType) => void- clickmapEnabled?: boolean- onClickmapEnabledChange?: (enabled: boolean) => void+ clickmapSettings?: JSX.Element}): JSX.Element {const [isSettingsOpen, setIsSettingsOpen] = useState(false)- const [isClickmapSettingsOpen, setIsClickmapSettingsOpen] = useState(false)const {heatmapFilters,heatmapColorPalette,@@ -251,41 +241,7 @@ export function FilterPanel({</LemonButton></Popover></div>- {clickmapEnabled !== undefined && onClickmapEnabledChange && (- <div className="mt-2 md:mt-0">- <Popover- overlay={- <div className="p-2 w-80 flex flex-col gap-2">- <LemonSwitch- checked={clickmapEnabled}- onChange={onClickmapEnabledChange}- label="Show clickmap"- size="small"- />- <div className="text-xs text-muted">- Overlay click counts on the elements users actually clicked.- </div>- </div>- }- visible={isClickmapSettingsOpen}- onClickOutside={() => {- setIsClickmapSettingsOpen(false)- }}- placement="bottom"- >- <LemonButton- type="secondary"- size="small"- onClick={() => setIsClickmapSettingsOpen(!isClickmapSettingsOpen)}- icon={<IconCursorClick />}- tooltip="Clickmap settings"- data-attr="clickmap-settings"- >- Clickmap settings- </LemonButton>- </Popover>- </div>- )}+ {clickmapSettings ? <div className="mt-2 md:mt-0">{clickmapSettings}</div> : null}<div className="mt-2 md:mt-0"><TestAccountFiltersize="small"diff --git a/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx b/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsxindex bf19ad8dbb70..60d9dc37527c 100644--- a/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx+++ b/frontend/src/scenes/heatmaps/components/HeatmapRecording.tsx@@ -9,6 +9,7 @@ import { HeatmapsWarnings } from 'scenes/heatmaps/components/HeatmapsWarnings'import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { ClickmapSettings } from './ClickmapSettings'import { FilterPanel } from './FilterPanel'import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'import { recordingClickmapLogic } from './recordingClickmapLogic'@@ -51,8 +52,7 @@ export function HeatmapRecording(): JSX.Element {const clickmapLogic = recordingClickmapLogic({ iframeRef })const { hasValidReplayIframeData } = useValues(logic)- const { clickmapEnabled, clickmapAvailable } = useValues(clickmapLogic)- const { setClickmapEnabled } = useActions(clickmapLogic)+ const { clickmapAvailable } = useValues(clickmapLogic)if (!hasValidReplayIframeData) {return (@@ -73,8 +73,7 @@ export function HeatmapRecording(): JSX.Element {<UrlSearchHeader /><LemonDivider className="my-4" /><FilterPanel- clickmapEnabled={clickmapAvailable ? clickmapEnabled : undefined}- onClickmapEnabledChange={clickmapAvailable ? setClickmapEnabled : undefined}+ clickmapSettings={clickmapAvailable ? <ClickmapSettings iframeRef={iframeRef} /> : undefined}/><LemonDivider className="my-4" /><div className="relative flex flex-1 overflow-hidden min-h-screen">diff --git a/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx b/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsxindex 651c7604dbbd..d36d3fa22134 100644--- a/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx+++ b/frontend/src/scenes/heatmaps/components/HeatmapsBrowser.tsx@@ -20,6 +20,7 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { ClickmapSettings } from './ClickmapSettings'import { FilterPanel } from './FilterPanel'import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'import { IframeHeatmapBrowser } from './IframeHeatmapBrowser'@@ -349,8 +350,7 @@ export function HeatmapsBrowser(): JSX.Element {const clickmapLogic = recordingClickmapLogic({ iframeRef })const { displayUrl, isBrowserUrlAuthorized, hasValidReplayIframeData, isBrowserUrlValid } = useValues(logic)- const { clickmapEnabled, clickmapAvailable } = useValues(clickmapLogic)- const { setClickmapEnabled } = useActions(clickmapLogic)+ const { clickmapAvailable } = useValues(clickmapLogic)return (<BindLogic logic={heatmapsBrowserLogic} props={logicProps}>@@ -360,9 +360,10 @@ export function HeatmapsBrowser(): JSX.Element {<UrlSearchHeader iframeRef={iframeRef} /><LemonDivider className="my-4" /><FilterPanel- clickmapEnabled={hasValidReplayIframeData && clickmapAvailable ? clickmapEnabled : undefined}- onClickmapEnabledChange={- hasValidReplayIframeData && clickmapAvailable ? setClickmapEnabled : undefined+ clickmapSettings={+ hasValidReplayIframeData && clickmapAvailable ? (+ <ClickmapSettings iframeRef={iframeRef} />+ ) : undefined}/><LemonDivider className="my-4" />diff --git a/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsx b/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsxindex 74cefd2bd992..b763eb2f400e 100644--- a/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsx+++ b/frontend/src/scenes/heatmaps/components/RecordingClickmapOverlay.tsx@@ -1,9 +1,13 @@-import { useValues } from 'kea'-import React, { useEffect, useRef } from 'react'+import { useActions, useValues } from 'kea'+import React, { useEffect, useMemo, useRef } from 'react'+import { Tooltip } from '@posthog/lemon-ui'++import { ElementClickStats } from 'lib/components/heatmaps/ElementClickStats'+import { Popover } from 'lib/lemon-ui/Popover'import { humanFriendlyLargeNumber } from 'lib/utils/numbers'-import { recordingClickmapLogic } from './recordingClickmapLogic'+import { ClickmapBox, recordingClickmapLogic } from './recordingClickmapLogic'function useSnapshotScrollTransform(enabled: boolean,@@ -53,43 +57,159 @@ function useSnapshotScrollTransform(return innerRef}+function ClickmapBoxInfo({+ box,+ rank,+ totalCount,+}: {+ box: ClickmapBox+ rank: number+ totalCount: number+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1 max-w-100">+ {box.label ? <div className="font-semibold">{box.label}</div> : null}+ <div className="font-mono text-xs text-muted-alt break-all">{box.displaySelector}</div>+ <ElementClickStats+ count={box.count}+ totalCount={totalCount}+ rank={rank}+ clickCount={box.clickCount}+ rageclickCount={box.rageclickCount}+ deadclickCount={box.deadclickCount}+ />+ </div>+ )+}++// pixel-equivalent heights for non-pixel wheel deltaMode values+const WHEEL_LINE_HEIGHT_PX = 20+const WHEEL_PAGE_HEIGHT_PX = 400+export function RecordingClickmapOverlay({iframeRef,}: {iframeRef?: React.MutableRefObject<HTMLIFrameElement | null>}): JSX.Element | null {const logic = recordingClickmapLogic({ iframeRef })- const { clickmapActive, clickmapBoxes, highestClickCount } = useValues(logic)+ const { clickmapActive, clickmapBoxes, highestClickCount, selectedBoxKey, totalClickCount } = useValues(logic)+ const { selectClickmapBox, setHoveredBoxKey } = useActions(logic)const showClickmap = clickmapActive && clickmapBoxes.length > 0const innerRef = useSnapshotScrollTransform(showClickmap, iframeRef)+ const overlayRef = useRef<HTMLDivElement>(null)++ // render smaller boxes on top so high-count nested elements stay reachable+ const renderOrder = useMemo(+ () =>+ clickmapBoxes+ .map((box, i) => ({ box, i }))+ .sort((a, b) => b.box.width * b.box.height - a.box.width * a.box.height),+ [clickmapBoxes]+ )++ useEffect(() => {+ const el = overlayRef.current+ if (!el || !showClickmap) {+ return+ }+ // React attaches wheel as a passive root listener, so synthetic stopPropagation()+ // cannot prevent the native scroll of the outer overflow-auto container, and+ // calling preventDefault() on a passive listener throws. A single non-passive+ // listener on the overlay itself lets us do both: stop the outer scroll and+ // forward scaled deltas into the snapshot iframe underneath.+ // The overlay div is pointer-events-none, but wheel events from the+ // pointer-events-auto boxes bubble through it natively, so this fires.+ const handler = (e: WheelEvent): void => {+ // ctrl+wheel is how browsers dispatch trackpad pinch-zoom; let it through+ if (e.ctrlKey) {+ return+ }+ e.preventDefault()+ const scale = e.deltaMode === 2 ? WHEEL_PAGE_HEIGHT_PX : e.deltaMode === 1 ? WHEEL_LINE_HEIGHT_PX : 1+ try {+ iframeRef?.current?.contentWindow?.scrollBy(e.deltaX * scale, e.deltaY * scale)+ } catch {+ // cross-origin frame; ignore+ }+ }+ el.addEventListener('wheel', handler, { passive: false })+ return () => el.removeEventListener('wheel', handler)+ }, [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={overlayRef}+ 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)}+ {renderOrder.map(({ box, i: originalIndex }) => {+ const key = String(originalIndex)+ const isSelected = key === selectedBoxKey+ // the boxes intercept pointer events so wheel events from within them+ // bubble up to the overlay's non-passive listener above+ const boxElement = (+ <div+ data-attr="clickmap-box"+ role="button"+ tabIndex={0}+ aria-label={box.label || box.displaySelector}+ className={`absolute rounded-sm border border-danger pointer-events-auto cursor-pointer ${+ isSelected ? 'border-2' : 'hover:border-2 focus-visible:border-2'+ }`}+ // 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)+ })`,+ }}+ onClick={() => selectClickmapBox(isSelected ? null : key)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ selectClickmapBox(isSelected ? null : key)+ }+ }}+ onMouseEnter={() => setHoveredBoxKey(key)}+ onMouseLeave={() => setHoveredBoxKey(null)}+ >+ <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>- ))}+ )++ return isSelected ? (+ <Popover+ key={key}+ visible+ onClickOutside={() => selectClickmapBox(null)}+ placement="right"+ overlay={+ <div className="p-2">+ <ClickmapBoxInfo box={box} rank={originalIndex + 1} totalCount={totalClickCount} />+ </div>+ }+ >+ {boxElement}+ </Popover>+ ) : (+ <Tooltip+ key={key}+ title={<ClickmapBoxInfo box={box} rank={originalIndex + 1} totalCount={totalClickCount} />}+ >+ {boxElement}+ </Tooltip>+ )+ })}</div></div>)diff --git a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.ts b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.tsindex 52a38125d424..1e578f528c08 100644--- a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.ts+++ b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.test.ts@@ -71,15 +71,26 @@ describe('recordingClickmapLogic', () => {jest.restoreAllMocks()})- it('aggregates counts from multiple chains resolving to the same element into one box', () => {+ it('aggregates counts per event type from chains resolving to the same element', () => {const boxes = computeClickmapBoxes(- [statsRow({ count: 10 }), statsRow({ count: 3, hash: 'other-chain-same-element' })],+ [+ statsRow({ count: 10 }),+ statsRow({ count: 3, hash: 'rage', type: '$rageclick' }),+ statsRow({ count: 2, hash: 'dead', type: '$dead_click' }),+ ],snapshotDocument,null,['data-attr'])expect(boxes).toHaveLength(1)- expect(boxes[0].count).toBe(13)+ expect(boxes[0]).toMatchObject({+ count: 15,+ clickCount: 10,+ rageclickCount: 3,+ deadclickCount: 2,+ label: 'Sign up',+ displaySelector: 'button#cta',+ })})it('produces one box per matched element, sorted by count descending', () => {diff --git a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.tsindex b3c985a04bd5..b006f0fc82b3 100644--- a/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts+++ b/frontend/src/scenes/heatmaps/components/recordingClickmapLogic.ts@@ -1,9 +1,11 @@-import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'+import { actions, connect, events, kea, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'import { collectAllElementsDeep } from 'query-selector-shadow-dom'import { RefObject } from 'react'+import api from 'lib/api'import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -15,7 +17,7 @@ import { escapeUnescapedRegex } from '~/toolbar/elements/heatmapToolbarMenuLogicimport { ElementsEventType } from '~/toolbar/types'import { PropertyFilterType, PropertyOperator } from '~/types'-import { elementsStatsRetrieve } from 'products/product_analytics/frontend/generated/api'+import { getElementsStatsRetrieveUrl } from 'products/product_analytics/frontend/generated/api'import type {ElementStatsResponseApi,ElementsStatsRetrieveParams,@@ -30,6 +32,11 @@ export interface ClickmapBox {width: numberheight: numbercount: number+ clickCount: number+ rageclickCount: number+ deadclickCount: number+ label: string+ displaySelector: string}export type RecordingClickmapLogicProps = {@@ -81,37 +88,60 @@ export function buildElementStatsParams(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}+function emptyCounts(): Pick<ClickmapBox, 'count' | 'clickCount' | 'rageclickCount' | 'deadclickCount'> {+ return { count: 0, clickCount: 0, rageclickCount: 0, deadclickCount: 0 }+}++function describeElement(element: HTMLElement): { label: string; displaySelector: string } {+ const tag = element.tagName.toLowerCase()+ const id = element.id ? `#${element.id}` : ''+ const firstClass = element.classList.length ? `.${element.classList[0]}` : ''+ return {+ displaySelector: `${tag}${id}${firstClass}`,+ label: element.textContent?.trim().replace(/\s+/g, ' ').slice(0, 60) ?? '',+ }+}+export function computeClickmapBoxes(statsRows: ElementStatsResponseApi['results'],snapshotDocument: Document,snapshotWindow: { scrollX: number; scrollY: number } | null,- dataAttributes: string[]+ dataAttributes: string[],+ matchLinksByHref: boolean = false): ClickmapBox[] {const pageElements = collectAllElementsDeep('*', snapshotDocument) as HTMLElement[]const domIndex = buildDOMIndex(pageElements)- const countsByElement = new Map<HTMLElement, number>()+ const countsByElement = new Map<HTMLElement, ReturnType<typeof emptyCounts>>()for (const row of statsRows) {const match = matchEventToElementUsingIndex(row as unknown as ElementsEventType,dataAttributes,- false,+ matchLinksByHref,domIndex)if (match) {- countsByElement.set(match.element, (countsByElement.get(match.element) ?? 0) + row.count)+ const counts = countsByElement.get(match.element) ?? emptyCounts()+ counts.count += row.count+ if (row.type === '$rageclick') {+ counts.rageclickCount += row.count+ } else if (row.type === '$dead_click') {+ counts.deadclickCount += row.count+ } else {+ counts.clickCount += row.count+ }+ countsByElement.set(match.element, counts)}}const scrollX = snapshotWindow?.scrollX ?? 0const scrollY = snapshotWindow?.scrollY ?? 0const boxes: ClickmapBox[] = []- countsByElement.forEach((count, element) => {+ countsByElement.forEach((counts, element) => {const rect = element.getBoundingClientRect()if (rect.width > 0 && rect.height > 0) {boxes.push({@@ -119,7 +149,8 @@ export function computeClickmapBoxes(left: rect.left + scrollX,width: rect.width,height: rect.height,- count,+ ...counts,+ ...describeElement(element),})}})@@ -146,11 +177,14 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([heatmapsBrowserLogic,['onIframeLoad', 'setReplayIframeData', 'setReplayIframeDataURL'],heatmapDataLogic({ context: 'in-app' }),- ['setCommonFilters', 'setWindowWidthOverride'],+ ['setCommonFilters', 'setWindowWidthOverride', 'setHeatmapTooltipSuppressed'],],})),actions({setClickmapEnabled: (enabled: boolean) => ({ enabled }),+ setMatchLinksByHref: (matchLinksByHref: boolean) => ({ matchLinksByHref }),+ selectClickmapBox: (key: string | null) => ({ key }),+ setHoveredBoxKey: (key: string | null) => ({ key }),loadElementStats: true,maybeLoadElementStats: true,recomputeClickmap: true,@@ -163,6 +197,12 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([setClickmapEnabled: (_, { enabled }) => enabled,},],+ matchLinksByHref: [+ false,+ {+ setMatchLinksByHref: (_, { matchLinksByHref }) => matchLinksByHref,+ },+ ],clickmapBoxes: [[] as ClickmapBox[],{@@ -172,6 +212,26 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([setReplayIframeDataURL: () => [],},],+ selectedBoxKey: [+ null as string | null,+ {+ selectClickmapBox: (_, { key }) => key,+ setClickmapBoxes: () => null,+ setClickmapEnabled: () => null,+ setReplayIframeData: () => null,+ setReplayIframeDataURL: () => null,+ },+ ],+ hoveredBoxKey: [+ null as string | null,+ {+ setHoveredBoxKey: (_, { key }) => key,+ setClickmapBoxes: () => null,+ setClickmapEnabled: () => null,+ setReplayIframeData: () => null,+ setReplayIframeDataURL: () => null,+ },+ ],// the loader keeps stale stats across recording changes otherwise, and// onIframeLoad would repaint the old recording's counts onto the new snapshotelementStats: {@@ -197,7 +257,9 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([values.commonFilters,values.wantedDataAttributes)- const response = await elementsStatsRetrieve(String(values.currentProjectId), params)+ const response = await api.get<ElementStatsResponseApi>(+ getElementsStatsRetrieveUrl(String(values.currentProjectId), params)+ )breakpoint()return response},@@ -221,7 +283,27 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([(s) => [s.clickmapBoxes],(clickmapBoxes) => clickmapBoxes.reduce((max, box) => Math.max(max, box.count), 0),],+ totalClickCount: [+ (s) => [s.clickmapBoxes],+ (clickmapBoxes) => clickmapBoxes.reduce((sum, box) => sum + box.count, 0),+ ],+ tooltipSuppressed: [+ (s) => [s.hoveredBoxKey, s.selectedBoxKey],+ (hoveredBoxKey, selectedBoxKey): boolean => hoveredBoxKey !== null || selectedBoxKey !== null,+ ],}),+ subscriptions(({ actions }) => ({+ tooltipSuppressed: (value: boolean) => {+ actions.setHeatmapTooltipSuppressed(value)+ },+ })),+ events(({ actions }) => ({+ beforeUnmount: () => {+ // heatmapDataLogic outlives this logic, so its reducer won't reset on our unmount —+ // we must explicitly clear the suppression flag we set via the subscription above+ actions.setHeatmapTooltipSuppressed(false)+ },+ })),listeners(({ actions, values, props }) => ({setClickmapEnabled: ({ enabled }) => {posthog.capture('in-app heatmap clickmap toggled', { enabled })@@ -237,6 +319,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([setReplayIframeData: () => actions.maybeLoadElementStats(),setReplayIframeDataURL: () => actions.maybeLoadElementStats(),setCommonFilters: () => actions.maybeLoadElementStats(),+ setMatchLinksByHref: () => actions.recomputeClickmap(),setWindowWidthOverride: () => actions.recomputeClickmap(),onIframeLoad: () => {if (values.elementStats) {@@ -263,7 +346,8 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([statsRows,snapshotDocument,iframe?.contentWindow ?? null,- values.wantedDataAttributes+ values.wantedDataAttributes,+ values.matchLinksByHref)posthog.capture('in-app heatmap clickmap rendered', {stats_rows: statsRows.length,diff --git a/frontend/src/toolbar/elements/ElementInfo.tsx b/frontend/src/toolbar/elements/ElementInfo.tsxindex 9d932f300f85..c304a5ec685f 100644--- a/frontend/src/toolbar/elements/ElementInfo.tsx+++ b/frontend/src/toolbar/elements/ElementInfo.tsx@@ -1,15 +1,16 @@import { useActions, useValues } from 'kea'-import { IconCalendar, IconPlus } from '@posthog/icons'+import { IconPlus } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'+import { ElementClickStats } from 'lib/components/heatmaps/ElementClickStats'+import { ActionsListView } from '~/toolbar/actions/ActionsListView'import { ActionStep } from '~/toolbar/actions/ActionStep'import { elementsLogic } from '~/toolbar/elements/elementsLogic'import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'import { actionsTabLogic } from '../actions/actionsTabLogic'-import { ElementStatistic } from './ElementStatistic'import { SelectorQualityWarning } from './SelectorQualityWarning'export function ElementInfo(): JSX.Element | null {@@ -37,22 +38,15 @@ export function ElementInfo(): JSX.Element | null {{position ? (<div className="p-3 border-l-[5px] border-l-danger bg-surface-primary text-primary"><h1 className="section-title">Stats</h1>- <p className="">- <IconCalendar /> <u>{dateRange}</u>- </p>- <div className="grid grid-cols-[auto_1fr] gap-4">- <ElementStatistic- title="Clicks"- value={count || 0}- suffix={`/${totalClickCount} (${- totalClickCount === 0 ? '?' : Math.round(((count || 0) / totalClickCount) * 10000) / 100- }%)`}- />- <ElementStatistic title="Ranking" prefix="#" value={position || 0} />- <ElementStatistic title="Autocapture clicks" value={clickCount || 0} />- <ElementStatistic title="Rageclicks" value={rageclickCount || 0} />- <ElementStatistic title="Deadclicks" value={deadclickCount || 0} />- </div>+ <ElementClickStats+ count={count || 0}+ totalCount={totalClickCount}+ rank={position || 0}+ clickCount={clickCount || 0}+ rageclickCount={rageclickCount || 0}+ deadclickCount={deadclickCount || 0}+ dateRange={dateRange ?? undefined}+ /></div>) : null}diff --git a/frontend/src/toolbar/elements/ElementStatistic.tsx b/frontend/src/toolbar/elements/ElementStatistic.tsxdeleted file mode 100644index 34edb11d3edc..000000000000--- a/frontend/src/toolbar/elements/ElementStatistic.tsx+++ /dev/null@@ -1,19 +0,0 @@-type ElementStatisticProps = {- title: string- value: string | number- prefix?: string- suffix?: string-}--export function ElementStatistic({ title, value, prefix, suffix }: ElementStatisticProps): JSX.Element {- return (- <div className="flex flex-col">- <div>{title}</div>- <div className="text-2xl">- {prefix}- {value}- {suffix}- </div>- </div>- )-}