: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
fix(toolbar): make clickmap element matching linear and position-aware (#67549)
Paul D'Ambra083529704e47
diff --git a/frontend/src/lib/utils/actions.test.ts b/frontend/src/lib/utils/actions.test.tsindex 89842a47e6e1..ddd7a02ed31f 100644--- a/frontend/src/lib/utils/actions.test.ts+++ b/frontend/src/lib/utils/actions.test.ts@@ -20,4 +20,31 @@ describe('elementToSelector', () => {const actual = elementToSelector(element, [])expect(actual).toEqual('.potato.soup')})++ const dataAttributeValueCases = [+ {+ name: 'keeps dots unescaped so backend literal matching still works',+ value: 'user.settings.save',+ expected: '[data-attr="user.settings.save"]',+ },+ {+ name: 'escapes quotes so a value cannot break out of the selector',+ value: 'x"],[id="other',+ expected: '[data-attr="x\\"],[id=\\"other"]',+ },+ {+ name: 'escapes backslashes before quotes',+ value: 'a\\"b',+ expected: '[data-attr="a\\\\\\"b"]',+ },+ ]++ it.each(dataAttributeValueCases)('$name', ({ value, expected }) => {+ const element = {+ attributes: { 'attr__data-attr': value },+ } as unknown as ElementType++ const actual = elementToSelector(element, ['data-attr'])+ expect(actual).toEqual(expected)+ })})diff --git a/frontend/src/lib/utils/actions.ts b/frontend/src/lib/utils/actions.tsindex c7befd0f7e69..9e49e3801122 100644--- a/frontend/src/lib/utils/actions.ts+++ b/frontend/src/lib/utils/actions.ts@@ -54,11 +54,15 @@ export function matchesDataAttribute(element: ElementType, dataAttributes: strin}}+// not CSS.escape: the backend selector parser matches quoted values literally, so escaping+// anything beyond \ and " (e.g. the dots in data-attr="user.settings.save") breaks server-side matching+const escapeQuotedSelectorValue = (value: string): string => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')+export function elementToSelector(element: ElementType, dataAttributes: string[]): string {let selector = ''const attribute = matchesDataAttribute(element, dataAttributes)if (attribute) {- selector += `[${attribute}="${element.attributes[`attr__${attribute}`]}"]`+ selector += `[${attribute}="${escapeQuotedSelectorValue(element.attributes[`attr__${attribute}`])}"]`return selector}if (element.attr_id) {diff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.mdindex 694a739985b0..b528f2340ee8 100644--- a/frontend/src/toolbar/TELEMETRY.md+++ b/frontend/src/toolbar/TELEMETRY.md@@ -149,6 +149,28 @@ Fired when a toolbar mode is toggled on or off.`actions/actionsTabLogic.tsx`, `experiments/experimentsTabLogic.tsx`,`product-tours/productToursLogic.ts`+## Heatmaps / clickmaps++### `toolbar clickmap processed`++Fired when a clickmap matching run ends, including runs cancelled because a newer run superseded them (see `completed`).+A user paginating emits one event per page with cumulative `event_count` — group by `trigger` when aggregating.++| Property | Type | Description |+| ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------- |+| `event_count` | `number` | Element stats rows processed |+| `matched_element_count` | `number` | Rows matched to a visible DOM element |+| `index_matched_count` | `number` | Rows matched via the DOM index fast path (before visibility trimming) |+| `fallback_matched_count` | `number` | Rows matched via the selector fallback (before visibility trimming); rising values signal index drift |+| `page_element_count` | `number` | Elements collected from the page for matching |+| `has_shadow_roots` | `boolean` | Whether open shadow roots were detected; selects which fallback implementation runs, not whether a fallback runs |+| `duration_ms` | `number` | Wall-clock processing time, including main-thread yields; DOM index build time is included only on a cold cache |+| `trigger` | `string` | What started the run: `initial`, `pagination`, `refresh`, or `toggle` |+| `cache_hit` | `boolean` | Whether the page-elements cache was warm (no collect + index rebuild) |+| `completed` | `boolean` | False when the run was cancelled mid-processing by a newer run |++**File:** `elements/heatmapToolbarMenuLogic.ts`+## Element inspection### `toolbar selected HTML element`diff --git a/frontend/src/toolbar/elements/domElementIndex.test.ts b/frontend/src/toolbar/elements/domElementIndex.test.tsindex b68549e48a8e..951b9d28cb9f 100644--- a/frontend/src/toolbar/elements/domElementIndex.test.ts+++ b/frontend/src/toolbar/elements/domElementIndex.test.ts@@ -1,77 +1,8 @@-import { collectAllElementsDeep, querySelectorAllDeep } from 'query-selector-shadow-dom'--import { elementToSelector } from 'lib/utils/actions'--import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'--import { buildDOMIndex, matchEventToElementUsingIndex } from './domElementIndex'--function matchEventToElementOriginal(- event: ElementsEventType,- dataAttributes: string[],- matchLinksByHref: boolean,- pageElements: HTMLElement[],- selectorCache: Record<string, HTMLElement[]>-): CountedHTMLElement | null {- let lastSelector: string | undefined-- for (let i = 0; i < event.elements.length; i++) {- const element = event.elements[i]- const selector =- elementToSelector(matchLinksByHref ? element : { ...element, href: undefined }, dataAttributes) || '*'- const combinedSelector = lastSelector ? `${selector} > ${lastSelector}` : selector-- try {- let domElements: HTMLElement[] | undefined = selectorCache[combinedSelector]- if (domElements === undefined) {- domElements = Array.from(querySelectorAllDeep(combinedSelector, document, pageElements))- selectorCache[combinedSelector] = domElements- }-- if (domElements.length === 1) {- const e = event.elements[i]- const isTooSimple =- i === 0 &&- e.tag_name &&- !e.attr_class &&- !e.attr_id &&- !e.href &&- !e.text &&- e.nth_child === 1 &&- e.nth_of_type === 1 &&- !e.attributes['attr__data-attr']-- if (!isTooSimple) {- return {- element: domElements[0],- count: event.count,- selector: selector,- hash: event.hash,- type: event.type,- clickCount: 0,- rageclickCount: 0,- deadclickCount: 0,- }- }- }-- if (domElements.length === 0) {- if (i === event.elements.length - 1) {- return null- } else if (i > 0 && lastSelector) {- lastSelector = `* > ${lastSelector}`- continue- }- }- } catch {- break- }+import { collectAllElementsDeep } from 'query-selector-shadow-dom'- lastSelector = combinedSelector- }+import { ElementsEventType } from '~/toolbar/types'- return null-}+import { buildDOMIndex, matchEventToElementUsingIndex, matchEventToElementUsingSelectors } from './domElementIndex'function createTestDOM(html: string): { container: HTMLElement; cleanup: () => void } {const container = document.createElement('div')@@ -325,18 +256,79 @@ describe('domElementIndex', () => {}})- it('uses parent chain to disambiguate multiple candidates', () => {- const { container, cleanup } = createTestDOM(`- <div class="container-a"><button class="btn"></button></div>- <div class="container-b"><button class="btn" id="target"></button></div>- `)- try {- const index = buildDOMIndex(getAllElements(container))- const event = createEvent([+ const parentChainCases = [+ {+ name: 'uses parent chain to disambiguate multiple candidates',+ html: `+ <div class="container-a"><button class="btn"></button></div>+ <div class="container-b"><button class="btn" id="target"></button></div>+ `,+ event: [{ tag_name: 'button', attr_class: ['btn'] },{ tag_name: 'div', attr_class: ['container-b'] },- ])- const result = matchEventToElementUsingIndex(event, [], false, index)+ ],+ },+ {+ name: 'uses ancestor position to disambiguate repeated identical structures',+ html: `+ <div class="row"><button class="btn"></button></div>+ <div class="row"><button class="btn" id="target"></button></div>+ <div class="row"><button class="btn"></button></div>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'], nth_child: 1, nth_of_type: 1 },+ { tag_name: 'div', attr_class: ['row'], nth_child: 2, nth_of_type: 2 },+ ],+ },+ {+ name: 'walks one ancestor level per chain entry, not the parent repeatedly',+ html: `+ <section class="outer-a"><div class="middle"><button class="btn"></button></div></section>+ <section class="outer-b"><div class="middle"><button class="btn" id="target"></button></div></section>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'] },+ { tag_name: 'div', attr_class: ['middle'] },+ { tag_name: 'section', attr_class: ['outer-b'] },+ ],+ },+ {+ name: 'ignores drifted sibling position when the ancestor is identified by id',+ html: `+ <div class="injected-banner"></div>+ <div id="main-panel"><button class="btn" id="target"></button></div>+ <div class="other"><button class="btn"></button></div>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'], nth_child: 1, nth_of_type: 1 },+ { tag_name: 'div', attr_id: 'main-panel', nth_child: 1, nth_of_type: 1 },+ ],+ },+ {+ name: 'ignores drifted sibling position when the ancestor is identified by a data attribute',+ html: `+ <div class="injected-banner"></div>+ <div data-attr="main-panel"><button class="btn" id="target"></button></div>+ <div class="other"><button class="btn"></button></div>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'], nth_child: 1, nth_of_type: 1 },+ {+ tag_name: 'div',+ attributes: { 'attr__data-attr': 'main-panel' },+ nth_child: 1,+ nth_of_type: 1,+ },+ ],+ dataAttributes: ['data-attr'],+ },+ ]++ it.each(parentChainCases)('$name', ({ html, event, dataAttributes = [] }) => {+ const { container, cleanup } = createTestDOM(html)+ try {+ const index = buildDOMIndex(getAllElements(container))+ const result = matchEventToElementUsingIndex(createEvent(event), dataAttributes, false, index)expect(result).not.toBeNull()expect(result?.element.id).toBe('target')@@ -467,37 +459,67 @@ describe('domElementIndex', () => {event: [{ tag_name: 'button', attributes: { 'attr__data-testid': 'cta-button' } }],dataAttributes: ['data-testid'],},+ {+ name: 'matches within repeated identical structures via ancestor position',+ html: `+ <div class="row"><a class="link" href="/one">One</a></div>+ <div class="row"><a class="link" href="/two">Two</a></div>+ <div class="row"><a class="link" href="/three">Three</a></div>+ `,+ event: [+ { tag_name: 'a', attr_class: ['link'], nth_child: 1, nth_of_type: 1 },+ { tag_name: 'div', attr_class: ['row'], nth_child: 3, nth_of_type: 3 },+ ],+ },+ {+ name: 'matches when only a grandparent disambiguates',+ html: `+ <section class="outer-a"><div class="middle"><button class="btn">A</button></div></section>+ <section class="outer-b"><div class="middle"><button class="btn">B</button></div></section>+ `,+ event: [+ { tag_name: 'button', attr_class: ['btn'] },+ { tag_name: 'div', attr_class: ['middle'] },+ { tag_name: 'section', attr_class: ['outer-b'] },+ ],+ },]- it.each(comparisonCases)('$name: both implementations agree', ({ html, event, dataAttributes = [] }) => {- const { cleanup } = createTestDOM(html)- try {- const pageElements = collectAllElementsDeep('*', document) as HTMLElement[]- const index = buildDOMIndex(pageElements)- const selectorCache: Record<string, HTMLElement[]> = {}-- const eventObj = createEvent(event)-- const indexResult = matchEventToElementUsingIndex(eventObj, dataAttributes, true, index)- const originalResult = matchEventToElementOriginal(- eventObj,- dataAttributes,- true,- pageElements,- selectorCache- )-- if (originalResult === null) {- expect(indexResult).toBeNull()- } else {- expect(indexResult).not.toBeNull()- expect(indexResult?.element).toBe(originalResult.element)- expect(indexResult?.count).toBe(originalResult.count)- expect(indexResult?.hash).toBe(originalResult.hash)+ const shadowRootModes = [{ hasShadowRoots: true }, { hasShadowRoots: false }]++ it.each(comparisonCases.flatMap((c) => shadowRootModes.map((mode) => ({ ...c, ...mode }))))(+ '$name: both implementations agree (hasShadowRoots=$hasShadowRoots)',+ ({ html, event, dataAttributes = [], hasShadowRoots }) => {+ const { cleanup } = createTestDOM(html)+ try {+ const pageElements = collectAllElementsDeep('*', document) as HTMLElement[]+ const index = buildDOMIndex(pageElements)+ const selectorCache = new Map<string, HTMLElement[]>()++ const eventObj = createEvent(event)++ const indexResult = matchEventToElementUsingIndex(eventObj, dataAttributes, true, index)+ const selectorResult = matchEventToElementUsingSelectors(+ eventObj,+ dataAttributes,+ true,+ pageElements,+ selectorCache,+ hasShadowRoots+ )++ if (selectorResult === null) {+ expect(indexResult).toBeNull()+ } else {+ expect(indexResult).not.toBeNull()+ expect(indexResult?.element).toBe(selectorResult.element)+ expect(indexResult?.count).toBe(selectorResult.count)+ expect(indexResult?.hash).toBe(selectorResult.hash)+ }+ } finally {+ cleanup()}- } finally {- cleanup()}- })+ )})})diff --git a/frontend/src/toolbar/elements/domElementIndex.ts b/frontend/src/toolbar/elements/domElementIndex.tsindex b4fa5a04005e..fd38a006c438 100644--- a/frontend/src/toolbar/elements/domElementIndex.ts+++ b/frontend/src/toolbar/elements/domElementIndex.ts@@ -1,6 +1,10 @@-import { matchesDataAttribute } from 'lib/utils/actions'+import { querySelectorAllDeep } from 'query-selector-shadow-dom'+import { elementToSelector, matchesDataAttribute } from 'lib/utils/actions'++import { toolbarLogger } from '~/toolbar/toolbarLogger'import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'+import { TOOLBAR_ID } from '~/toolbar/utils'import { ElementType } from '~/types'interface ElementFingerprint {@@ -12,6 +16,11 @@ interface ElementFingerprint {nthOfType: number}+interface ElementPosition {+ nthChild: number+ nthOfType: number+}+export interface DOMIndex {byId: Map<string, HTMLElement[]>byTagName: Map<string, HTMLElement[]>@@ -19,6 +28,7 @@ export interface DOMIndex {byDataAttr: Map<string, Map<string, HTMLElement[]>>byHref: Map<string, HTMLElement[]>fingerprints: WeakMap<HTMLElement, ElementFingerprint>+ hasShadowRoots: boolean}function addToIndex(map: Map<string, HTMLElement[]>, key: string, element: HTMLElement): void {@@ -30,17 +40,36 @@ function addToIndex(map: Map<string, HTMLElement[]>, key: string, element: HTMLE}}-function createFingerprint(element: HTMLElement): ElementFingerprint {+function getPosition(+ element: HTMLElement,+ positionsByParent: WeakMap<HTMLElement, Map<Element, ElementPosition>>+): ElementPosition {const parent = element.parentElement- let nthChild = 1- let nthOfType = 1+ if (!parent) {+ return { nthChild: 1, nthOfType: 1 }+ }- if (parent) {- const siblings = Array.from(parent.children)- const elementIndex = siblings.indexOf(element)- nthChild = elementIndex + 1- nthOfType = siblings.filter((s, idx) => s.tagName === element.tagName && idx < elementIndex).length + 1+ let positions = positionsByParent.get(parent)+ if (!positions) {+ positions = new Map()+ const typeCounts = new Map<string, number>()+ let nthChild = 0+ for (const child of Array.from(parent.children)) {+ nthChild += 1+ const nthOfType = (typeCounts.get(child.tagName) ?? 0) + 1+ typeCounts.set(child.tagName, nthOfType)+ positions.set(child, { nthChild, nthOfType })+ }+ positionsByParent.set(parent, positions)}+ return positions.get(element) ?? { nthChild: -1, nthOfType: -1 }+}++function createFingerprint(+ element: HTMLElement,+ positionsByParent: WeakMap<HTMLElement, Map<Element, ElementPosition>>+): ElementFingerprint {+ const { nthChild, nthOfType } = getPosition(element, positionsByParent)const dataAttrs = new Map<string, string>()for (let i = 0; i < element.attributes.length; i++) {@@ -68,10 +97,12 @@ export function buildDOMIndex(pageElements: HTMLElement[]): DOMIndex {byDataAttr: new Map(),byHref: new Map(),fingerprints: new WeakMap(),+ hasShadowRoots: false,}+ const positionsByParent = new WeakMap<HTMLElement, Map<Element, ElementPosition>>()for (const element of pageElements) {- const fingerprint = createFingerprint(element)+ const fingerprint = createFingerprint(element, positionsByParent)index.fingerprints.set(element, fingerprint)if (fingerprint.id) {@@ -95,6 +126,10 @@ export function buildDOMIndex(pageElements: HTMLElement[]): DOMIndex {if (href) {addToIndex(index.byHref, href, element)}++ if (element.shadowRoot && element.id !== TOOLBAR_ID) {+ index.hasShadowRoots = true+ }}return index@@ -110,6 +145,13 @@ function matchesPosition(fingerprint: ElementFingerprint, eventElement: ElementTreturn true}+function filterByPosition(candidates: HTMLElement[], eventElement: ElementType, index: DOMIndex): HTMLElement[] {+ return candidates.filter((el) => {+ const fp = index.fingerprints.get(el)+ return fp && matchesPosition(fp, eventElement)+ })+}+function getCandidatesFromIndex(eventElement: ElementType,dataAttributes: string[],@@ -122,10 +164,7 @@ function getCandidatesFromIndex(if (value !== undefined) {const candidates = index.byDataAttr.get(matchedAttr)?.get(value) || []if (candidates.length) {- return candidates.filter((el) => {- const fp = index.fingerprints.get(el)- return fp && matchesPosition(fp, eventElement)- })+ return filterByPosition(candidates, eventElement, index)}}}@@ -133,14 +172,11 @@ function getCandidatesFromIndex(if (eventElement.attr_id) {const candidates = index.byId.get(eventElement.attr_id) || []if (candidates.length) {- return candidates.filter((el) => {- const fp = index.fingerprints.get(el)- return fp && matchesPosition(fp, eventElement)- })+ return filterByPosition(candidates, eventElement, index)}}- let candidates = eventElement.tag_name ? [...(index.byTagName.get(eventElement.tag_name.toLowerCase()) || [])] : []+ let candidates = eventElement.tag_name ? index.byTagName.get(eventElement.tag_name.toLowerCase()) || [] : []if (eventElement.attr_class?.length) {for (const cls of eventElement.attr_class) {@@ -156,40 +192,51 @@ function getCandidatesFromIndex(candidates = candidates.filter((el) => hrefMatches.has(el))}- return candidates.filter((el) => {- const fp = index.fingerprints.get(el)- return fp && matchesPosition(fp, eventElement)- })+ return filterByPosition(candidates, eventElement, index)}-function matchesParent(candidate: HTMLElement, parentEvent: ElementType, index: DOMIndex): boolean {- const parent = candidate.parentElement- if (!parent) {- return false+// derived once per chain level, not per candidate: matchesDataAttribute builds a RegExp per call+function getMatchedDataAttribute(+ eventElement: ElementType,+ dataAttributes: string[]+): { name: string; value: string } | null {+ const matchedAttr = matchesDataAttribute(eventElement, dataAttributes)+ if (!matchedAttr) {+ return null}+ const value = eventElement.attributes?.[`attr__${matchedAttr}`]+ return value === undefined ? null : { name: matchedAttr, value }+}- const fp = index.fingerprints.get(parent)- if (!fp) {+function fingerprintMatchesEventElement(+ fingerprint: ElementFingerprint | undefined,+ eventElement: ElementType,+ matchedDataAttribute: { name: string; value: string } | null+): boolean {+ if (!fingerprint) {return false}-- if (parentEvent.tag_name && fp.tagName !== parentEvent.tag_name.toLowerCase()) {+ if (eventElement.tag_name && fingerprint.tagName !== eventElement.tag_name.toLowerCase()) {return false}- if (parentEvent.attr_id && fp.id !== parentEvent.attr_id) {+ if (eventElement.attr_id && fingerprint.id !== eventElement.attr_id) {return false}- if (parentEvent.attr_class?.length) {- for (const cls of parentEvent.attr_class) {- if (cls && !fp.classes.has(cls)) {- return false- }+ for (const cls of eventElement.attr_class ?? []) {+ if (cls && !fingerprint.classes.has(cls)) {+ return false}}- return true+ // an id or configured data attribute identifies the ancestor on its own, so DOM drift that+ // shifts sibling positions (cookie banners, injected wrappers) shouldn't kill the match —+ // mirroring elementToSelector, which early-returns on these without position+ const identifiedWithoutPosition =+ (!!eventElement.attr_id && fingerprint.id === eventElement.attr_id) ||+ (!!matchedDataAttribute && fingerprint.dataAttrs.get(matchedDataAttribute.name) === matchedDataAttribute.value)+ return identifiedWithoutPosition || matchesPosition(fingerprint, eventElement)}-function isTooSimple(element: ElementType): boolean {+export function isTooSimple(element: ElementType): boolean {return !!(element.tag_name &&!element.attr_class &&@@ -213,19 +260,30 @@ export function matchEventToElementUsingIndex(return null}- let candidates = getCandidatesFromIndex(targetElement, dataAttributes, matchLinksByHref, index)+ const candidates = getCandidatesFromIndex(targetElement, dataAttributes, matchLinksByHref, index)if (candidates.length === 0) {return null}- for (let i = 1; i < event.elements.length && candidates.length > 1; i++) {- candidates = candidates.filter((c) => matchesParent(c, event.elements[i], index))+ let walkers = candidates.map((candidate) => ({ candidate, ancestor: candidate.parentElement }))+ for (let i = 1; i < event.elements.length && walkers.length > 1; i++) {+ const eventAncestor = event.elements[i]+ const ancestorDataAttribute = getMatchedDataAttribute(eventAncestor, dataAttributes)+ walkers = walkers.flatMap(({ candidate, ancestor }) => {+ if (+ !ancestor ||+ !fingerprintMatchesEventElement(index.fingerprints.get(ancestor), eventAncestor, ancestorDataAttribute)+ ) {+ return []+ }+ return [{ candidate, ancestor: ancestor.parentElement }]+ })}- if (candidates.length === 1 && !isTooSimple(targetElement)) {+ if (walkers.length === 1 && !isTooSimple(targetElement)) {return {- element: candidates[0],+ element: walkers[0].candidate,count: event.count,selector: '',hash: event.hash,@@ -238,3 +296,75 @@ export function matchEventToElementUsingIndex(return null}++// each chain level costs a selector query, so a single deep-chain event (legitimately deep DOM or a+// forged chain) could otherwise hold the main thread for an unbounded uninterruptible stretch+const MAX_SELECTOR_CHAIN_LEVELS = 10++export function matchEventToElementUsingSelectors(+ event: ElementsEventType,+ dataAttributes: string[],+ matchLinksByHref: boolean,+ pageElements: HTMLElement[],+ selectorCache: Map<string, HTMLElement[]>,+ hasShadowRoots: boolean+): CountedHTMLElement | null {+ let lastSelector: string | undefined++ const chainDepth = Math.min(event.elements.length, MAX_SELECTOR_CHAIN_LEVELS)+ for (let i = 0; i < chainDepth; i++) {+ const element = event.elements[i]+ const selector =+ elementToSelector(matchLinksByHref ? element : { ...element, href: undefined }, dataAttributes) || '*'+ const combinedSelector = lastSelector ? `${selector} > ${lastSelector}` : selector++ try {+ let domElements: HTMLElement[] | undefined = selectorCache.get(combinedSelector)+ if (domElements === undefined) {+ domElements = hasShadowRoots+ ? Array.from(querySelectorAllDeep(combinedSelector, document, pageElements))+ : Array.from(document.querySelectorAll<HTMLElement>(combinedSelector))+ selectorCache.set(combinedSelector, domElements)+ }++ if (domElements.length === 1) {+ const firstAndTooSimple = i === 0 && isTooSimple(event.elements[i])+ if (!firstAndTooSimple) {+ return {+ element: domElements[0],+ count: event.count,+ selector: selector,+ hash: event.hash,+ type: event.type,+ clickCount: 0,+ rageclickCount: 0,+ deadclickCount: 0,+ }+ }+ }++ if (domElements.length === 0) {+ if (i === event.elements.length - 1) {+ return null+ } else if (i > 0 && lastSelector) {+ lastSelector = `* > ${lastSelector}`+ continue+ }+ }+ } catch {+ // sentinel-cache the failing selector so repeated rows neither re-throw nor re-log,+ // and truncate: event-derived selectors can embed long customer-page attribute values+ if (!selectorCache.has(combinedSelector)) {+ selectorCache.set(combinedSelector, [])+ toolbarLogger.warn('heatmap', 'Failed to resolve heatmap element with selector', {+ selector: combinedSelector.slice(0, 200),+ })+ }+ break+ }++ lastSelector = combinedSelector+ }++ return null+}diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex ebf93250d223..5728a2ab162b 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -3,27 +3,32 @@ import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'import { windowValues } from 'kea-window-values'import { PostHog } from 'posthog-js'-import { collectAllElementsDeep, querySelectorAllDeep } from 'query-selector-shadow-dom'+import { collectAllElementsDeep } from 'query-selector-shadow-dom'import type { PaginatedResponse } from 'lib/api'import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'-import { elementToSelector } from 'lib/utils/actions'import { createVersionChecker } from 'lib/utils/semver'-import { DOMIndex, buildDOMIndex, matchEventToElementUsingIndex } from '~/toolbar/elements/domElementIndex'+import {+ DOMIndex,+ buildDOMIndex,+ matchEventToElementUsingIndex,+ matchEventToElementUsingSelectors,+} from '~/toolbar/elements/domElementIndex'import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'-import { toolbarLogger } from '~/toolbar/toolbarLogger'import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'-import { elementIsVisible, invalidateZoomCache, trimElement } from '~/toolbar/utils'+import { TOOLBAR_ID, elementIsVisible, invalidateZoomCache, trimElement } from '~/toolbar/utils'import { PropertyFilterType, PropertyOperator } from '~/types'import type { heatmapToolbarMenuLogicType } from './heatmapToolbarMenuLogicType'export const doesVersionSupportScrollDepth = createVersionChecker('1.99')+export const ELEMENT_STATS_PAGE_LIMIT = 5000+function yieldToMain(): Promise<void> {return new Promise((resolve) => {if ('scheduler' in window && typeof (window as any).scheduler?.yield === 'function') {@@ -36,10 +41,12 @@ function yieldToMain(): Promise<void> {})}+export type ClickmapProcessingTrigger = 'initial' | 'pagination' | 'refresh' | 'toggle'+interface ElementProcessingCache {pageElements?: HTMLElement[]domIndex?: DOMIndex- selectorToElements: Record<string, HTMLElement[]>+ selectorToElements: Map<string, HTMLElement[]>lastHref?: stringintersectionObserver?: IntersectionObservervisibilityCache: WeakMap<HTMLElement, boolean>@@ -56,20 +63,32 @@ function invalidatePageElementsCache(cache: ElementProcessingCache): void {function getCachedPageElements(cache: ElementProcessingCache,href: string-): { pageElements: HTMLElement[]; domIndex: DOMIndex } {+): { pageElements: HTMLElement[]; domIndex: DOMIndex; hasShadowRoots: boolean; cacheHit: boolean } {const hrefChanged = cache.lastHref !== hrefconst cacheValid = cache.pageElements && !hrefChanged && !cache.cacheInvalidatedif (cacheValid && cache.pageElements && cache.domIndex) {- return { pageElements: cache.pageElements, domIndex: cache.domIndex }+ return {+ pageElements: cache.pageElements,+ domIndex: cache.domIndex,+ // attachShadow() emits no light-DOM mutation, so the build-time flag can go stale —+ // recheck the snapshot on every run+ hasShadowRoots: cache.pageElements.some((el) => el.shadowRoot && el.id !== TOOLBAR_ID),+ cacheHit: true,+ }}cache.pageElements = collectAllElementsDeep('*', document)cache.domIndex = buildDOMIndex(cache.pageElements)cache.lastHref = href- cache.selectorToElements = {}+ cache.selectorToElements = new Map()cache.cacheInvalidated = false- return { pageElements: cache.pageElements, domIndex: cache.domIndex }+ return {+ pageElements: cache.pageElements,+ domIndex: cache.domIndex,+ hasShadowRoots: cache.domIndex.hasShadowRoots,+ cacheHit: false,+ }}const emptyElementsStatsPages: PaginatedResponse<ElementsEventType> = {@@ -133,7 +152,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([updateElementMetrics: (observedElements: [HTMLElement, boolean][]) => ({ observedElements }),startElementObservation: true,stopElementObservation: true,- processElements: true,+ processElements: (trigger: ClickmapProcessingTrigger) => ({ trigger }),refreshClickmap: true,setIsRefreshing: (isRefreshing: boolean) => ({ isRefreshing }),setProcessedElements: (elements: CountedHTMLElement[]) => ({ elements }),@@ -267,6 +286,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([date_to: values.commonFilters.date_to,paginate_response: true,sampling_factor: values.samplingFactor,+ limit: ELEMENT_STATS_PAGE_LIMIT,},options)@@ -281,11 +301,11 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}return {- results: [+ results: dedupeByChainIdentity([// if url is present we are paginating and merge results, otherwise we only use the new results...(url ? values.elementStats?.results || [] : []),...(result.data.results || []),- ],+ ]),next: result.data.next,previous: result.data.previous,} as PaginatedResponse<ElementsEventType>@@ -359,9 +379,9 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([},})),listeners(({ actions, values, cache }) => ({- processElements: async (_, breakpoint) => {- const BATCH_SIZE = 200- const INITIAL_BATCH_SIZE = 50+ processElements: async ({ trigger }, breakpoint) => {+ const SLICE_BUDGET_MS = 10+ const startedAt = performance.now()const { elementStats, dataAttributes, href, matchLinksByHref, clickmapsEnabled } = values.processingInputs@@ -373,28 +393,38 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([cache.visibilityCache = cache.visibilityCache || new WeakMap<HTMLElement, boolean>()const cursorPointerCache = new WeakMap<HTMLElement, boolean>()- const { pageElements, domIndex } = getCachedPageElements(cache as ElementProcessingCache, href)+ const { pageElements, domIndex, hasShadowRoots, cacheHit } = getCachedPageElements(+ cache as ElementProcessingCache,+ href+ )const eventsToProcess = elementStats.resultsconst totalEvents = eventsToProcess.lengthconst allTrimmedElements: CountedHTMLElement[] = []- let processedCount = 0+ let indexMatchedCount = 0+ let fallbackMatchedCount = 0+ let completed = false+ let sliceStart = performance.now()- while (processedCount < totalEvents) {- const batchSize = processedCount === 0 ? INITIAL_BATCH_SIZE : BATCH_SIZE- const batchEnd = Math.min(processedCount + batchSize, totalEvents)-- for (let i = processedCount; i < batchEnd; i++) {+ try {+ for (let i = 0; i < totalEvents; i++) {const event = eventsToProcess[i]- const matched =- matchEventToElementUsingIndex(event, dataAttributes, matchLinksByHref, domIndex) ||- matchEventToElement(+ let matched = matchEventToElementUsingIndex(event, dataAttributes, matchLinksByHref, domIndex)+ if (matched) {+ indexMatchedCount += 1+ } else {+ matched = matchEventToElementUsingSelectors(event,dataAttributes,matchLinksByHref,pageElements,- cache as ElementProcessingCache+ (cache as ElementProcessingCache).selectorToElements,+ hasShadowRoots)+ if (matched) {+ fallbackMatchedCount += 1+ }+ }if (matched) {const trimmed = trimElement(matched.element, { cursorPointerCache })@@ -405,18 +435,36 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([allTrimmedElements.push({ ...matched, element: trimmed })}}- }- processedCount = batchEnd- actions.setProcessingProgress(processedCount, totalEvents)+ if (performance.now() - sliceStart > SLICE_BUDGET_MS) {+ actions.setProcessingProgress(i + 1, totalEvents)+ await yieldToMain()+ breakpoint()+ sliceStart = performance.now()+ }+ }breakpoint()- await yieldToMain()+ actions.setProcessedElements(aggregateAndSortElements(allTrimmedElements))+ actions.startElementObservation()+ actions.setIsRefreshing(false)+ completed = true+ } finally {+ // fire on cancelled runs too — the slow pages that get superseded are exactly+ // the ones we most need to see+ toolbarPosthogJS.capture('toolbar clickmap processed', {+ event_count: totalEvents,+ matched_element_count: allTrimmedElements.length,+ index_matched_count: indexMatchedCount,+ fallback_matched_count: fallbackMatchedCount,+ page_element_count: pageElements.length,+ has_shadow_roots: hasShadowRoots,+ duration_ms: Math.round(performance.now() - startedAt),+ trigger,+ cache_hit: cacheHit,+ completed,+ })}-- actions.setProcessedElements(aggregateAndSortElements(allTrimmedElements))- actions.startElementObservation()- actions.setIsRefreshing(false)},enableHeatmap: () => {@@ -494,7 +542,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([actions.stopElementObservation()actions.resetElementStats()cache.pageElements = undefined- cache.selectorToElements = {}+ cache.selectorToElements = new Map()cache.lastHref = undefinedcache.visibilityCache = new WeakMap()}@@ -506,12 +554,12 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}},- getElementStatsSuccess: () => {- actions.processElements()+ getElementStatsSuccess: ({ elementStats }) => {+ actions.processElements(elementStats?.previous ? 'pagination' : 'initial')},setMatchLinksByHref: () => {- actions.processElements()+ actions.processElements('toggle')},refreshClickmap: () => {@@ -520,7 +568,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}actions.setIsRefreshing(true)invalidatePageElementsCache(cache as ElementProcessingCache)- actions.processElements()+ actions.processElements('refresh')},patchHeatmapFilters: ({ filters }) => {@@ -531,7 +579,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([},})),afterMount(({ actions, cache, values }) => {- cache.selectorToElements = {}+ cache.selectorToElements = new Map()cache.visibilityCache = new WeakMap()cache.disposables.add(() => {@@ -595,78 +643,25 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}),beforeUnmount(({ cache }) => {cache.pageElements = undefined- cache.selectorToElements = {}+ cache.selectorToElements = new Map()cache.visibilityCache = new WeakMap()cache.lastHref = undefinedcache.cacheInvalidated = false}),])-function matchEventToElement(- event: ElementsEventType,- dataAttributes: string[],- matchLinksByHref: boolean,- pageElements: HTMLElement[],- cache: ElementProcessingCache-): CountedHTMLElement | null {- let lastSelector: string | undefined-- for (let i = 0; i < event.elements.length; i++) {- const element = event.elements[i]- const selector =- elementToSelector(matchLinksByHref ? element : { ...element, href: undefined }, dataAttributes) || '*'- const combinedSelector = lastSelector ? `${selector} > ${lastSelector}` : selector-- try {- let domElements: HTMLElement[] | undefined = cache.selectorToElements[combinedSelector]- if (domElements === undefined) {- domElements = Array.from(querySelectorAllDeep(combinedSelector, document, pageElements))- cache.selectorToElements[combinedSelector] = domElements- }-- if (domElements.length === 1) {- const e = event.elements[i]- const isTooSimple =- i === 0 &&- e.tag_name &&- !e.attr_class &&- !e.attr_id &&- !e.href &&- !e.text &&- e.nth_child === 1 &&- e.nth_of_type === 1 &&- !e.attributes['attr__data-attr']-- if (!isTooSimple) {- return {- element: domElements[0],- count: event.count,- selector: selector,- hash: event.hash,- type: event.type,- } as CountedHTMLElement- }- }-- if (domElements.length === 0) {- if (i === event.elements.length - 1) {- return null- } else if (i > 0 && lastSelector) {- lastSelector = `* > ${lastSelector}`- continue- }- }- } catch {- toolbarLogger.warn('heatmap', 'Failed to resolve heatmap element with selector', {- selector: combinedSelector,- })- break+function dedupeByChainIdentity(events: ElementsEventType[]): ElementsEventType[] {+ const seen = new Set<string>()+ const deduped: ElementsEventType[] = []+ for (const event of events) {+ const identity = `${event.type}:${event.hash}`+ if (seen.has(identity)) {+ continue}-- lastSelector = combinedSelector+ seen.add(identity)+ deduped.push(event)}-- return null+ return deduped}function aggregateAndSortElements(elements: CountedHTMLElement[]): CountedHTMLElement[] {diff --git a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsxindex d8ed236d50b7..8a605979aa85 100644--- a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx+++ b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx@@ -18,7 +18,7 @@ import { urls } from 'scenes/urls'import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'import { elementsLogic } from '~/toolbar/elements/elementsLogic'-import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'+import { ELEMENT_STATS_PAGE_LIMIT, heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'import { joinWithUiHost } from '~/toolbar/utils'@@ -270,6 +270,7 @@ export const HeatmapToolbarMenu = (): JSX.Element => {type="secondary"size="small"onClick={loadMoreElementStats}+ loading={elementStatsLoading}disabledReason={canLoadMoreElementStats ? undefined : 'Loaded all elements in this data range.'}@@ -309,6 +310,12 @@ export const HeatmapToolbarMenu = (): JSX.Element => {'!')}</div>+ {canLoadMoreElementStats && (+ <div className="mb-2 text-muted text-xs">+ Showing the top {ELEMENT_STATS_PAGE_LIMIT.toLocaleString()} element groups by click+ count — load more for the full data range.+ </div>+ )}<div className="flex flex-col w-full h-full">{countedElements.length ? (countedElements.map(({ element, count }, index) => {