: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): resolve clickmap element ties with href and text (#93748)
Jordan Mryyan0da330787ebd
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex a630ed7b3133..ba724f09451c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -218,6 +218,8 @@ export const FEATURE_FLAGS = {BOX_PLOT_INSIGHT: 'box-plot-insight', // owner: @pauldambra #team-product-analyticsEXPERIMENT_INTERVAL_TIMESERIES: 'experiments-interval-timeseries', // owner: @jurajmajerik #team-experimentsGATEWAY_PERSONAL_API_KEY: 'gateway-personal-api-key', // owner: #team-platform-features+ HEATMAPS_CLICKMAP_DISCRIMINATORS: 'heatmaps-clickmap-discriminators', // owner: #team-web-analytics+ HEATMAPS_CLICKMAP_PAGINATION: 'heatmaps-clickmap-pagination', // owner: #team-web-analyticsHEATMAPS_COHORT_FILTER: 'heatmaps-cohort-filter', // owner: #team-web-analyticsHEATMAPS_CREATION_FLOW: 'heatmaps-creation-flow', // owner: #team-web-analytics, gates the guided heatmap creation wizard at /heatmaps/newHEATMAPS_EVENT_FILTER: 'heatmaps-event-filter', // owner: #team-web-analyticsdiff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.tsindex d9e608857eee..643ff933081a 100644--- a/frontend/src/lib/utils/async.ts+++ b/frontend/src/lib/utils/async.ts@@ -171,3 +171,28 @@ export function debounce<F extends (...args: Parameters<F>) => ReturnType<F>>(timeout = setTimeout(() => func(...args), waitFor)}}++export function yieldToMain(): Promise<void> {+ return new Promise((resolve) => {+ if (typeof (window as any).scheduler?.yield === 'function') {+ ;(window as any).scheduler.yield().then(resolve)+ } else if (typeof window.requestIdleCallback === 'function') {+ window.requestIdleCallback(() => resolve(), { timeout: 50 })+ } else {+ setTimeout(resolve, 0)+ }+ })+}++export function createSliceYielder(budgetMs: number = 10): (beforeYield?: () => void) => Promise<boolean> {+ let sliceStart = performance.now()+ return async (beforeYield?: () => void): Promise<boolean> => {+ if (performance.now() - sliceStart <= budgetMs) {+ return false+ }+ beforeYield?.()+ await yieldToMain()+ sliceStart = performance.now()+ return true+ }+}diff --git a/frontend/src/toolbar/elements/domElementIndex.test.ts b/frontend/src/toolbar/elements/domElementIndex.test.tsindex 305cb1a090d2..a551d8aafc81 100644--- a/frontend/src/toolbar/elements/domElementIndex.test.ts+++ b/frontend/src/toolbar/elements/domElementIndex.test.ts@@ -1,8 +1,14 @@import { collectAllElementsDeep } from 'query-selector-shadow-dom'import { ElementsEventType } from '~/toolbar/types'+import { ElementType } from '~/types'-import { buildDOMIndex, matchEventToElementUsingIndex, matchEventToElementUsingSelectors } from './domElementIndex'+import {+ buildDOMIndex,+ matchEventToElementUsingIndex,+ matchEventToElementUsingSelectors,+ matchIsChainConsistent,+} from './domElementIndex'function createTestDOM(html: string): { container: HTMLElement; cleanup: () => void } {const container = document.createElement('div')@@ -178,7 +184,7 @@ describe('domElementIndex', () => {const { container, cleanup } = createTestDOM(html)try {const index = buildDOMIndex(getAllElements(container))- const result = matchEventToElementUsingIndex(createEvent([event]), [], false, index)+ const result = matchEventToElementUsingIndex(createEvent([event]), index)if (shouldMatch) {expect(result).not.toBeNull()@@ -216,7 +222,7 @@ describe('domElementIndex', () => {const { container, cleanup } = createTestDOM(html)try {const index = buildDOMIndex(getAllElements(container))- const result = matchEventToElementUsingIndex(createEvent([event]), [], false, index)+ const result = matchEventToElementUsingIndex(createEvent([event]), index)if (shouldMatch) {expect(result).not.toBeNull()@@ -247,7 +253,7 @@ describe('domElementIndex', () => {const { container, cleanup } = createTestDOM(html)try {const index = buildDOMIndex(getAllElements(container))- const result = matchEventToElementUsingIndex(createEvent([event]), [], false, index)+ const result = matchEventToElementUsingIndex(createEvent([event]), index)expect(result).not.toBeNull()expect(result?.element.id).toBe(expectedId)@@ -370,7 +376,7 @@ describe('domElementIndex', () => {const { container, cleanup } = createTestDOM(html)try {const index = buildDOMIndex(getAllElements(container))- const result = matchEventToElementUsingIndex(createEvent(event), dataAttributes, false, index)+ const result = matchEventToElementUsingIndex(createEvent(event), index, { dataAttributes })expect(result).not.toBeNull()expect(result?.element.id).toBe('target')@@ -379,12 +385,119 @@ describe('domElementIndex', () => {}})+ const discriminatorCases = [+ {+ name: 'breaks a structural tie using the captured href',+ html: `+ <nav class="menu">+ <a class="item" id="decoy" href="/reports"></a>+ <a class="item" id="target" href="/settings"></a>+ </nav>+ `,+ event: [+ { tag_name: 'a', attr_class: ['item'], href: '/settings' },+ { tag_name: 'nav', attr_class: ['menu'] },+ ],+ expectedId: 'target',+ expectedIdWhenOff: null,+ },+ {+ name: 'breaks a structural tie using the captured text when there is no href',+ html: `+ <div class="toolbar">+ <button class="btn" id="decoy">Save</button>+ <button class="btn" id="target">Delete</button>+ </div>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'], text: 'Delete' },+ { tag_name: 'div', attr_class: ['toolbar'] },+ ],+ expectedId: 'target',+ expectedIdWhenOff: null,+ },+ {+ name: 'rejects a lone survivor the chain contradicts and resolves the real element',+ html: `+ <nav class="group"><a class="item" id="target" href="/reports">Reports</a></nav>+ <nav class="group expanded"><a class="item" id="decoy" href="/settings">Settings</a></nav>+ `,+ event: [+ { tag_name: 'a', attr_class: ['item'], href: '/reports', text: 'Reports' },+ { tag_name: 'nav', attr_class: ['group', 'expanded'] },+ ],+ expectedId: 'target',+ expectedIdWhenOff: 'decoy',+ },+ {+ name: 'returns null rather than attributing to an element the chain contradicts',+ html: `+ <nav class="group"><a class="item" href="/reports">Reports</a></nav>+ <nav class="group expanded"><a class="item" id="decoy" href="/settings">Settings</a></nav>+ `,+ event: [+ { tag_name: 'a', attr_class: ['item'], href: '/archive', text: 'Archive' },+ { tag_name: 'nav', attr_class: ['group', 'expanded'] },+ ],+ expectedId: null,+ expectedIdWhenOff: 'decoy',+ },+ {+ name: 'narrows by href first, then breaks the remaining tie with the captured text',+ html: `+ <nav class="menu">+ <a class="item" id="other" href="/pricing">Getting started</a>+ <a class="item" id="decoy" href="/docs">API reference</a>+ <a class="item" id="target" href="/docs">Getting started</a>+ </nav>+ `,+ event: [+ { tag_name: 'a', attr_class: ['item'], href: '/docs', text: 'Getting started' },+ { tag_name: 'nav', attr_class: ['menu'] },+ ],+ expectedId: 'target',+ expectedIdWhenOff: null,+ },+ {+ name: 'still matches when captured text is truncated relative to the live DOM',+ html: `+ <div class="toolbar">+ <button class="btn" id="decoy">Discard all unsaved changes</button>+ <button class="btn" id="target">Publish every pending revision</button>+ </div>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'], text: 'Publish every' },+ { tag_name: 'div', attr_class: ['toolbar'] },+ ],+ expectedId: 'target',+ expectedIdWhenOff: null,+ },+ ]++ it.each(+ discriminatorCases.flatMap(({ expectedId, expectedIdWhenOff, ...rest }) => [+ { ...rest, useDiscriminators: true, expected: expectedId },+ { ...rest, useDiscriminators: false, expected: expectedIdWhenOff },+ ])+ )('$name (useDiscriminators=$useDiscriminators)', ({ html, event, useDiscriminators, expected }) => {+ const { container, cleanup } = createTestDOM(html)+ try {+ const index = buildDOMIndex(getAllElements(container))+ const result = matchEventToElementUsingIndex(createEvent(event), index, { useDiscriminators })++ expect(result?.element.id ?? null).toBe(expected)+ } finally {+ cleanup()+ }+ })+it('applies isTooSimple check for generic elements', () => {const { container, cleanup } = createTestDOM('<div><div></div></div>')try {const index = buildDOMIndex(getAllElements(container))const event = createEvent([{ tag_name: 'div', nth_child: 1, nth_of_type: 1 }])- const result = matchEventToElementUsingIndex(event, [], false, index)+ const result = matchEventToElementUsingIndex(event, index)expect(result).toBeNull()} finally {@@ -397,7 +510,7 @@ describe('domElementIndex', () => {try {const index = buildDOMIndex(getAllElements(container))const event = createEvent([{ tag_name: 'div', attr_class: ['content'], nth_child: 1, nth_of_type: 1 }])- const result = matchEventToElementUsingIndex(event, [], false, index)+ const result = matchEventToElementUsingIndex(event, index)expect(result).not.toBeNull()} finally {@@ -410,7 +523,7 @@ describe('domElementIndex', () => {try {const index = buildDOMIndex(getAllElements(container))const event = createEvent([])- const result = matchEventToElementUsingIndex(event, [], false, index)+ const result = matchEventToElementUsingIndex(event, index)expect(result).toBeNull()} finally {@@ -423,7 +536,7 @@ describe('domElementIndex', () => {try {const index = buildDOMIndex(getAllElements(container))const event = createEvent([{ attr_id: 'target' }], { count: 42, type: '$rageclick' })- const result = matchEventToElementUsingIndex(event, [], false, index)+ const result = matchEventToElementUsingIndex(event, index)expect(result?.count).toBe(42)expect(result?.type).toBe('$rageclick')@@ -540,7 +653,10 @@ describe('domElementIndex', () => {const eventObj = createEvent(event)- const indexResult = matchEventToElementUsingIndex(eventObj, dataAttributes, true, index)+ const indexResult = matchEventToElementUsingIndex(eventObj, index, {+ dataAttributes,+ matchLinksByHref: true,+ })const selectorResult = matchEventToElementUsingSelectors(eventObj,dataAttributes,@@ -564,4 +680,79 @@ describe('domElementIndex', () => {})})++ describe('matchIsChainConsistent', () => {+ const consistencyCases = [+ {+ name: 'accepts an element whose whole ancestor path matches the chain',+ html: '<nav class="group"><a class="item" id="target" href="/reports">Reports</a></nav>',+ selector: '#target',+ chain: [+ { tag_name: 'a', attr_id: 'target', nth_child: 1, nth_of_type: 1 },+ { tag_name: 'nav', nth_child: 1, nth_of_type: 1 },+ ],+ expected: true,+ },+ {+ name: 'rejects an element sitting at a different ancestor position',+ html: `+ <div><nav class="group"><a class="item" href="/reports"></a></nav>+ <nav class="group"><a class="item" id="decoy" href="/settings"></a></nav></div>+ `,+ selector: '#decoy',+ chain: [+ { tag_name: 'a', nth_child: 1, nth_of_type: 1 },+ { tag_name: 'nav', nth_child: 1, nth_of_type: 1 },+ ],+ expected: false,+ },+ {+ name: 'ignores classes so legitimate class drift is not counted as misattribution',+ html: '<nav class="group expanded ng-star-inserted"><a class="item extra" id="target"></a></nav>',+ selector: '#target',+ chain: [+ { tag_name: 'a', nth_child: 1, nth_of_type: 1 },+ { tag_name: 'nav', nth_child: 1, nth_of_type: 1 },+ ],+ expected: true,+ },+ {+ name: 'rejects a chain deeper than the live ancestor path',+ html: '<nav><a id="target"></a></nav>',+ selector: '#target',+ chain: [+ { tag_name: 'a' },+ { tag_name: 'nav' },+ { tag_name: 'section' },+ { tag_name: 'main' },+ { tag_name: 'div' },+ { tag_name: 'div' },+ ],+ expected: false,+ },+ {+ name: 'ignores href and text so the measure stays independent of how the match was chosen',+ html: '<nav><a id="target" href="/actual">Actual</a></nav>',+ selector: '#target',+ chain: [+ { tag_name: 'a', href: '/different', text: 'Different', nth_child: 1, nth_of_type: 1 },+ { tag_name: 'nav', nth_child: 1, nth_of_type: 1 },+ ],+ expected: true,+ },+ ]++ it.each(consistencyCases)('$name', ({ html, selector, chain, expected }) => {+ const { container, cleanup } = createTestDOM(html)+ try {+ const element = container.querySelector<HTMLElement>(selector)!+ const elements = chain.map((level) => ({ attributes: {}, ...level })) as ElementType[]+ const index = buildDOMIndex(getAllElements(container))++ expect(matchIsChainConsistent(element, elements, index)).toBe(expected)+ } finally {+ cleanup()+ }+ })+ })})diff --git a/frontend/src/toolbar/elements/domElementIndex.ts b/frontend/src/toolbar/elements/domElementIndex.tsindex 7b7de1e7adcf..e6f84d490d2c 100644--- a/frontend/src/toolbar/elements/domElementIndex.ts+++ b/frontend/src/toolbar/elements/domElementIndex.ts@@ -252,6 +252,102 @@ function fingerprintMatchesEventElement(return identifiedWithoutPosition || matchesPosition(fingerprint, eventElement)}+const normalizeText = (text: string | null | undefined): string => (text ?? '').replace(/\s+/g, ' ').trim()++function textCompatible(capturedText: string, element: HTMLElement): boolean {+ const live = normalizeText(element.textContent)+ if (!live) {+ return true+ }+ return capturedText === live || capturedText.startsWith(live) || live.startsWith(capturedText)+}++function hrefCompatible(element: HTMLElement, eventElement: ElementType): boolean {+ return !eventElement.href || element.getAttribute('href') === eventElement.href+}++function discriminateCandidates(+ candidates: HTMLElement[],+ eventElement: ElementType,+ capturedText: string+): HTMLElement[] {+ let remaining = candidates+ if (remaining.length > 1 && eventElement.href) {+ const byHref = remaining.filter((element) => hrefCompatible(element, eventElement))+ if (byHref.length) {+ remaining = byHref+ }+ }+ if (remaining.length > 1 && capturedText) {+ const byText = remaining.filter((element) => textCompatible(capturedText, element))+ if (byText.length === 1) {+ remaining = byText+ }+ }+ return remaining+}++function resolveMatchedElement(+ walkers: { candidate: HTMLElement }[],+ candidates: HTMLElement[],+ eventElement: ElementType,+ useDiscriminators: boolean+): HTMLElement | null {+ const chainMatch = walkers.length === 1 ? walkers[0].candidate : null+ if (!useDiscriminators) {+ return chainMatch+ }+ const capturedText = normalizeText(eventElement.text)+ if (+ chainMatch &&+ hrefCompatible(chainMatch, eventElement) &&+ (!capturedText || textCompatible(capturedText, chainMatch))+ ) {+ return chainMatch+ }+ const pool = walkers.length > 1 ? walkers.map((walker) => walker.candidate) : candidates+ const narrowed = discriminateCandidates(pool, eventElement, capturedText)+ return narrowed.length === 1 ? narrowed[0] : null+}++function liveNodeMatchesLevel(node: HTMLElement, level: ElementType, index: DOMIndex): boolean {+ const fingerprint = index.fingerprints.get(node)+ if (level.tag_name && (fingerprint?.tagName ?? node.tagName.toLowerCase()) !== level.tag_name.toLowerCase()) {+ return false+ }+ if (level.attr_id && node.id !== level.attr_id) {+ return false+ }+ return !fingerprint || !node.parentElement || matchesPosition(fingerprint, level)+}++export function matchIsChainConsistent(element: HTMLElement, chain: ElementType[], index: DOMIndex): boolean {+ let node: HTMLElement | null = element+ for (const level of chain) {+ if (!node || !liveNodeMatchesLevel(node, level, index)) {+ return false+ }+ node = node.parentElement+ }+ return true+}++export function chainConsistencyProperties(counts: {+ useDiscriminators: boolean+ consistentClicks: number+ inconsistentClicks: number+ matchedClicks: number+ totalClicks: number+}): Record<string, boolean | number> {+ return {+ discriminators_enabled: counts.useDiscriminators,+ consistent_click_count: counts.consistentClicks,+ inconsistent_click_count: counts.inconsistentClicks,+ matched_click_count: counts.matchedClicks,+ total_click_count: counts.totalClicks,+ }+}+export function isTooSimple(element: ElementType): boolean {return !!(element.tag_name &&@@ -265,11 +361,16 @@ export function isTooSimple(element: ElementType): boolean {)}+export interface ElementMatchOptions {+ dataAttributes?: string[]+ matchLinksByHref?: boolean+ useDiscriminators?: boolean+}+export function matchEventToElementUsingIndex(event: ElementsEventType,- dataAttributes: string[],- matchLinksByHref: boolean,- index: DOMIndex+ index: DOMIndex,+ { dataAttributes = [], matchLinksByHref = false, useDiscriminators = false }: ElementMatchOptions = {}): CountedHTMLElement | null {const targetElement = event.elements[0]if (!targetElement) {@@ -297,9 +398,11 @@ export function matchEventToElementUsingIndex(})}- if (walkers.length === 1 && !isTooSimple(targetElement)) {+ const resolved = resolveMatchedElement(walkers, candidates, targetElement, useDiscriminators)++ if (resolved && !isTooSimple(targetElement)) {return {- element: walkers[0].candidate,+ element: resolved,count: event.count,selector: '',hash: event.hash,diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex a027ca22501d..1c1ae47b91b6 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -19,14 +19,18 @@ 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 { FEATURE_FLAGS } from 'lib/constants'+import { createSliceYielder } from 'lib/utils/async'import { createVersionChecker } from 'lib/utils/semver'import {DOMIndex,buildDOMIndex,+ chainConsistencyProperties,hasNonToolbarShadowRoots,matchEventToElementUsingIndex,matchEventToElementUsingSelectors,+ matchIsChainConsistent,} from '~/toolbar/elements/domElementIndex'import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'@@ -260,18 +264,6 @@ export function computeAreaBounds(element: HTMLElement): HeatmapBoundsFilter {// a page and can't miss rows that shifted across page boundaries between scansconst ELEMENT_STATS_AUTO_LOAD_LIMIT = 50000-function yieldToMain(): Promise<void> {- return new Promise((resolve) => {- if ('scheduler' in window && typeof (window as any).scheduler?.yield === 'function') {- ;(window as any).scheduler.yield().then(resolve)- } else if (typeof (window as any).requestIdleCallback === 'function') {- ;(window as any).requestIdleCallback(() => resolve(), { timeout: 50 })- } else {- setTimeout(resolve, 0)- }- })-}-export type ClickmapProcessingTrigger = 'initial' | 'auto-load' | 'pagination' | 'refresh' | 'toggle'interface ElementProcessingCache {@@ -1056,7 +1048,6 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}),listeners(({ actions, values, cache }) => ({processElements: async ({ trigger }, breakpoint) => {- const SLICE_BUDGET_MS = 10const startedAt = performance.now()const { elementStats, dataAttributes, href, matchLinksByHref, clickmapsEnabled, heatmapAreaFilter } =@@ -1084,16 +1075,19 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([cache as ElementProcessingCache,href)+ const useDiscriminators = !!toolbarPosthogJS.getFeatureFlag(FEATURE_FLAGS.HEATMAPS_CLICKMAP_DISCRIMINATORS)const eventsToProcess = elementStats.resultsconst totalEvents = eventsToProcess.lengthconst matchedElementByIdentity = (cache as ElementProcessingCache).matchedElementByIdentityconst allTrimmedElements: CountedHTMLElement[] = []+ let consistentClicks = 0+ let inconsistentClicks = 0let indexMatchedCount = 0let fallbackMatchedCount = 0let matchCacheHitCount = 0let completed = false- let sliceStart = performance.now()+ const maybeYield = createSliceYielder()try {for (let i = 0; i < totalEvents; i++) {@@ -1117,7 +1111,11 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}: null} else {- matched = matchEventToElementUsingIndex(event, dataAttributes, matchLinksByHref, domIndex)+ matched = matchEventToElementUsingIndex(event, domIndex, {+ dataAttributes,+ matchLinksByHref,+ useDiscriminators,+ })if (matched) {indexMatchedCount += 1} else {@@ -1139,6 +1137,11 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}if (matched) {+ if (matchIsChainConsistent(matched.element, event.elements, domIndex)) {+ consistentClicks += event.count+ } else {+ inconsistentClicks += event.count+ }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@@ -1155,11 +1158,8 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}}- if (performance.now() - sliceStart > SLICE_BUDGET_MS) {- actions.setProcessingProgress(i + 1, totalEvents)- await yieldToMain()+ if (await maybeYield(() => actions.setProcessingProgress(i + 1, totalEvents))) {breakpoint()- sliceStart = performance.now()}}@@ -1183,6 +1183,13 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([trigger,cache_hit: cacheHit,completed,+ ...chainConsistencyProperties({+ useDiscriminators,+ consistentClicks,+ inconsistentClicks,+ matchedClicks: allTrimmedElements.reduce((total, element) => total + element.count, 0),+ totalClicks: eventsToProcess.reduce((total, row) => total + row.count, 0),+ }),})}},diff --git a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.tsindex 1e578f528c08..484970187a05 100644--- a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts+++ b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.test.ts@@ -71,8 +71,8 @@ describe('recordingClickmapLogic', () => {jest.restoreAllMocks()})- it('aggregates counts per event type from chains resolving to the same element', () => {- const boxes = computeClickmapBoxes(+ it('aggregates counts per event type from chains resolving to the same element', async () => {+ const { boxes } = await computeClickmapBoxes([statsRow({ count: 10 }),statsRow({ count: 3, hash: 'rage', type: '$rageclick' }),@@ -80,7 +80,7 @@ describe('recordingClickmapLogic', () => {],snapshotDocument,null,- ['data-attr']+ { dataAttributes: ['data-attr'] })expect(boxes).toHaveLength(1)expect(boxes[0]).toMatchObject({@@ -93,8 +93,8 @@ describe('recordingClickmapLogic', () => {})})- it('produces one box per matched element, sorted by count descending', () => {- const boxes = computeClickmapBoxes(+ it('produces one box per matched element, sorted by count descending', async () => {+ const { boxes } = await computeClickmapBoxes([statsRow({ count: 2 }),statsRow({@@ -113,13 +113,13 @@ describe('recordingClickmapLogic', () => {],snapshotDocument,null,- ['data-attr']+ { dataAttributes: ['data-attr'] })expect(boxes.map((box) => box.count)).toEqual([9, 2])})- it('drops chains that match nothing in the snapshot', () => {- const boxes = computeClickmapBoxes(+ it('drops chains that match nothing in the snapshot', async () => {+ const { boxes } = await computeClickmapBoxes([statsRow({count: 5,@@ -128,17 +128,17 @@ describe('recordingClickmapLogic', () => {],snapshotDocument,null,- ['data-attr']+ { dataAttributes: ['data-attr'] })expect(boxes).toHaveLength(0)})- it('offsets boxes by the snapshot scroll position', () => {- const boxes = computeClickmapBoxes(+ it('offsets boxes by the snapshot scroll position', async () => {+ const { boxes } = await computeClickmapBoxes([statsRow({ count: 1 })],snapshotDocument,{ scrollX: 5, scrollY: 200 },- ['data-attr']+ { dataAttributes: ['data-attr'] })expect(boxes[0]).toMatchObject({ top: 210, left: 25 })})diff --git a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.tsindex a2a15e1a0483..33eef1a904ef 100644--- a/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts+++ b/products/web_analytics/frontend/heatmaps/components/recordingClickmapLogic.ts@@ -10,10 +10,17 @@ import type { CommonFilters } from 'lib/components/heatmaps/types'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { createSliceYielder } from 'lib/utils/async'import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'-import { buildDOMIndex, matchEventToElementUsingIndex } from '~/toolbar/elements/domElementIndex'+import {+ buildDOMIndex,+ chainConsistencyProperties,+ matchEventToElementUsingIndex,+ matchIsChainConsistent,+} from '~/toolbar/elements/domElementIndex'+import type { ElementMatchOptions } from '~/toolbar/elements/domElementIndex'import { escapeUnescapedRegex } from '~/toolbar/elements/heatmapToolbarMenuLogic'import { ElementsEventType } from '~/toolbar/types'import { PropertyFilterType, PropertyOperator } from '~/types'@@ -46,6 +53,7 @@ export type RecordingClickmapLogicProps = {}const CLICKMAP_STATS_LIMIT = 500+const CLICKMAP_STATS_AUTO_LOAD_LIMIT = 10000function currentUrlProperty(href: string, isPattern: boolean): Record<string, unknown> {return isPattern@@ -72,7 +80,8 @@ export function buildElementStatsParams(filter_test_accounts?: booleancohort_ids?: number[]},- dataAttributes: string[]+ dataAttributes: string[],+ limit: number = CLICKMAP_STATS_LIMIT): ElementsStatsRetrieveParams {const properties: Record<string, unknown>[] = [currentUrlProperty(href, isPattern)]for (const cohortId of commonFilters.cohort_ids ?? []) {@@ -90,12 +99,14 @@ export function buildElementStatsParams(date_from: commonFilters.date_from,date_to: commonFilters.date_to,filter_test_accounts: commonFilters.filter_test_accounts,- limit: CLICKMAP_STATS_LIMIT,+ limit,data_attributes: dataAttributes.join(','),} as unknown as ElementsStatsRetrieveParams}-function emptyCounts(): Pick<ClickmapBox, 'count' | 'clickCount' | 'rageclickCount' | 'deadclickCount'> {+type ElementCounts = Pick<ClickmapBox, 'count' | 'clickCount' | 'rageclickCount' | 'deadclickCount'>++function emptyCounts(): ElementCounts {return { count: 0, clickCount: 0, rageclickCount: 0, deadclickCount: 0 }}@@ -109,24 +120,65 @@ function describeElement(element: HTMLElement): { label: string; displaySelector}}-export function computeClickmapBoxes(+function boxesFromCounts(+ countsByElement: Map<HTMLElement, ElementCounts>,+ snapshotWindow: { scrollX: number; scrollY: number } | null+): ClickmapBox[] {+ const scrollX = snapshotWindow?.scrollX ?? 0+ const scrollY = snapshotWindow?.scrollY ?? 0+ const boxes: ClickmapBox[] = []+ countsByElement.forEach((counts, element) => {+ const rect = element.getBoundingClientRect()+ if (rect.width > 0 && rect.height > 0) {+ boxes.push({+ top: rect.top + scrollY,+ left: rect.left + scrollX,+ width: rect.width,+ height: rect.height,+ ...counts,+ ...describeElement(element),+ })+ }+ })+ return boxes.sort((a, b) => b.count - a.count)+}++export interface ClickmapComputeOptions extends ElementMatchOptions {+ dataAttributes: string[]+ onSlice?: () => void+}++export interface ClickmapComputeResult {+ boxes: ClickmapBox[]+ consistentClicks: number+ inconsistentClicks: number+}++export async function computeClickmapBoxes(statsRows: ElementStatsResponseApi['results'],snapshotDocument: Document,snapshotWindow: { scrollX: number; scrollY: number } | null,- dataAttributes: string[],- matchLinksByHref: boolean = false-): ClickmapBox[] {- const pageElements = collectAllElementsDeep('*', snapshotDocument) as HTMLElement[]- const domIndex = buildDOMIndex(pageElements)- const countsByElement = new Map<HTMLElement, ReturnType<typeof emptyCounts>>()+ { dataAttributes, matchLinksByHref, useDiscriminators, onSlice }: ClickmapComputeOptions+): Promise<ClickmapComputeResult> {+ const domIndex = buildDOMIndex(collectAllElementsDeep('*', snapshotDocument) as HTMLElement[])+ const countsByElement = new Map<HTMLElement, ElementCounts>()+ const maybeYield = createSliceYielder()+ let consistentClicks = 0+ let inconsistentClicks = 0+for (const row of statsRows) {- const match = matchEventToElementUsingIndex(- row as unknown as ElementsEventType,+ const match = matchEventToElementUsingIndex(row as unknown as ElementsEventType, domIndex, {dataAttributes,matchLinksByHref,- domIndex- )+ useDiscriminators,+ })if (match) {+ const chain = row.elements as unknown as ElementsEventType['elements']+ if (matchIsChainConsistent(match.element, chain, domIndex)) {+ consistentClicks += row.count+ } else {+ inconsistentClicks += row.count+ }const counts = countsByElement.get(match.element) ?? emptyCounts()counts.count += row.countif (row.type === '$rageclick') {@@ -138,25 +190,13 @@ export function computeClickmapBoxes(}countsByElement.set(match.element, counts)}- }- const scrollX = snapshotWindow?.scrollX ?? 0- const scrollY = snapshotWindow?.scrollY ?? 0- const boxes: ClickmapBox[] = []- countsByElement.forEach((counts, element) => {- const rect = element.getBoundingClientRect()- if (rect.width > 0 && rect.height > 0) {- boxes.push({- top: rect.top + scrollY,- left: rect.left + scrollX,- width: rect.width,- height: rect.height,- ...counts,- ...describeElement(element),- })+ if (await maybeYield()) {+ onSlice?.()}- })- return boxes.sort((a, b) => b.count - a.count)+ }++ return { boxes: boxesFromCounts(countsByElement, snapshotWindow), consistentClicks, inconsistentClicks }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -201,8 +241,8 @@ export interface recordingClickmapLogicActions {setReplayIframeDataURL: (url: string | null) => {url: string | null} // heatmapsBrowserLogic- loadElementStats: () => {- value: true+ loadElementStats: (limit?: number) => {+ limit: number | undefined}loadElementStatsFailure: (error: string,@@ -214,12 +254,12 @@ export interface recordingClickmapLogicActions {loadElementStatsSuccess: (elementStats: ElementStatsResponseApi | null,payload?: {- value: true+ limit: number | undefined}) => {elementStats: ElementStatsResponseApi | nullpayload?: {- value: true+ limit: number | undefined}}maybeLoadElementStats: () => {@@ -292,7 +332,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([setMatchLinksByHref: (matchLinksByHref: boolean) => ({ matchLinksByHref }),selectClickmapBox: (key: string | null) => ({ key }),setHoveredBoxKey: (key: string | null) => ({ key }),- loadElementStats: true,+ loadElementStats: (limit?: number) => ({ limit }),maybeLoadElementStats: true,recomputeClickmap: true,setClickmapBoxes: (boxes: ClickmapBox[]) => ({ boxes }),@@ -350,7 +390,7 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([elementStats: [null as ElementStatsResponseApi | null,{- loadElementStats: async (_, breakpoint) => {+ loadElementStats: async ({ limit }, breakpoint) => {await breakpoint(150)// heatmapDataLogic's href is shared and driven by the browser data-URL flow,// so the replay payload's URL is the stable source of truth here@@ -362,7 +402,8 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([url,isUrlPattern(url),values.commonFilters,- values.wantedDataAttributes+ values.wantedDataAttributes,+ limit)const response = await elementsStatsRetrieve(String(values.currentProjectId), params)breakpoint()@@ -436,7 +477,16 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([actions.maybeLoadElementStats()}},- loadElementStatsSuccess: () => actions.recomputeClickmap(),+ loadElementStatsSuccess: ({ elementStats, payload }) => {+ actions.recomputeClickmap()+ if (+ !payload?.limit &&+ elementStats?.next &&+ values.featureFlags[FEATURE_FLAGS.HEATMAPS_CLICKMAP_PAGINATION]+ ) {+ actions.loadElementStats(CLICKMAP_STATS_AUTO_LOAD_LIMIT)+ }+ },recomputeClickmap: async (_, breakpoint) => {if (!values.clickmapActive || !values.replayIframeData?.url?.trim()) {return@@ -450,17 +500,29 @@ export const recordingClickmapLogic = kea<recordingClickmapLogicType>([return}- const boxes = computeClickmapBoxes(+ const useDiscriminators = !!values.featureFlags[FEATURE_FLAGS.HEATMAPS_CLICKMAP_DISCRIMINATORS]+ const { boxes, consistentClicks, inconsistentClicks } = await computeClickmapBoxes(statsRows,snapshotDocument,iframe?.contentWindow ?? null,- values.wantedDataAttributes,- values.matchLinksByHref+ {+ dataAttributes: values.wantedDataAttributes,+ matchLinksByHref: values.matchLinksByHref,+ useDiscriminators,+ onSlice: breakpoint,+ })posthog.capture('in-app heatmap clickmap rendered', {stats_rows: statsRows.length,matched_elements: boxes.length,has_more: !!values.elementStats?.next,+ ...chainConsistencyProperties({+ useDiscriminators,+ consistentClicks,+ inconsistentClicks,+ matchedClicks: boxes.reduce((total, box) => total + box.count, 0),+ totalClicks: statsRows.reduce((total, row) => total + row.count, 0),+ }),})actions.setClickmapBoxes(boxes)},