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(toolbar): filter heatmap and clickmap to a selected page area (#68474)

Paul D'Ambrac66bee5704f2
diff --git a/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx b/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx
index dfabbf1894b6..e1018d538e36 100644
--- a/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx
+++ b/frontend/src/lib/components/heatmaps/HeatmapCanvas.tsx
@@ -90,7 +90,7 @@ export function HeatmapCanvas({
isReady,
heightOverride,
heatmapFixedPositionMode,
- heatmapElements,
+ filteredHeatmapElements,
windowWidthOverride,
} = useValues(heatmapDataLogic({ context, exportToken }))
const { setSelectedArea } = useActions(heatmapDataLogic({ context, exportToken }))
@@ -133,7 +133,7 @@ export function HeatmapCanvas({
const nearbyElements: HeatmapAreaPoint[] = []
let totalCount = 0
- for (const element of heatmapElements) {
+ for (const element of filteredHeatmapElements) {
const visualX = element.xPercentage * width
const distance = Math.sqrt(Math.pow(clickX - visualX, 2) + Math.pow(clickY - element.y, 2))
@@ -156,7 +156,7 @@ export function HeatmapCanvas({
})
}
},
- [heatmapElements, windowWidth, windowWidthOverride, setSelectedArea, isToolbar, scrollYRef]
+ [filteredHeatmapElements, windowWidth, windowWidthOverride, setSelectedArea, isToolbar, scrollYRef]
)
const setHeatmapContainer = useCallback((container: HTMLDivElement | null): void => {
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts
index 16cd6b25331d..568d46944a0f 100644
--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts
+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts
@@ -1,7 +1,33 @@
-import { heatmapApiPath } from 'lib/components/heatmaps/heatmapDataLogic'
+import { heatmapApiPath, isWithinBounds } from 'lib/components/heatmaps/heatmapDataLogic'
+import { HeatmapBoundsFilter } from 'lib/components/heatmaps/types'
import { AppContext } from '~/types'
+describe('isWithinBounds', () => {
+ const staticArea: HeatmapBoundsFilter = {
+ areaFixed: false,
+ bounds: { left: 100, right: 200, top: 1000, bottom: 2000 },
+ }
+ const fixedArea: HeatmapBoundsFilter = {
+ areaFixed: true,
+ bounds: { left: 100, right: 200, top: 10, bottom: 60 },
+ }
+
+ it.each([
+ ['no filter keeps every point', { x: 0, y: 0, targetFixed: false }, null, true],
+ ['a static point inside a static area', { x: 150, y: 1500, targetFixed: false }, staticArea, true],
+ ['a static point outside a static area', { x: 150, y: 100, targetFixed: false }, staticArea, false],
+ // points and areas in different coordinate spaces are excluded, not cross-compared
+ ['a fixed point against a static area', { x: 150, y: 1500, targetFixed: true }, staticArea, false],
+ ['a static point against a fixed area', { x: 150, y: 30, targetFixed: false }, fixedArea, false],
+ ['a fixed point inside a fixed area', { x: 150, y: 30, targetFixed: true }, fixedArea, true],
+ ['a fixed point outside a fixed area', { x: 150, y: 300, targetFixed: true }, fixedArea, false],
+ ['a boundary point is inclusive', { x: 100, y: 1000, targetFixed: false }, staticArea, true],
+ ] as const)('%s', (_name, point, filter, expected) => {
+ expect(isWithinBounds(point, filter)).toBe(expected)
+ })
+})
+
describe('heatmapApiPath', () => {
let priorAppContext: AppContext | undefined
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
index a1fff35be69f..321f5858019d 100644
--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
@@ -7,6 +7,7 @@ import { windowValues } from 'kea-window-values'
import {
CommonFilters,
HeatmapArea,
+ HeatmapBoundsFilter,
HeatmapEventsResponse,
HeatmapFilters,
HeatmapFixedPositionMode,
@@ -81,6 +82,22 @@ export function heatmapApiPath(context: HeatmapDataLogicProps['context'], endpoi
export type HrefMatchType = 'exact' | 'pattern'
+export function isWithinBounds(
+ point: { x: number; y: number; targetFixed: boolean },
+ boundsFilter: HeatmapBoundsFilter | null
+): boolean {
+ if (!boundsFilter) {
+ return true
+ }
+ // points and areas live in different coordinate spaces depending on fixedness, so a
+ // point of the other kind can't be meaningfully tested against this area — exclude it
+ if (point.targetFixed !== boundsFilter.areaFixed) {
+ return false
+ }
+ const { bounds } = boundsFilter
+ return point.x >= bounds.left && point.x <= bounds.right && point.y >= bounds.top && point.y <= bounds.bottom
+}
+
export const heatmapDataLogic = kea<heatmapDataLogicType>([
path((key) => ['lib', 'components', 'heatmap', 'heatmapDataLogic', key]),
props({ context: 'toolbar', exportToken: null } as HeatmapDataLogicProps),
@@ -95,6 +112,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([
setHref: (href: string) => ({ href }),
setHrefMatchType: (matchType: HrefMatchType) => ({ matchType }),
setWindowWidthOverride: (widthOverride: number | null) => ({ widthOverride }),
+ setHeatmapBoundsFilter: (boundsFilter: HeatmapBoundsFilter | null) => ({ boundsFilter }),
setIsReady: (isReady: boolean) => ({ isReady }),
// Click-to-view-events actions
setSelectedArea: (area: HeatmapArea | null) => ({ area }),
@@ -158,6 +176,14 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([
setWindowWidthOverride: (_, { widthOverride }) => widthOverride,
},
],
+ // deliberately not persisted: the bounds describe an element on the page currently
+ // being viewed, so they'd be meaningless (and misleading) on the next page
+ heatmapBoundsFilter: [
+ null as HeatmapBoundsFilter | null,
+ {
+ setHeatmapBoundsFilter: (_, { boundsFilter }) => boundsFilter,
+ },
+ ],
isReady: [
false as boolean,
{
@@ -393,11 +419,33 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([
},
],
+ // the one place the area bounds filter applies, so rendering (heatmapJsData) and
+ // click-to-view-events hit testing can't disagree about which points exist
+ filteredHeatmapElements: [
+ (s) => [s.heatmapElements, s.windowWidth, s.windowWidthOverride, s.heatmapBoundsFilter],
+ (heatmapElements, windowWidth, windowWidthOverride, heatmapBoundsFilter): HeatmapElement[] => {
+ if (!heatmapBoundsFilter) {
+ return heatmapElements
+ }
+ const width = windowWidthOverride ?? windowWidth
+ return heatmapElements.filter((element) =>
+ isWithinBounds(
+ {
+ x: Math.round(element.xPercentage * width),
+ y: Math.round(element.y),
+ targetFixed: element.targetFixed,
+ },
+ heatmapBoundsFilter
+ )
+ )
+ },
+ ],
+
heatmapJsData: [
- (s) => [s.heatmapElements, s.windowWidth, s.windowWidthOverride, s.heatmapFixedPositionMode],
- (heatmapElements, windowWidth, windowWidthOverride, heatmapFixedPositionMode): HeatmapJsData => {
+ (s) => [s.filteredHeatmapElements, s.windowWidth, s.windowWidthOverride, s.heatmapFixedPositionMode],
+ (filteredHeatmapElements, windowWidth, windowWidthOverride, heatmapFixedPositionMode): HeatmapJsData => {
const width = windowWidthOverride ?? windowWidth
- const data = heatmapElements.reduce((acc, element) => {
+ const data = filteredHeatmapElements.reduce((acc, element) => {
if (heatmapFixedPositionMode === 'hidden' && element.targetFixed) {
return acc
}
diff --git a/frontend/src/lib/components/heatmaps/types.ts b/frontend/src/lib/components/heatmaps/types.ts
index 6bd5a969a1e1..8e51b41eda58 100644
--- a/frontend/src/lib/components/heatmaps/types.ts
+++ b/frontend/src/lib/components/heatmaps/types.ts
@@ -39,6 +39,23 @@ export type HeatmapJsData = {
export type HeatmapFixedPositionMode = 'fixed' | 'relative' | 'hidden'
+export type HeatmapBounds = {
+ left: number
+ right: number
+ top: number
+ bottom: number
+}
+
+// pixel bounds of a page element the heatmap is filtered to. Fixed/sticky targets are
+// recorded in viewport coordinates and everything else in document coordinates (posthog-js's
+// target_fixed rule), so points are only comparable to an area of the same kind: a filter
+// carries the one rect that matches its area's kind, and points of the other kind are
+// excluded rather than compared across coordinate spaces (where they'd go stale on scroll)
+export type HeatmapBoundsFilter = {
+ bounds: HeatmapBounds
+ areaFixed: boolean
+}
+
export type HeatmapAreaPoint = {
x: number
y: number
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 4f866c392921..20a67c081cda 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -492,6 +492,7 @@ export const FEATURE_FLAGS = {
TAXONOMIC_FILTER_DEFAULT_PINS: 'taxonomic-filter-default-pins', // owner: @pauldambra #team-product-analytics, seeds $current_url/email default pinned filters
TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)
TOGGLE_PROPERTY_ARRAYS: 'toggle-property-arrays', // owner: @arthurdedeus #team-customer-analytics
+ TOOLBAR_HEATMAP_AREA_FILTER: 'toolbar-heatmap-area-filter', // owner: @pauldambra #team-replay, gates the target button that filters the toolbar heatmap/clickmap to a chosen page area
TRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)
TRACING_FACET_RAIL: 'tracing-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in tracing
TRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracing
diff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.md
index 4488ed0ae0f1..ba615642d77e 100644
--- a/frontend/src/toolbar/TELEMETRY.md
+++ b/frontend/src/toolbar/TELEMETRY.md
@@ -172,6 +172,31 @@ A user paginating emits one event per page with cumulative `event_count` — gro
**File:** `elements/heatmapToolbarMenuLogic.ts`
+### `toolbar heatmap area selection started`
+
+Fired when the user starts picking an area to filter the heatmap/clickmap to (the target icon in the heatmap menu).
+
+| Property | Type | Description |
+| ----------------- | --------- | -------------------------------------------------------------------------------------------------- |
+| `candidate_count` | `number` | Area candidates rendered as hover targets |
+| `capped` | `boolean` | Whether the candidate list hit its rendering cap (candidates beyond the cap, if any, were dropped) |
+
+**File:** `elements/heatmapToolbarMenuLogic.ts`
+
+### `toolbar heatmap area filter changed`
+
+Fired when the heatmap area filter is applied, changed, or cleared.
+
+| Property | Type | Description |
+| --------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| `enabled` | `boolean` | Whether a filter is now applied (`false` = cleared) |
+| `has_selector` | `boolean` | Whether a stable CSS selector was derived for the area (without one, only pixel bounds filtering runs) |
+| `tag_name` | `string \| null` | Lowercase tag name of the selected area element |
+| `trigger` | `'user' \| 'element_lost'` | `user` = picked or cleared in the UI; `element_lost` = the tracked node left the DOM and could not be re-resolved |
+| `arrow_stepped` | `boolean \| undefined` | Only on `trigger: 'user'`: whether arrow keys refined the selection before it was applied |
+
+**File:** `elements/heatmapToolbarMenuLogic.ts`
+
## Element inspection
### `toolbar selected HTML element`
diff --git a/frontend/src/toolbar/elements/Elements.tsx b/frontend/src/toolbar/elements/Elements.tsx
index 7245a7145df5..f8251f62013e 100644
--- a/frontend/src/toolbar/elements/Elements.tsx
+++ b/frontend/src/toolbar/elements/Elements.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { Fragment, memo } from 'react'
+import { Fragment, MouseEvent as ReactMouseEvent, memo, useMemo } from 'react'
import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
import { useShiftKeyPressed } from 'lib/components/heatmaps/useShiftKeyPressed'
@@ -14,11 +14,13 @@ import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLo
import { ElementHighlight } from '~/toolbar/product-tours/ElementHighlight'
import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'
import { ElementWithMetadata } from '~/toolbar/types'
-import { getBoxColors, getHeatMapHue } from '~/toolbar/utils'
+import { getBoxColors, getHeatMapHue, getToolbarRootElement } from '~/toolbar/utils'
import { toolbarLogic } from '../bar/toolbarLogic'
import { ScrollDepth } from './ScrollDepth'
+const noop = (): void => {}
+
let nextElementId = 0
const elementIdMap = new WeakMap<HTMLElement, number>()
@@ -42,10 +44,13 @@ export function Elements(): JSX.Element {
inspectEnabled,
highlightElementMeta,
relativePositionCompensation,
+ heatmapEnabled,
+ rectUpdateCounter,
} = useValues(elementsLogic)
const { setHoverElement, selectElement } = useActions(elementsLogic)
- const { highestClickCount } = useValues(heatmapToolbarMenuLogic)
- const { refreshClickmap } = useActions(heatmapToolbarMenuLogic)
+ const { highestClickCount, areaSelectionActive, areaHoverElement, heatmapAreaFilter, areaCandidates } =
+ useValues(heatmapToolbarMenuLogic)
+ const { refreshClickmap, setAreaHover, selectHeatmapAreaFilter } = useActions(heatmapToolbarMenuLogic)
const {
isSelecting: productToursSelecting,
hoverElementRect: productToursHoverRect,
@@ -53,7 +58,38 @@ export function Elements(): JSX.Element {
} = useValues(productToursLogic)
const shiftPressed = useShiftKeyPressed(refreshClickmap)
- const heatmapPointerEvents = shiftPressed ? 'none' : 'all'
+ // while picking an area the page itself must receive pointer events, so all overlays pass through
+ const heatmapPointerEvents = shiftPressed || areaSelectionActive ? 'none' : 'all'
+
+ // recomputed on scroll/resize via rectUpdateCounter so the fixed-position highlights track the page
+ const areaHoverRect = useMemo(
+ () => (areaHoverElement?.isConnected ? areaHoverElement.getBoundingClientRect() : null),
+ [areaHoverElement, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps
+ )
+ const areaFilterRect = useMemo(
+ () => (heatmapAreaFilter?.element.isConnected ? heatmapAreaFilter.element.getBoundingClientRect() : null),
+ [heatmapAreaFilter, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps
+ )
+ // already sorted biggest-first, so nested candidates paint children-on-top and stay hoverable
+ const areaCandidateRects = useMemo(
+ () =>
+ areaSelectionActive
+ ? areaCandidates
+ .filter((element) => element.isConnected)
+ .map((element) => ({ element, rect: element.getBoundingClientRect() }))
+ : [],
+ [areaSelectionActive, areaCandidates, rectUpdateCounter] // eslint-disable-line react-hooks/exhaustive-deps
+ )
+
+ const hoverAreaCandidate = (e: ReactMouseEvent, element: HTMLElement): void => {
+ // the real page leaf under the pointer (not this overlay box) anchors the arrow-key
+ // walk, so pressing down still shrinks toward what the user is pointing at
+ const toolbarRoot = getToolbarRootElement()
+ const leaf = (document.elementsFromPoint(e.clientX, e.clientY) as HTMLElement[]).find(
+ (el) => !toolbarRoot?.contains(el)
+ )
+ setAreaHover(leaf ?? element, element)
+ }
const { theme } = useValues(toolbarLogic)
@@ -84,6 +120,28 @@ export function Elements(): JSX.Element {
<ScrollDepth />
{activeToolbarMode === 'heatmap' && <HeatmapCanvas positioning="absolute" context="toolbar" />}
{highlightElementMeta?.rect ? <FocusRect rect={highlightElementMeta.rect} /> : null}
+ {areaCandidateRects.map(({ element, rect }) => (
+ <AutocaptureElement
+ key={`area-candidate-${getStableElementId(element)}`}
+ rect={rect}
+ style={{
+ pointerEvents: 'all',
+ cursor: 'crosshair',
+ zIndex: 1,
+ borderRadius: 5,
+ opacity: !areaHoverElement || areaHoverElement === element ? 1 : 0.6,
+ transition: 'opacity 0.2s, box-shadow 0.2s',
+ ...getBoxColors('blue', areaHoverElement === element, 0.1),
+ }}
+ onMouseOver={(e) => hoverAreaCandidate(e, element)}
+ onMouseOut={noop}
+ onClick={() => selectHeatmapAreaFilter(areaHoverElement ?? element)}
+ />
+ ))}
+ {areaSelectionActive && areaHoverRect && <ElementHighlight rect={areaHoverRect} />}
+ {heatmapEnabled && !areaSelectionActive && areaFilterRect && (
+ <ElementHighlight rect={areaFilterRect} isSelected />
+ )}
{productToursSelecting && productToursHoverRect && <ElementHighlight rect={productToursHoverRect} />}
{productToursSelectedStepRect && <ElementHighlight rect={productToursSelectedStepRect} isSelected />}
diff --git a/frontend/src/toolbar/elements/elementsLogic.ts b/frontend/src/toolbar/elements/elementsLogic.ts
index ab44b049c103..a786fa958b36 100644
--- a/frontend/src/toolbar/elements/elementsLogic.ts
+++ b/frontend/src/toolbar/elements/elementsLogic.ts
@@ -575,6 +575,10 @@ export const elementsLogic = kea<elementsLogicType>([
if (e.keyCode !== 27) {
return
}
+ if (heatmapToolbarMenuLogic.values.areaSelectionActive) {
+ heatmapToolbarMenuLogic.actions.cancelAreaSelection()
+ return
+ }
if (values.hoverElement) {
actions.setHoverElement(null)
}
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
index a30d15f41d5a..bc582b58f315 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
@@ -5,7 +5,16 @@ import { toolbarApi } from '~/toolbar/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { ElementsEventType } from '~/toolbar/types'
-import { dedupeByChainIdentity, heatmapToolbarMenuLogic } from './heatmapToolbarMenuLogic'
+import {
+ buildElementStatsProperties,
+ computeAreaCandidates,
+ dedupeByChainIdentity,
+ heatmapToolbarMenuLogic,
+ isInFixedContainer,
+ resolveAreaElement,
+ resolveAreaTarget,
+ stepAreaCandidate,
+} from './heatmapToolbarMenuLogic'
function statsRow(overrides: Partial<ElementsEventType>): ElementsEventType {
return {
@@ -60,6 +69,211 @@ describe('heatmapToolbarMenuLogic', () => {
})
})
+ describe('buildElementStatsProperties', () => {
+ it.each([
+ [
+ 'an exact url filter when the wildcard href matches the href',
+ 'https://example.com/page',
+ 'https://example.com/page',
+ null,
+ [{ key: '$current_url', value: 'https://example.com/page', operator: 'exact', type: 'event' }],
+ ],
+ [
+ 'a regex url filter when the wildcard href differs',
+ 'https://example.com/page/1',
+ 'https://example.com/page/*',
+ null,
+ [
+ {
+ key: '$current_url',
+ value: '^https\\:\\/\\/example\\.com\\/page\\/.*$',
+ operator: 'regex',
+ type: 'event',
+ },
+ ],
+ ],
+ [
+ 'an element selector filter when an area is chosen',
+ 'https://example.com/page',
+ 'https://example.com/page',
+ 'nav#main-nav',
+ [
+ { key: '$current_url', value: 'https://example.com/page', operator: 'exact', type: 'event' },
+ { key: 'selector', value: 'nav#main-nav', operator: 'exact', type: 'element' },
+ ],
+ ],
+ ])('builds %s', (_name, href, wildcardHref, areaSelector, expected) => {
+ expect(buildElementStatsProperties(href, wildcardHref, areaSelector)).toEqual(expected)
+ })
+ })
+
+ describe('resolveAreaTarget', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it.each([
+ ['snaps to the nearest semantic container', '<nav id="n"><ul><li id="leaf">x</li></ul></nav>', 'leaf', 'n'],
+ ['keeps a semantic container that is hovered directly', '<main id="m">x</main>', 'm', 'm'],
+ ['falls back to the hovered element when no container wraps it', '<div><b id="b">x</b></div>', 'b', 'b'],
+ [
+ 'snaps to a role-annotated container',
+ '<div role="navigation" id="r"><span id="s">x</span></div>',
+ 's',
+ 'r',
+ ],
+ ])('%s', (_name, html, hoveredId, expectedId) => {
+ document.body.innerHTML = html
+ const hovered = document.getElementById(hoveredId) as HTMLElement
+ expect(resolveAreaTarget(hovered).id).toBe(expectedId)
+ })
+ })
+
+ describe('resolveAreaElement', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it.each([
+ [
+ 'keeps the tracked element while it is connected',
+ (element: HTMLElement) => ({ element, selector: 'nav#other' }),
+ 'tracked',
+ ],
+ [
+ 'follows a replaced node via the stored selector',
+ (element: HTMLElement) => {
+ element.remove()
+ return { element, selector: 'nav#other' }
+ },
+ 'replacement',
+ ],
+ [
+ 'returns null when the node is gone and the selector matches nothing',
+ (element: HTMLElement) => {
+ element.remove()
+ return { element, selector: 'nav#gone' }
+ },
+ null,
+ ],
+ [
+ 'returns null when the node is gone and no selector was derived',
+ (element: HTMLElement) => {
+ element.remove()
+ return { element, selector: null }
+ },
+ null,
+ ],
+ [
+ 'returns null when the node is gone and the selector is not valid querySelector input',
+ (element: HTMLElement) => {
+ element.remove()
+ return { element, selector: ':::' }
+ },
+ null,
+ ],
+ ])('%s', (_name, buildFilter, expectedTestId) => {
+ document.body.innerHTML =
+ '<nav id="tracked" data-testid="tracked"></nav><nav id="other" data-testid="replacement"></nav>'
+ const tracked = document.getElementById('tracked') as HTMLElement
+ const filter = buildFilter(tracked)
+
+ const resolved = resolveAreaElement(filter)
+
+ expect(resolved?.dataset.testid ?? null).toBe(expectedTestId)
+ })
+ })
+
+ describe('stepAreaCandidate', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ function chain(rects: number[]): HTMLElement[] {
+ // builds body > el0 > el1 > ... where each element's mocked rect width is
+ // rects[i] (same-width neighbours simulate zero-layout wrapper divs)
+ const elements: HTMLElement[] = []
+ let parent: HTMLElement = document.body
+ rects.forEach((width, i) => {
+ const el = document.createElement('div')
+ el.id = `el${i}`
+ el.getBoundingClientRect = () =>
+ ({ top: 0, left: 0, width, height: 100, right: width, bottom: 100 }) as DOMRect
+ parent.appendChild(el)
+ elements.push(el)
+ parent = el
+ })
+ return elements
+ }
+
+ it.each([
+ ['up steps to the parent when it is bigger', [300, 200, 100], 2, 2, 'up', 1],
+ ['up skips same-size wrapper parents', [300, 200, 200, 200, 100], 4, 3, 'up', 0],
+ ['up stops below body when nothing bigger remains', [300], 0, 0, 'up', 0],
+ ['down steps back toward the anchor', [300, 200, 100], 2, 0, 'down', 1],
+ ['down skips same-size wrappers next to the candidate', [300, 300, 300, 100], 3, 0, 'down', 3],
+ ['down at the anchor stays put', [300, 200, 100], 2, 2, 'down', 2],
+ ] as const)('%s', (_name, rects, anchorIdx, candidateIdx, direction, expectedIdx) => {
+ const els = chain([...rects])
+ expect(stepAreaCandidate(els[anchorIdx], els[candidateIdx], direction)).toBe(els[expectedIdx])
+ })
+ })
+
+ describe('computeAreaCandidates', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ function addElement(
+ tag: string,
+ rect: { top: number; left: number; width: number; height: number },
+ parent: HTMLElement = document.body
+ ): HTMLElement {
+ const el = document.createElement(tag)
+ el.getBoundingClientRect = () =>
+ ({ ...rect, right: rect.left + rect.width, bottom: rect.top + rect.height }) as DOMRect
+ parent.appendChild(el)
+ return el
+ }
+
+ it('offers visible containers sorted biggest first, dropping too-small elements and non-containers', () => {
+ const big = addElement('div', { top: 0, left: 0, width: 800, height: 600 })
+ const nav = addElement('nav', { top: 0, left: 0, width: 200, height: 600 })
+ addElement('div', { top: 0, left: 0, width: 50, height: 20 }) // below the size floor
+ addElement('span', { top: 0, left: 0, width: 400, height: 400 }) // not a container tag
+
+ expect(computeAreaCandidates()).toEqual([big, nav])
+ })
+
+ it('collapses a same-rect wrapper chain to its deepest element', () => {
+ const outer = addElement('div', { top: 0, left: 0, width: 800, height: 600 })
+ const inner = addElement('div', { top: 0, left: 0, width: 800, height: 600 }, outer)
+ const distinct = addElement('div', { top: 0, left: 0, width: 400, height: 300 }, inner)
+
+ expect(computeAreaCandidates()).toEqual([inner, distinct])
+ })
+ })
+
+ describe('isInFixedContainer', () => {
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it.each([
+ ['a fixed element itself', 'fixed', 'self', true],
+ ['a sticky element itself', 'sticky', 'self', true],
+ ['a child of a fixed container', 'fixed', 'child', true],
+ ['a static element', 'static', 'self', false],
+ ])('detects %s', (_name, position, which, expected) => {
+ const container = document.createElement('div')
+ container.style.position = position
+ const child = document.createElement('span')
+ container.appendChild(child)
+ document.body.appendChild(container)
+ expect(isInFixedContainer(which === 'self' ? container : child)).toBe(expected)
+ })
+ })
+
describe('clickmap loading', () => {
let logic: ReturnType<typeof heatmapToolbarMenuLogic.build>
@@ -138,6 +352,37 @@ describe('heatmapToolbarMenuLogic', () => {
expect(logic.values.heatmapEnabled).toBe(true)
})
+ it('reloads the clickmap with the element selector filter when an area is chosen', async () => {
+ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions(['getElementStatsSuccess'])
+
+ const area = document.createElement('nav')
+ area.id = 'main-nav'
+ document.body.appendChild(area)
+ try {
+ await expectLogic(logic, () => logic.actions.selectHeatmapAreaFilter(area)).toDispatchActions([
+ 'setHeatmapAreaFilter',
+ 'getElementStatsSuccess',
+ ])
+
+ const lastCall = (toolbarApi.elementStats.list as jest.Mock).mock.calls.at(-1)[0]
+ expect(lastCall.properties).toContainEqual(
+ expect.objectContaining({
+ key: 'selector',
+ type: 'element',
+ value: expect.stringContaining('nav'),
+ })
+ )
+
+ await expectLogic(logic, () => logic.actions.selectHeatmapAreaFilter(null)).toDispatchActions([
+ 'getElementStatsSuccess',
+ ])
+ const clearedCall = (toolbarApi.elementStats.list as jest.Mock).mock.calls.at(-1)[0]
+ expect(clearedCall.properties).toHaveLength(1)
+ } finally {
+ area.remove()
+ }
+ })
+
it('retries the initial load via load more after a stats fetch failure', async () => {
jest.spyOn(toolbarApi.elementStats, 'list').mockRejectedValueOnce(new Error('network error'))
await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions(['getElementStatsFailure'])
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index e1e0954b218e..20f0bf1d8efd 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -7,6 +7,7 @@ import { collectAllElementsDeep } from 'query-selector-shadow-dom'
import type { PaginatedResponse } from 'lib/api'
import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'
+import { HeatmapBoundsFilter } from 'lib/components/heatmaps/types'
import { createVersionChecker } from 'lib/utils/semver'
import {
@@ -16,19 +17,230 @@ import {
matchEventToElementUsingIndex,
matchEventToElementUsingSelectors,
} from '~/toolbar/elements/domElementIndex'
+import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'
import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'
import { toolbarApi } from '~/toolbar/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'
-import { elementIsVisible, invalidateZoomCache, trimElement } from '~/toolbar/utils'
-import { PropertyFilterType, PropertyOperator } from '~/types'
+import {
+ elementIsVisible,
+ elementToActionStep,
+ getParent,
+ getToolbarRootElement,
+ invalidateZoomCache,
+ trimElement,
+} from '~/toolbar/utils'
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
import type { heatmapToolbarMenuLogicType } from './heatmapToolbarMenuLogicType'
export const doesVersionSupportScrollDepth = createVersionChecker('1.99')
const ELEMENT_STATS_PAGE_LIMIT = 5000
+
+// when picking an area to filter to, hovering snaps to the nearest of these semantic
+// containers so "the nav" or "the main content" is one click; anything else falls back
+// to the hovered element itself. The role variants cover framework/legacy markup that
+// skips the semantic tags.
+export const AREA_TARGET_SELECTOR = [
+ 'nav',
+ 'main',
+ 'header',
+ 'footer',
+ 'aside',
+ 'section',
+ 'article',
+ 'form',
+ '[role="navigation"]',
+ '[role="main"]',
+ '[role="banner"]',
+ '[role="contentinfo"]',
+].join(', ')
+
+export function resolveAreaTarget(target: HTMLElement): HTMLElement {
+ return (target.closest(AREA_TARGET_SELECTOR) as HTMLElement | null) ?? target
+}
+
+// area candidates smaller than this are noise — tiny elements stay reachable via the
+// arrow keys, and boxing them would bury the containers this mode exists to offer
+const AREA_CANDIDATE_MIN_WIDTH_PX = 80
+const AREA_CANDIDATE_MIN_HEIGHT_PX = 40
+// rendering cost cap: the biggest candidates are the useful ones, so drop the tail
+const AREA_CANDIDATE_LIMIT = 300
+
+// every plausible container on the page, rendered as simultaneous hover targets while
+// picking (the actions-inspector pattern): semantic containers plus any div that is
+// visibly its own region. Same-rect wrapper chains collapse to their deepest element,
+// and the result is sorted biggest-first so nested boxes paint children-on-top.
+export function computeAreaCandidates(): HTMLElement[] {
+ const toolbarRoot = getToolbarRootElement()
+ const visibilityCache = new WeakMap<HTMLElement, boolean>()
+ const byRectKey = new Map<string, { element: HTMLElement; area: number }>()
+
+ for (const element of collectAllElementsDeep('*', document) as HTMLElement[]) {
+ if (toolbarRoot?.contains(element) || !element.matches(`${AREA_TARGET_SELECTOR}, div`)) {
+ continue
+ }
+ const rect = element.getBoundingClientRect()
+ if (rect.width < AREA_CANDIDATE_MIN_WIDTH_PX || rect.height < AREA_CANDIDATE_MIN_HEIGHT_PX) {
+ continue
+ }
+ if (!elementIsVisible(element, visibilityCache)) {
+ continue
+ }
+ const key = `${Math.round(rect.top)}:${Math.round(rect.left)}:${Math.round(rect.width)}:${Math.round(rect.height)}`
+ // document order visits parents before children, so the last write per rect key
+ // keeps the deepest element of a zero-layout wrapper chain
+ byRectKey.set(key, { element, area: rect.width * rect.height })
+ }
+
+ return Array.from(byRectKey.values())
+ .sort((a, b) => b.area - a.area)
+ .slice(0, AREA_CANDIDATE_LIMIT)
+ .map(({ element }) => element)
+}
+
+function rectsMatch(a: DOMRect, b: DOMRect): boolean {
+ return (
+ Math.abs(a.top - b.top) < 1 &&
+ Math.abs(a.left - b.left) < 1 &&
+ Math.abs(a.width - b.width) < 1 &&
+ Math.abs(a.height - b.height) < 1
+ )
+}
+
+// arrow-key refinement of the hovered area: "up" grows the selection to the nearest
+// ancestor that is visibly bigger, "down" shrinks it back toward the exact hovered
+// element (the anchor). Same-size wrapper elements are skipped in both directions so
+// every step visibly changes the highlight on div-heavy pages.
+export function stepAreaCandidate(anchor: HTMLElement, candidate: HTMLElement, direction: 'up' | 'down'): HTMLElement {
+ const candidateRect = candidate.getBoundingClientRect()
+
+ if (direction === 'up') {
+ let next = getParent(candidate)
+ while (next && next !== document.body && rectsMatch(next.getBoundingClientRect(), candidateRect)) {
+ next = getParent(next)
+ }
+ return next && next !== document.body && next !== document.documentElement ? next : candidate
+ }
+
+ if (candidate === anchor) {
+ return candidate
+ }
+ // pointer hover keeps the anchor a descendant of the candidate, so the way down is
+ // the chain from the anchor up to just below the candidate; hovering an overlapping
+ // candidate box can break that, in which case the guard below makes "down" a no-op
+ const path: HTMLElement[] = []
+ let current: HTMLElement | null = anchor
+ while (current && current !== candidate) {
+ path.push(current)
+ current = getParent(current)
+ }
+ if (current !== candidate || path.length === 0) {
+ return candidate
+ }
+ let index = path.length - 1
+ while (index > 0 && rectsMatch(path[index].getBoundingClientRect(), candidateRect)) {
+ index--
+ }
+ return path[index]
+}
+
+export function buildElementStatsProperties(
+ href: string,
+ wildcardHref: string,
+ areaSelector: string | null
+): AnyPropertyFilter[] {
+ const properties: AnyPropertyFilter[] = [
+ wildcardHref === href
+ ? {
+ key: '$current_url',
+ value: href,
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ }
+ : {
+ key: '$current_url',
+ value: `^${wildcardHref.split('*').map(escapeUnescapedRegex).join('.*')}$`,
+ operator: PropertyOperator.Regex,
+ type: PropertyFilterType.Event,
+ },
+ ]
+ if (areaSelector) {
+ properties.push({
+ key: 'selector',
+ value: areaSelector,
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Element,
+ })
+ }
+ return properties
+}
+
+// mirrors how posthog-js decides target_fixed when recording heatmap points, so an area
+// and its points classify the same way
+export function isInFixedContainer(element: HTMLElement): boolean {
+ let current: HTMLElement | null = element
+ while (current) {
+ const position = window.getComputedStyle(current).position
+ if (position === 'fixed' || position === 'sticky') {
+ return true
+ }
+ current = getParent(current)
+ }
+ return false
+}
+
+// containment that follows shadow boundaries, unlike Node.contains — the clickmap matcher
+// deliberately matches elements inside shadow roots
+export function containsInComposedTree(container: HTMLElement, element: HTMLElement): boolean {
+ let current: HTMLElement | null = element
+ while (current) {
+ if (current === container) {
+ return true
+ }
+ current = getParent(current)
+ }
+ return false
+}
+
+function findElementBySelector(selector: string | null): HTMLElement | null {
+ if (!selector) {
+ return null
+ }
+ try {
+ return document.querySelector(selector) as HTMLElement | null
+ } catch {
+ // toolbar-derived selectors are not guaranteed to be valid querySelector input
+ return null
+ }
+}
+
+// the single rule for following a filter whose node a re-render replaced — shared by the
+// clickmap containment check and the bounds updater so the two can't resolve differently
+export function resolveAreaElement(filter: { element: HTMLElement; selector: string | null }): HTMLElement | null {
+ return filter.element.isConnected ? filter.element : findElementBySelector(filter.selector)
+}
+
+export function computeAreaBounds(element: HTMLElement): HeatmapBoundsFilter {
+ const rect = element.getBoundingClientRect()
+ const areaFixed = isInFixedContainer(element)
+ return {
+ areaFixed,
+ // fixed/sticky areas compare against viewport-recorded points, so keep the viewport
+ // rect; static areas compare against document-recorded points, so add the scroll offset
+ bounds: areaFixed
+ ? { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom }
+ : {
+ left: rect.left + window.scrollX,
+ right: rect.right + window.scrollX,
+ top: rect.top + window.scrollY,
+ bottom: rect.bottom + window.scrollY,
+ },
+ }
+}
+
// the follow-up fetch re-reads from offset 0 with a bigger limit rather than paginating:
// the server re-runs the full aggregation for any offset, so one big scan costs the same as
// a page and can't miss rows that shifted across page boundaries between scans
@@ -146,6 +358,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
'loadHeatmap',
'loadHeatmapSuccess',
'loadHeatmapFailure',
+ 'setHeatmapBoundsFilter',
],
],
})),
@@ -172,6 +385,18 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
setProcessedElements: (elements: CountedHTMLElement[]) => ({ elements }),
setElementsLoading: (loading: boolean) => ({ loading }),
setProcessingProgress: (processed: number, total: number) => ({ processed, total }),
+ startAreaSelection: true,
+ cancelAreaSelection: true,
+ setAreaHover: (anchor: HTMLElement, candidate: HTMLElement) => ({ anchor, candidate }),
+ setAreaHoverCandidate: (candidate: HTMLElement) => ({ candidate }),
+ stepAreaHover: (direction: 'up' | 'down') => ({ direction }),
+ setAreaCandidates: (candidates: HTMLElement[]) => ({ candidates }),
+ selectHeatmapAreaFilter: (element: HTMLElement | null) => ({ element }),
+ setHeatmapAreaFilter: (element: HTMLElement | null, selector: string | null) => ({ element, selector }),
+ // swap the tracked node for a re-resolved one without refetching: the selector is
+ // unchanged, so the server response would be byte-identical
+ rebindAreaElement: (element: HTMLElement) => ({ element }),
+ updateAreaBounds: true,
}),
windowValues(() => ({
windowWidth: (window: Window) => window.innerWidth,
@@ -179,6 +404,66 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
})),
reducers({
matchLinksByHref: [false, { setMatchLinksByHref: (_, { matchLinksByHref }) => matchLinksByHref }],
+ // exits picking mode only — an already-applied filter is cleared separately via
+ // selectHeatmapAreaFilter(null) (the snack's close button)
+ areaSelectionActive: [
+ false,
+ {
+ startAreaSelection: () => true,
+ cancelAreaSelection: () => false,
+ setHeatmapAreaFilter: () => false,
+ },
+ ],
+ // the raw element under the pointer; the fixed reference point arrow-key steps
+ // shrink back toward
+ areaHoverAnchor: [
+ null as HTMLElement | null,
+ {
+ setAreaHover: (_, { anchor }) => anchor,
+ startAreaSelection: () => null,
+ cancelAreaSelection: () => null,
+ setHeatmapAreaFilter: () => null,
+ },
+ ],
+ // the currently highlighted candidate: the semantic snap of the anchor by default,
+ // moved along the ancestor chain by arrow keys
+ areaHoverElement: [
+ null as HTMLElement | null,
+ {
+ setAreaHover: (_, { candidate }) => candidate,
+ setAreaHoverCandidate: (_, { candidate }) => candidate,
+ startAreaSelection: () => null,
+ cancelAreaSelection: () => null,
+ setHeatmapAreaFilter: () => null,
+ },
+ ],
+ areaHoverStepped: [
+ false,
+ {
+ setAreaHoverCandidate: () => true,
+ setAreaHover: () => false,
+ startAreaSelection: () => false,
+ cancelAreaSelection: () => false,
+ setHeatmapAreaFilter: () => false,
+ },
+ ],
+ areaCandidates: [
+ [] as HTMLElement[],
+ {
+ setAreaCandidates: (_, { candidates }) => candidates,
+ cancelAreaSelection: () => [],
+ setHeatmapAreaFilter: () => [],
+ },
+ ],
+ // cleared on disableHeatmap and navigation via the listeners dispatching
+ // setHeatmapAreaFilter(null, null), which also clears the pushed bounds
+ heatmapAreaFilter: [
+ null as { element: HTMLElement; selector: string | null } | null,
+ {
+ setHeatmapAreaFilter: (_, { element, selector }) => (element ? { element, selector } : null),
+ rebindAreaElement: (state, { element }) => (state ? { ...state, element } : state),
+ },
+ ],
lastElementStatsRequest: [
null as { url: string | null; limit: number } | null,
{
@@ -292,24 +577,11 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
await toolbarApi.elementStats.page(url, options)
: await toolbarApi.elementStats.list(
{
- properties: [
- wildcardHref === href
- ? {
- key: '$current_url',
- value: href,
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- }
- : {
- key: '$current_url',
- value: `^${wildcardHref
- .split('*')
- .map(escapeUnescapedRegex)
- .join('.*')}$`,
- operator: PropertyOperator.Regex,
- type: PropertyFilterType.Event,
- },
- ],
+ properties: buildElementStatsProperties(
+ href,
+ wildcardHref,
+ values.heatmapAreaFilter?.selector ?? null
+ ),
date_from: values.commonFilters.date_from,
date_to: values.commonFilters.date_to,
paginate_response: true,
@@ -403,27 +675,39 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
s.href,
s.matchLinksByHref,
s.clickmapsEnabled,
+ s.heatmapAreaFilter,
],
- (elementStats, dataAttributes, href, matchLinksByHref, clickmapsEnabled) => ({
+ (elementStats, dataAttributes, href, matchLinksByHref, clickmapsEnabled, heatmapAreaFilter) => ({
elementStats,
dataAttributes,
href,
matchLinksByHref,
clickmapsEnabled,
+ heatmapAreaFilter,
}),
],
})),
- subscriptions(({ actions }) => ({
- viewportRange: () => {
- actions.maybeLoadHeatmap()
- },
- })),
+ subscriptions(({ actions, values }) => {
+ const updateAreaBoundsIfFiltered = (): void => {
+ if (values.heatmapAreaFilter) {
+ actions.updateAreaBounds()
+ }
+ }
+ return {
+ viewportRange: () => {
+ actions.maybeLoadHeatmap()
+ },
+ windowWidth: updateAreaBoundsIfFiltered,
+ windowHeight: updateAreaBoundsIfFiltered,
+ }
+ }),
listeners(({ actions, values, cache }) => ({
processElements: async ({ trigger }, breakpoint) => {
const SLICE_BUDGET_MS = 10
const startedAt = performance.now()
- const { elementStats, dataAttributes, href, matchLinksByHref, clickmapsEnabled } = values.processingInputs
+ const { elementStats, dataAttributes, href, matchLinksByHref, clickmapsEnabled, heatmapAreaFilter } =
+ values.processingInputs
if (!clickmapsEnabled || !elementStats?.results?.length) {
actions.setProcessedElements([])
@@ -431,6 +715,16 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
return
}
+ // a re-render can replace the picked area node between mutation-observer ticks;
+ // re-resolve so the containment check keeps filtering across the swap
+ const areaElement = heatmapAreaFilter ? resolveAreaElement(heatmapAreaFilter) : null
+ if (heatmapAreaFilter && !areaElement) {
+ // unresolvable: hand off to the action that owns the clear-with-telemetry path
+ // now, rather than showing unfiltered rows until the mutation observer's
+ // debounce next fires (sustained DOM churn can push that back indefinitely)
+ actions.updateAreaBounds()
+ }
+
cache.visibilityCache = cache.visibilityCache || new WeakMap<HTMLElement, boolean>()
const cursorPointerCache = new WeakMap<HTMLElement, boolean>()
const { pageElements, domIndex, hasShadowRoots, cacheHit } = getCachedPageElements(
@@ -493,8 +787,15 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
if (matched) {
const trimmed = trimElement(matched.element, { cursorPointerCache })
+ // the server already filters chains by the area selector, but chains can
+ // match DOM nodes outside the chosen area (stale markup, repeated
+ // components), so keep the display honest with a containment check —
+ // composed-tree containment, since matches can live inside shadow roots
+ const withinArea =
+ !areaElement || (trimmed !== null && containsInComposedTree(areaElement, trimmed))
if (
trimmed &&
+ withinArea &&
elementIsVisible(trimmed, cache.visibilityCache as WeakMap<HTMLElement, boolean>)
) {
allTrimmedElements.push({ ...matched, element: trimmed })
@@ -542,9 +843,103 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
disableHeatmap: () => {
actions.resetElementStats()
actions.resetHeatmapData()
+ if (values.areaSelectionActive) {
+ actions.cancelAreaSelection()
+ }
+ // route the clear through the one action whose listener owns the
+ // "filter null => pushed bounds null" invariant
+ if (values.heatmapAreaFilter) {
+ actions.setHeatmapAreaFilter(null, null)
+ }
toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'heatmap', enabled: false })
},
+ // the feature flag gates only the menu button; the whole selection machine stays
+ // dormant because startAreaSelection is that button's only caller — a second caller
+ // would silently un-gate the feature
+ startAreaSelection: () => {
+ // product tours' picker also listens for document clicks; two armed pickers
+ // would both consume the same page click
+ const productTours = productToursLogic.findMounted()
+ if (productTours?.values.isSelecting) {
+ productTours.actions.setEditorState({ mode: 'idle' })
+ }
+ const candidates = computeAreaCandidates()
+ actions.setAreaCandidates(candidates)
+ toolbarPosthogJS.capture('toolbar heatmap area selection started', {
+ candidate_count: candidates.length,
+ capped: candidates.length === AREA_CANDIDATE_LIMIT,
+ })
+ },
+
+ stepAreaHover: ({ direction }) => {
+ const { areaHoverAnchor, areaHoverElement } = values
+ if (!areaHoverAnchor || !areaHoverElement) {
+ return
+ }
+ const next = stepAreaCandidate(areaHoverAnchor, areaHoverElement, direction)
+ if (next !== areaHoverElement) {
+ actions.setAreaHoverCandidate(next)
+ }
+ },
+
+ selectHeatmapAreaFilter: ({ element }) => {
+ const selector = element
+ ? elementToActionStep(element, toolbarConfigLogic.values.dataAttributes).selector || null
+ : null
+ const arrowStepped = values.areaHoverStepped
+ actions.setHeatmapAreaFilter(element, selector)
+ toolbarPosthogJS.capture('toolbar heatmap area filter changed', {
+ enabled: !!element,
+ has_selector: !!selector,
+ tag_name: element?.tagName.toLowerCase() ?? null,
+ trigger: 'user',
+ arrow_stepped: arrowStepped,
+ })
+ },
+
+ setHeatmapAreaFilter: ({ element }) => {
+ if (element) {
+ actions.updateAreaBounds()
+ } else {
+ actions.setHeatmapBoundsFilter(null)
+ }
+ // apply the containment check to the already-loaded stats immediately so the
+ // selection feels instant, then fetch the server-filtered data
+ actions.processElements('toggle')
+ actions.maybeLoadClickmap()
+ },
+
+ rebindAreaElement: () => {
+ actions.updateAreaBounds()
+ },
+
+ updateAreaBounds: () => {
+ const filter = values.heatmapAreaFilter
+ if (!filter) {
+ return
+ }
+ const resolved = resolveAreaElement(filter)
+ if (!resolved) {
+ // the node is gone and the selector no longer matches anything; clear the
+ // filter visibly rather than degrade silently
+ actions.setHeatmapAreaFilter(null, null)
+ toolbarPosthogJS.capture('toolbar heatmap area filter changed', {
+ enabled: false,
+ has_selector: !!filter.selector,
+ tag_name: filter.element.tagName.toLowerCase(),
+ trigger: 'element_lost',
+ })
+ return
+ }
+ if (resolved !== filter.element) {
+ // a re-render replaced the node; follow it via the stored selector
+ actions.rebindAreaElement(resolved)
+ return
+ }
+ actions.setHeatmapBoundsFilter(computeAreaBounds(filter.element))
+ },
+
startElementObservation: () => {
if (!cache.intersectionObserver || !values.clickmapsEnabled) {
return
@@ -586,6 +981,14 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
actions.setHrefMatchType(href === window.location.href ? 'exact' : 'pattern')
actions.setDataHref(href)
}
+ // the area filter describes an element on the page it was picked on; carrying it
+ // across navigation would filter the new page by the old page's selector and bounds
+ if (values.areaSelectionActive) {
+ actions.cancelAreaSelection()
+ }
+ if (values.heatmapAreaFilter) {
+ actions.setHeatmapAreaFilter(null, null)
+ }
actions.maybeLoadClickmap()
},
@@ -694,6 +1097,15 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
debounceTimer = setTimeout(() => {
invalidatePageElementsCache(cache as ElementProcessingCache)
invalidateZoomCache()
+ // mid-pick DOM churn would leave the candidate boxes pointing at stale nodes
+ if (values.areaSelectionActive) {
+ actions.setAreaCandidates(computeAreaCandidates())
+ }
+ // layout shifts move the filtered area; this also re-resolves or clears
+ // the filter when the picked node was replaced by a re-render
+ if (values.heatmapAreaFilter) {
+ actions.updateAreaBounds()
+ }
debounceTimer = null
}, 500)
})
@@ -713,6 +1125,74 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
}
}, 'mutationObserver')
+ cache.disposables.add(() => {
+ // capture-phase document listeners so area picking sees page elements before the
+ // page's own handlers do; guarded by areaSelectionActive so they cost nothing otherwise
+ const isToolbarElement = (element: HTMLElement): boolean =>
+ getToolbarRootElement()?.contains(element) ?? false
+
+ const onMouseOver = (e: MouseEvent): void => {
+ if (!values.areaSelectionActive) {
+ return
+ }
+ const target = e.target as HTMLElement | null
+ if (!target || isToolbarElement(target)) {
+ return
+ }
+ // moving the mouse resets any arrow-key refinement to the new hover's snap
+ actions.setAreaHover(target, resolveAreaTarget(target))
+ }
+
+ const onClick = (e: MouseEvent): void => {
+ if (!values.areaSelectionActive) {
+ return
+ }
+ const target = e.target as HTMLElement | null
+ if (!target || isToolbarElement(target)) {
+ return
+ }
+ e.preventDefault()
+ e.stopPropagation()
+ // the highlighted candidate, not the click target: arrow keys may have
+ // grown or shrunk the selection away from what's under the pointer
+ actions.selectHeatmapAreaFilter(values.areaHoverElement ?? resolveAreaTarget(target))
+ }
+
+ const onKeyDown = (e: KeyboardEvent): void => {
+ if (!values.areaSelectionActive || (e.key !== 'ArrowUp' && e.key !== 'ArrowDown')) {
+ return
+ }
+ // focus usually sits on the toolbar button that started the pick, and shadow
+ // retargeting turns document-level targets into the toolbar host, so a
+ // toolbar-membership guard would eat every arrow key; guard on the composed
+ // target instead — arrows step the highlight unless the user is typing or
+ // navigating a menu (Lemon dropdowns are ARIA menus, not native selects)
+ const composedTarget = e.composedPath()[0]
+ if (
+ composedTarget instanceof HTMLElement &&
+ (composedTarget.isContentEditable ||
+ composedTarget.closest(
+ 'input, textarea, select, [role="listbox"], [role="menu"], [role="option"], [role="menuitem"]'
+ ))
+ ) {
+ return
+ }
+ // arrows refine the selection, so they must not scroll the page mid-pick
+ e.preventDefault()
+ e.stopPropagation()
+ actions.stepAreaHover(e.key === 'ArrowUp' ? 'up' : 'down')
+ }
+
+ document.addEventListener('mouseover', onMouseOver, true)
+ document.addEventListener('click', onClick, true)
+ document.addEventListener('keydown', onKeyDown, true)
+ return () => {
+ document.removeEventListener('mouseover', onMouseOver, true)
+ document.removeEventListener('click', onClick, true)
+ document.removeEventListener('keydown', onKeyDown, true)
+ }
+ }, 'areaSelectionListeners')
+
cache.disposables.add(() => {
const handleVisibilityChange = (): void => {
if (document.hidden) {
@@ -729,6 +1209,8 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
}, 'visibilityChangeHandler')
}),
beforeUnmount(({ cache }) => {
+ // heatmapDataLogic outlives this logic, so reducer resets alone can't clear the bounds
+ heatmapDataLogic.findMounted({ context: 'toolbar' })?.actions.setHeatmapBoundsFilter(null)
cache.pageElements = undefined
cache.selectorToElements = new Map()
cache.matchedElementByIdentity = new Map()
diff --git a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx
index cabfe1696e63..17b575c62fdd 100644
--- a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx
+++ b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx
@@ -2,8 +2,8 @@ import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import React from 'react'
-import { IconMagicWand } from '@posthog/icons'
-import { LemonButton, LemonSwitch, Link } from '@posthog/lemon-ui'
+import { IconMagicWand, IconTarget } from '@posthog/icons'
+import { LemonButton, LemonSnack, LemonSwitch, Link } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { HeatmapsSettings } from 'lib/components/heatmaps/HeatMapsSettings'
@@ -20,6 +20,7 @@ import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'
import { elementsLogic } from '~/toolbar/elements/elementsLogic'
import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'
import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'
+import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'
import { joinWithUiHost } from '~/toolbar/utils'
import { toolbarConfigLogic } from '../toolbarConfigLogic'
@@ -83,6 +84,7 @@ const SectionButton = ({
export const HeatmapToolbarMenu = (): JSX.Element => {
const { wildcardHref, autoWildcardEnabled } = useValues(currentPageLogic)
const { setWildcardHref, autoWildcardHref, setAutoWildcardEnabled } = useActions(currentPageLogic)
+ const areaFilterFlagEnabled = useToolbarFeatureFlag('toolbar-heatmap-area-filter')
const {
matchLinksByHref,
@@ -101,6 +103,8 @@ export const HeatmapToolbarMenu = (): JSX.Element => {
samplingFactor,
elementsLoading,
processingProgress,
+ areaSelectionActive,
+ heatmapAreaFilter,
} = useValues(heatmapToolbarMenuLogic)
const {
setCommonFilters,
@@ -111,6 +115,9 @@ export const HeatmapToolbarMenu = (): JSX.Element => {
setHeatmapFixedPositionMode,
setHeatmapColorPalette,
setSamplingFactor,
+ startAreaSelection,
+ cancelAreaSelection,
+ selectHeatmapAreaFilter,
} = useActions(heatmapToolbarMenuLogic)
const { setHighlightElement, setSelectedElement } = useActions(elementsLogic)
@@ -167,7 +174,43 @@ export const HeatmapToolbarMenu = (): JSX.Element => {
}}
dateOptions={heatmapDateOptions}
/>
+ {areaFilterFlagEnabled ? (
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconTarget />}
+ active={areaSelectionActive}
+ data-attr="heatmap-area-filter-toggle"
+ onClick={() => (areaSelectionActive ? cancelAreaSelection() : startAreaSelection())}
+ tooltip={
+ <>
+ Filter the heatmap and clickmap to one part of the page, e.g. the nav or the main
+ content. Click this, then hover the page and click an area. Press <kbd>↑</kbd> to
+ grow the selection to a bigger container, <kbd>↓</kbd> to shrink it, and{' '}
+ <kbd>Esc</kbd> to cancel. Heatmap points on fixed or sticky elements are only
+ included when the chosen area is itself fixed or sticky.
+ </>
+ }
+ >
+ {areaSelectionActive ? 'Click an area of the page…' : 'Filter to area'}
+ </LemonButton>
+ ) : null}
</div>
+ {heatmapAreaFilter && !areaSelectionActive ? (
+ <div className="flex flex-row items-center gap-2 py-2 border-b">
+ <span className="text-muted text-xs">Filtered to</span>
+ <LemonSnack
+ className="font-mono text-xs shrink min-w-0 truncate"
+ title={
+ heatmapAreaFilter.selector ??
+ 'No unique selector could be derived for this element, so the clickmap is filtered client-side only and may be limited to the loaded data.'
+ }
+ onClose={() => selectHeatmapAreaFilter(null)}
+ >
+ {heatmapAreaFilter.selector ?? `<${heatmapAreaFilter.element.tagName.toLowerCase()}>`}
+ </LemonSnack>
+ </div>
+ ) : null}
</ToolbarMenu.Header>
<ToolbarMenu.Body>
<div className="border-b p-2">