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.

fix(heatmaps): Add loading + other fixes to heatmaps (#95716)

Jordan Mryyanc776e68dab84
diff --git a/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx b/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx
index 133035733f8b..09194d5193e8 100644
--- a/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx
+++ b/frontend/src/lib/components/heatmaps/HeatMapsSettings.tsx
@@ -3,7 +3,7 @@ import React, { useState } from 'react'
import { IconInfo } from '@posthog/icons'
-import { HEATMAP_COLOR_PALETTE_OPTIONS } from 'lib/components/heatmaps/heatmapDataLogic'
+import { HEATMAP_COLOR_PALETTE_OPTIONS, HEATMAP_TYPE_OPTIONS } from 'lib/components/heatmaps/heatmapDataLogic'
import { HeatmapFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
@@ -106,28 +106,7 @@ export const HeatmapsSettings = ({
<LemonSelect
onChange={(e) => patchHeatmapFilters?.({ type: e })}
value={heatmapFilters?.type ?? undefined}
- options={[
- {
- value: 'click',
- label: 'Clicks',
- },
- {
- value: 'rageclick',
- label: 'Rageclicks',
- },
- {
- value: 'deadclick',
- label: 'Dead clicks',
- },
- {
- value: 'mousemove',
- label: 'Mouse moves',
- },
- {
- value: 'scrolldepth',
- label: 'Scroll depth',
- },
- ]}
+ options={HEATMAP_TYPE_OPTIONS}
size="small"
/>
diff --git a/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx b/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx
index 964d92215f3a..b86f23e485eb 100644
--- a/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx
+++ b/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx
@@ -6,10 +6,12 @@ import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import { HeatmapAreaPoint } from 'lib/components/heatmaps/types'
import { useShiftKeyPressed } from 'lib/components/heatmaps/useShiftKeyPressed'
import { cn } from 'lib/utils/css-classes'
+import { pluralize } from 'lib/utils/strings'
import { HeatmapEventsPanel } from './HeatmapEventsPanel'
+import { HeatmapLoadingInfo } from './HeatmapLoadingInfo'
import { ScrollDepthCanvas } from './ScrollDepthCanvas'
-import { useMousePosition } from './useMousePosition'
+import { MousePosition, useMousePosition } from './useMousePosition'
import { useScrollSync } from './useScrollSync'
// Radius in pixels to search for nearby heatmap elements when clicking
@@ -23,6 +25,19 @@ const HEATMAP_CONFIG = {
maxOpacity: 0.8,
}
+const INFO_BOX_CLASSES = 'border rounded bg-surface-primary shadow-md font-semibold'
+
+function heatmapValueAt(
+ heatmapJs: HeatmapJS<'value', 'x', 'y'> | undefined,
+ position: MousePosition
+): number | undefined {
+ try {
+ return heatmapJs?.getValueAt(position)
+ } catch {
+ return undefined
+ }
+}
+
function HeatmapMouseInfo({
heatmapJsRef,
containerRef,
@@ -35,21 +50,11 @@ function HeatmapMouseInfo({
onHasValue?: (hasValue: boolean) => void
}): JSX.Element | null {
const shiftPressed = useShiftKeyPressed()
- const { heatmapTooltipLabel, rawHeatmapLoading, heatmapTooltipSuppressed } = useValues(
- heatmapDataLogic({ context })
- )
+ const { heatmapTooltipNoun, rawHeatmapLoading, heatmapTooltipSuppressed } = useValues(heatmapDataLogic({ context }))
const containerMousePosition = useMousePosition(containerRef?.current)
const viewportMousePosition = useMousePosition()
- let value: number | undefined
- try {
- value = heatmapJsRef.current?.getValueAt(containerMousePosition)
- } catch {
- // heatmap.js throws reading its canvas if it was created while the container had
- // zero height (IndexSizeError in Chromium, raw NS_ERROR_FAILURE in Firefox);
- // this runs on every mouse move, so swallow rather than crash the scene
- value = undefined
- }
+ const value = containerMousePosition ? heatmapValueAt(heatmapJsRef.current, containerMousePosition) : undefined
const hasValue = !!(containerMousePosition && (value || shiftPressed)) && !heatmapTooltipSuppressed
@@ -57,7 +62,7 @@ function HeatmapMouseInfo({
onHasValue?.(hasValue)
}, [hasValue, onHasValue])
- if (!hasValue) {
+ if (!hasValue || !viewportMousePosition) {
return null
}
@@ -73,8 +78,8 @@ function HeatmapMouseInfo({
right: flipLeft ? window.innerWidth - viewportMousePosition.x + TOOLTIP_OFFSET_PX : undefined,
}}
>
- <div className="border rounded bg-surface-primary shadow-md p-2 whitespace-nowrap font-semibold">
- {rawHeatmapLoading ? 'Loading…' : `${value ?? 0} ${heatmapTooltipLabel}`}
+ <div className={cn(INFO_BOX_CLASSES, 'p-2 whitespace-nowrap')}>
+ {rawHeatmapLoading ? 'Loading…' : pluralize(value ?? 0, heatmapTooltipNoun)}
</div>
</div>
)
@@ -219,12 +224,15 @@ export function HeatmapCanvas({
if (heatmapFilters.type === 'scrolldepth') {
return (
- <ScrollDepthCanvas
- key={`scrolldepth-${heatmapFilters.type}-${exportToken ? 'export' : `${widthOverride ?? windowWidth}x${windowHeight}`}`}
- positioning={positioning}
- context={context}
- exportToken={exportToken}
- />
+ <>
+ <ScrollDepthCanvas
+ key={`scrolldepth-${heatmapFilters.type}-${exportToken ? 'export' : `${widthOverride ?? windowWidth}x${windowHeight}`}`}
+ positioning={positioning}
+ context={context}
+ exportToken={exportToken}
+ />
+ <HeatmapLoadingInfo context={context} exportToken={exportToken} />
+ </>
)
}
@@ -283,6 +291,7 @@ export function HeatmapCanvas({
onHasValue={setHasValueUnderMouse}
/>
<HeatmapEventsPanel context={context} exportToken={exportToken} />
+ <HeatmapLoadingInfo context={context} exportToken={exportToken} />
</div>
)
}
diff --git a/frontend/src/lib/components/heatmaps/HeatmapLoadingInfo.tsx b/frontend/src/lib/components/heatmaps/HeatmapLoadingInfo.tsx
new file mode 100644
index 000000000000..b68aedc5a8b9
--- /dev/null
+++ b/frontend/src/lib/components/heatmaps/HeatmapLoadingInfo.tsx
@@ -0,0 +1,30 @@
+import { useValues } from 'kea'
+
+import { HEATMAP_LOADING_DEBOUNCE_MS, heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
+
+export function HeatmapLoadingInfo({
+ context,
+ exportToken,
+}: {
+ context: 'in-app' | 'toolbar'
+ exportToken?: string
+}): JSX.Element | null {
+ const { rawHeatmapLoading } = useValues(heatmapDataLogic({ context, exportToken }))
+ const loading = useDebouncedValue(rawHeatmapLoading, HEATMAP_LOADING_DEBOUNCE_MS)
+
+ if (!loading || context === 'toolbar' || exportToken || inStorybook() || inStorybookTestRunner()) {
+ return null
+ }
+
+ return (
+ <div className="absolute inset-0 z-20 flex items-start justify-center pointer-events-none">
+ <div className="flex items-center gap-2 mt-8 px-3 py-2 border rounded bg-surface-primary shadow-md font-semibold">
+ <Spinner />
+ Loading heatmap data
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/heatmaps/ScrollDepthCanvas.tsx b/frontend/src/lib/components/heatmaps/ScrollDepthCanvas.tsx
index 3249b9c3162e..bd4db346b7fd 100644
--- a/frontend/src/lib/components/heatmaps/ScrollDepthCanvas.tsx
+++ b/frontend/src/lib/components/heatmaps/ScrollDepthCanvas.tsx
@@ -89,9 +89,9 @@ function ScrollDepthMouseInfo({
}): JSX.Element | null {
const { heatmapElements, rawHeatmapLoading } = useValues(heatmapDataLogic({ context, exportToken }))
- const { y: mouseY } = useMousePosition()
+ const mouseY = useMousePosition()?.y
- if (!mouseY) {
+ if (mouseY === undefined) {
return null
}
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
index c1fb10e3ee07..87de1a6f7529 100644
--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
@@ -13,6 +13,7 @@ import {
HeatmapFixedPositionMode,
HeatmapJsData,
HeatmapJsDataPoint,
+ HeatmapKind,
} from 'lib/components/heatmaps/types'
import {
DEFAULT_HEATMAP_FILTERS,
@@ -38,6 +39,20 @@ const UNBOUNDED_HEATMAP_LIMIT = 0
// Large canvases (e.g., 24000px) cause heatmap.js to block the main thread
export const MAX_HEATMAP_HEIGHT = 8000
+export const HEATMAP_LOADING_DEBOUNCE_MS = 200
+
+export const HEATMAP_TYPES: Record<HeatmapKind, { label: string; noun: string }> = {
+ click: { label: 'Clicks', noun: 'click' },
+ rageclick: { label: 'Rageclicks', noun: 'rageclick' },
+ deadclick: { label: 'Dead clicks', noun: 'dead click' },
+ mousemove: { label: 'Mouse moves', noun: 'mouse move' },
+ scrolldepth: { label: 'Scroll depth', noun: 'scroll depth' },
+}
+
+export const HEATMAP_TYPE_OPTIONS: LemonSelectOption<HeatmapKind>[] = (Object.keys(HEATMAP_TYPES) as HeatmapKind[]).map(
+ (value) => ({ value, label: HEATMAP_TYPES[value].label })
+)
+
export const HEATMAP_COLOR_PALETTE_OPTIONS: LemonSelectOption<string>[] = [
{ value: 'default', label: 'Default (multicolor)' },
{ value: 'red', label: 'Red (monocolor)' },
@@ -163,7 +178,7 @@ export interface heatmapDataLogicValues {
heatmapFilters: HeatmapFilters
heatmapFixedPositionMode: HeatmapFixedPositionMode
heatmapJsData: HeatmapJsData
- heatmapTooltipLabel: string
+ heatmapTooltipNoun: string
heatmapTooltipSuppressed: boolean
heightOverride: number
href: string | null
@@ -307,7 +322,7 @@ export interface heatmapDataLogicMeta {
min: number
}
widthOverride: (windowWidthOverride: number | null) => number
- heatmapTooltipLabel: (heatmapFilters: HeatmapFilters) => string
+ heatmapTooltipNoun: (heatmapFilters: HeatmapFilters) => string
heatmapEmpty: (rawHeatmap: HeatmapResponseType | null, rawHeatmapLoading: boolean) => boolean
maxYFromEvents: (heatmapElements: HeatmapElement[]) => number
heightOverride: (maxYFromEvents: number, windowHeight: number) => number
@@ -604,13 +619,13 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([
(windowWidthOverride: number | null): number => windowWidthOverride ?? DEFAULT_HEATMAP_WIDTH,
],
- heatmapTooltipLabel: [
+ heatmapTooltipNoun: [
(s) => [s.heatmapFilters],
(heatmapFilters: HeatmapFilters) => {
if (heatmapFilters.aggregation === 'unique_visitors') {
- return 'visitors'
+ return 'visitor'
}
- return heatmapFilters.type + 's'
+ return (HEATMAP_TYPES[heatmapFilters.type ?? 'click'] ?? HEATMAP_TYPES.click).noun
},
],
diff --git a/frontend/src/lib/components/heatmaps/types.ts b/frontend/src/lib/components/heatmaps/types.ts
index 5ce8b4ce686f..da89a895bcc8 100644
--- a/frontend/src/lib/components/heatmaps/types.ts
+++ b/frontend/src/lib/components/heatmaps/types.ts
@@ -17,7 +17,7 @@ export type HeatmapEventFilter = {
properties?: Record<string, any>[]
}
-export type HeatmapKind = 'click' | 'rageclick' | 'mousemove' | 'scrolldepth'
+export type HeatmapKind = 'click' | 'rageclick' | 'deadclick' | 'mousemove' | 'scrolldepth'
export type HeatmapRequestType = {
type: HeatmapKind
@@ -32,7 +32,7 @@ export type HeatmapRequestType = {
export type HeatmapFilters = {
enabled: boolean
- type?: string
+ type?: HeatmapKind
viewportAccuracy?: number
aggregation?: HeatmapRequestType['aggregation']
}
diff --git a/frontend/src/lib/components/heatmaps/useMousePosition.test.ts b/frontend/src/lib/components/heatmaps/useMousePosition.test.ts
new file mode 100644
index 000000000000..17d092947564
--- /dev/null
+++ b/frontend/src/lib/components/heatmaps/useMousePosition.test.ts
@@ -0,0 +1,48 @@
+import { fireEvent, renderHook } from '@testing-library/react'
+
+import { useMousePosition } from './useMousePosition'
+
+const CONTAINER_LEFT = 100
+const CONTAINER_TOP = 50
+const CONTAINER_WIDTH = 200
+const CONTAINER_HEIGHT = 300
+
+function createContainer(): HTMLElement {
+ const element = document.createElement('div')
+ element.getBoundingClientRect = () =>
+ ({
+ left: CONTAINER_LEFT,
+ top: CONTAINER_TOP,
+ width: CONTAINER_WIDTH,
+ height: CONTAINER_HEIGHT,
+ }) as DOMRect
+ return element
+}
+
+describe('useMousePosition', () => {
+ test.each<[string, number, number]>([
+ ['left of', 90, 100],
+ ['above', 150, 40],
+ ['right of', 310, 100],
+ ['below', 150, 360],
+ ])('clears the container position once the pointer is %s the container', (_, clientX, clientY) => {
+ const container = createContainer()
+ const { result } = renderHook(() => useMousePosition(container))
+
+ fireEvent.mouseMove(window, { clientX: 150, clientY: 100 })
+ expect(result.current).toEqual({ x: 50, y: 50 })
+
+ fireEvent.mouseMove(window, { clientX, clientY })
+ expect(result.current).toBeNull()
+ })
+
+ it('reports viewport positions when no container is given', () => {
+ const { result } = renderHook(() => useMousePosition())
+
+ expect(result.current).toBeNull()
+
+ fireEvent.mouseMove(window, { clientX: 150, clientY: 100 })
+
+ expect(result.current).toEqual({ x: 150, y: 100 })
+ })
+})
diff --git a/frontend/src/lib/components/heatmaps/useMousePosition.ts b/frontend/src/lib/components/heatmaps/useMousePosition.ts
index a9fe1e9cb22b..af33377d1c0a 100644
--- a/frontend/src/lib/components/heatmaps/useMousePosition.ts
+++ b/frontend/src/lib/components/heatmaps/useMousePosition.ts
@@ -1,24 +1,28 @@
import { useEffect, useState } from 'react'
+export type MousePosition = { x: number; y: number }
+
+function positionIn(e: MouseEvent, container?: HTMLElement | null): MousePosition | null {
+ if (!container) {
+ return { x: e.clientX, y: e.clientY }
+ }
+ const rect = container.getBoundingClientRect()
+ const x = e.clientX - rect.left
+ const y = e.clientY - rect.top
+ return x >= 0 && y >= 0 && x <= rect.width && y <= rect.height ? { x, y } : null
+}
+
/**
* Hook to get the current mouse position relative to the window.
* Optionally takes a container element.
* if one is provided, the position will be relative to the container.
*/
-export const useMousePosition = (container?: HTMLElement | null): { x: number; y: number } => {
- const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 })
+export function useMousePosition(container?: HTMLElement | null): MousePosition | null {
+ const [mousePosition, setMousePosition] = useState<MousePosition | null>(null)
useEffect(() => {
const onMove = (e: MouseEvent): void => {
- const rect = container ? container.getBoundingClientRect() : { left: 0, top: 0 }
- const newX = e.clientX - rect.left
- const newY = e.clientY - rect.top
- const inBounds = newX >= 0 && newY >= 0
-
- setMousePosition((prev) => {
- const hasChanged = newX !== prev.x || newY !== prev.y
- return inBounds && hasChanged ? { x: newX, y: newY } : prev
- })
+ setMousePosition(positionIn(e, container))
}
window.addEventListener('mousemove', onMove, { passive: true })
diff --git a/frontend/src/toolbar/elements/ScrollDepth.tsx b/frontend/src/toolbar/elements/ScrollDepth.tsx
index d919e941b398..2cf480345d90 100644
--- a/frontend/src/toolbar/elements/ScrollDepth.tsx
+++ b/frontend/src/toolbar/elements/ScrollDepth.tsx
@@ -13,9 +13,9 @@ function ScrollDepthMouseInfo(): JSX.Element | null {
const { heatmapElements, rawHeatmapLoading } = useValues(heatmapToolbarMenuLogic)
const shiftPressed = useShiftKeyPressed()
- const { y: mouseY } = useMousePosition()
+ const mouseY = useMousePosition()?.y
- if (!mouseY) {
+ if (mouseY === undefined) {
return null
}
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index d571c442317c..de6d0b164a3c 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -343,7 +343,6 @@ export interface heatmapToolbarMenuLogicValues {
heatmapElements: HeatmapElement[] // heatmapDataLogic
heatmapFilters: HeatmapFilters // heatmapDataLogic
heatmapFixedPositionMode: HeatmapFixedPositionMode // heatmapDataLogic
- heatmapTooltipLabel: string // heatmapDataLogic
rawHeatmapLoading: boolean // heatmapDataLogic
viewportRange: {
max: number
@@ -668,7 +667,6 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
'viewportRange',
'heatmapFilters',
'heatmapElements',
- 'heatmapTooltipLabel',
'dateRange',
],
],
diff --git a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx
index e9ef32a7ba51..8c418fe52fdd 100644
--- a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx
+++ b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx
@@ -1,17 +1,18 @@
import { useActions, useValues } from 'kea'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { IconFilter, IconGear, IconLaptop, IconPhone, IconTabletLandscape, IconTabletPortrait } from '@posthog/icons'
import { LemonBadge, LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { HEATMAP_LOADING_DEBOUNCE_MS, heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
import { HeatmapsSettings } from 'lib/components/heatmaps/HeatMapsSettings'
import { SectionSetting } from 'lib/components/heatmaps/HeatMapsSettings'
import { HeatmapEventFilter } from 'lib/components/heatmaps/types'
import { heatmapDateOptions } from 'lib/components/IframedToolbarBrowser/utils'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LoadingBar } from 'lib/lemon-ui/LoadingBar'
import { Popover } from 'lib/lemon-ui/Popover'
@@ -37,20 +38,6 @@ const propertyFiltersToCohortIds = (filters: AnyPropertyFilter[]): number[] =>
.map((f) => f.value)
.filter((v): v is number => typeof v === 'number')
-const useDebounceLoading = (loading: boolean, delay = 200): boolean => {
- const [debouncedLoading, setDebouncedLoading] = useState(false)
-
- useEffect(() => {
- const timer = setTimeout(() => {
- setDebouncedLoading(loading)
- }, delay)
-
- return () => clearTimeout(timer)
- }, [loading, delay])
-
- return debouncedLoading
-}
-
export function ViewportChooser({ lockedWidth }: { lockedWidth?: number }): JSX.Element {
const { widthOverride } = useValues(heatmapDataLogic({ context: 'in-app' }))
const { setWindowWidthOverride } = useActions(heatmapDataLogic({ context: 'in-app' }))
@@ -152,13 +139,13 @@ export function FilterPanel({
const eventFilterEnabled = useFeatureFlag('HEATMAPS_EVENT_FILTER')
const eventFilterCount = commonFilters?.events?.length ?? 0
- const debouncedLoading = useDebounceLoading(rawHeatmapLoading ?? false)
+ const debouncedLoading = useDebouncedValue(rawHeatmapLoading, HEATMAP_LOADING_DEBOUNCE_MS)
// KLUDGE: the loading bar flaps in visual regression tests,
// for some reason our wait for loading to finish can't see it
// this is ugly but better than stopping taking visual snapshots of it
return (
- <>
+ <div className="relative">
{debouncedLoading && !inStorybook() && !inStorybookTestRunner() && (
<LoadingBar
wrapperClassName="absolute top-0 left-0 w-full overflow-hidden rounded-none my-0"
@@ -328,6 +315,6 @@ export function FilterPanel({
settings. A high value can hide data on pages with less traffic.
</LemonBanner>
) : null}
- </>
+ </div>
)
}