: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(toolbar): load every page of click data from one button (#95575)
Paul D'Ambra32e494f4897d
diff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.mdindex 733106d9859f..dd1b05646dd1 100644--- a/frontend/src/toolbar/TELEMETRY.md+++ b/frontend/src/toolbar/TELEMETRY.md@@ -172,6 +172,23 @@ A user paginating emits one event per page with cumulative `event_count` — gro**File:** `elements/heatmapToolbarMenuLogic.ts`+### `toolbar heatmap load all started`++Fired when someone presses "Load all" in the heatmap menu to page through the remaining click data. No properties.++**File:** `stats/HeatmapToolbarMenu.tsx`++### `toolbar heatmap load all stopped`++Fired when someone presses "Stop loading" to end a run early. A run that ends on its own, or at the page cap, does not emit this.++| Property | Type | Description |+| --------------- | -------- | --------------------------------------------- |+| `pages_loaded` | `number` | Pages the run had loaded when it was stopped |+| `element_count` | `number` | Element stats rows loaded when it was stopped |++**File:** `stats/HeatmapToolbarMenu.tsx`+### `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).diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.tsindex 304c0f378d59..9d2f653e6d54 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts@@ -2,11 +2,13 @@ import { expectLogic } from 'kea-test-utils'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { initKeaTests } from '~/test/init'+import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { ElementsEventType } from '~/toolbar/types'import {+ LOAD_ALL_MAX_PAGES,buildElementStatsProperties,computeAreaCandidates,dedupeByChainIdentity,@@ -393,6 +395,145 @@ describe('heatmapToolbarMenuLogic', () => {}})+ it('loads every remaining page when load all starts, and ends the run on the last page', async () => {+ jest.spyOn(toolbarApi.elementStats, 'list').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=100', previous: null },+ } as any)+ const page = jest+ .spyOn(toolbarApi.elementStats, 'page')+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=200', previous: null },+ } as any)+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ data: { results: [], next: null, previous: null },+ } as any)++ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStatsSuccess',+ 'getElementStatsSuccess',+ ])++ await expectLogic(logic, () => logic.actions.startLoadingAllElementStats()).toDispatchActions([+ 'getElementStatsSuccess',+ ])+ expect(logic.values.loadingAllElementStats).toBe(true)++ await expectLogic(logic).toDispatchActions(['getElementStatsSuccess'])++ expect(page).toHaveBeenCalledTimes(2)+ expect(logic.values.loadingAllElementStats).toBe(false)+ })++ it('ends a run at the page cap, so one press cannot page forever', async () => {+ // every page reports another page, so only the cap can end the run+ jest.spyOn(toolbarApi.elementStats, 'list').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=100', previous: null },+ } as any)+ const page = jest.spyOn(toolbarApi.elementStats, 'page').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=200', previous: null },+ } as any)++ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStatsSuccess',+ 'getElementStatsSuccess',+ ])+ // the run outlasts the action history expectLogic can match against, so watch the value+ logic.actions.startLoadingAllElementStats()+ const deadline = Date.now() + 15000+ while (logic.values.loadingAllElementStats && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 50))+ }++ expect(page).toHaveBeenCalledTimes(LOAD_ALL_MAX_PAGES)+ expect(logic.values.loadingAllElementStats).toBe(false)+ // every page waits out the loader's debounce, so the whole run outlasts the default timeout+ }, 20000)++ it('ends the run when the page navigates', async () => {+ // every page reports another page, so only the navigation can end the run+ jest.spyOn(toolbarApi.elementStats, 'list').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=100', previous: null },+ } as any)+ jest.spyOn(toolbarApi.elementStats, 'page').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=200', previous: null },+ } as any)++ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStatsSuccess',+ 'getElementStatsSuccess',+ ])+ await expectLogic(logic, () => logic.actions.startLoadingAllElementStats()).toDispatchActions([+ 'getElementStatsSuccess',+ ])+ expect(logic.values.loadingAllElementStats).toBe(true)++ currentPageLogic.actions.setHref('http://localhost/another-page')+ expect(logic.values.loadingAllElementStats).toBe(false)+ })++ it('ends the run when a page comes back refused', async () => {+ jest.spyOn(toolbarApi.elementStats, 'list').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=100', previous: null },+ } as any)+ // a 403 resolves to the empty page, which carries no next link+ jest.spyOn(toolbarApi.elementStats, 'page').mockResolvedValue({ ok: false, status: 403 } as any)++ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStatsSuccess',+ 'getElementStatsSuccess',+ ])+ await expectLogic(logic, () => logic.actions.startLoadingAllElementStats()).toDispatchActions([+ 'getElementStatsSuccess',+ ])++ expect(logic.values.loadingAllElementStats).toBe(false)+ })++ it('requests no more pages after the run is stopped', async () => {+ // every page reports another page, so only the stop can end the run+ jest.spyOn(toolbarApi.elementStats, 'list').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=100', previous: null },+ } as any)+ const page = jest.spyOn(toolbarApi.elementStats, 'page').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: 'http://localhost/api/element/stats?offset=200', previous: null },+ } as any)++ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStatsSuccess',+ 'getElementStatsSuccess',+ ])++ await expectLogic(logic, () => logic.actions.startLoadingAllElementStats()).toDispatchActions([+ 'getElementStatsSuccess',+ ])+ logic.actions.stopLoadingAllElementStats()+ expect(logic.values.loadingAllElementStats).toBe(false)++ // long enough for the page already in flight to land and try to queue another+ await new Promise((resolve) => setTimeout(resolve, 500))+ expect(page).toHaveBeenCalledTimes(2)+ })+it('retries the initial load via load more after a stats fetch failure', async () => {// Deliberate loader failure — kea-loaders would log itsilenceKeaLoadersErrors()diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex e59f891276c2..d571c442317c 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -264,6 +264,11 @@ 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+// one press of "Load all" covers at most this many pages. Each page re-runs the matcher over every+// row loaded so far, so an uncapped run on a busy site grows its own cost with each page. The button+// comes back when the cap is reached, so a longer range takes another press rather than a hung tab.+export const LOAD_ALL_MAX_PAGES = 20+export type ClickmapProcessingTrigger = 'initial' | 'auto-load' | 'pagination' | 'refresh' | 'toggle'interface ElementProcessingCache {@@ -375,7 +380,9 @@ export interface heatmapToolbarMenuLogicValues {limit: numberurl: string | null} | null+ loadAllPagesLoaded: numberloadedElementStatsCount: number+ loadingAllElementStats: booleanmatchLinksByHref: booleanprocessedElements: CountedHTMLElement[]processingInputs: {@@ -572,12 +579,18 @@ export interface heatmapToolbarMenuLogicActions {startElementObservation: () => {value: true}+ startLoadingAllElementStats: () => {+ value: true+ }stepAreaHover: (direction: 'down' | 'up') => {direction: 'down' | 'up'}stopElementObservation: () => {value: true}+ stopLoadingAllElementStats: () => {+ value: true+ }toggleClickmapsEnabled: (enabled: boolean) => {enabled: boolean}@@ -687,6 +700,8 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([disableHeatmap: true,toggleClickmapsEnabled: (enabled: boolean) => ({ enabled }),loadMoreElementStats: true,+ startLoadingAllElementStats: true,+ stopLoadingAllElementStats: true,setMatchLinksByHref: (matchLinksByHref: boolean) => ({ matchLinksByHref }),loadAllEnabled: true,maybeLoadClickmap: true,@@ -795,6 +810,29 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([getElementStatsFailure: () => true, // so at least someone can recover from transient errors},],+ loadAllPagesLoaded: [+ 0,+ {+ startLoadingAllElementStats: () => 0,+ getElementStatsSuccess: (state) => state + 1,+ },+ ],+ loadingAllElementStats: [+ false,+ {+ startLoadingAllElementStats: () => true,+ stopLoadingAllElementStats: () => false,+ // the last page ends the run; a page that carries no next link at all ends it too,+ // so a refused request cannot leave the button reading "Stop loading" forever+ getElementStatsSuccess: (state, { elementStats }) => state && !!elementStats.next,+ getElementStatsFailure: () => false,+ resetElementStats: () => false,+ disableHeatmap: () => false,+ // the run belongs to the page and pattern it started on+ setHref: () => false,+ setWildcardHref: () => false,+ },+ ],heatmapEnabled: [false,{@@ -1363,6 +1401,11 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}},+ startLoadingAllElementStats: () => {+ // the first page starts the run; getElementStatsSuccess requests the next one+ actions.loadMoreElementStats()+ },+loadMoreElementStats: () => {if (values.elementStats?.next) {actions.getElementStats(values.elementStats.next)@@ -1385,6 +1428,17 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([// trigger refetches, so an auto-load result can never re-trigger itself.if (trigger === 'initial' && elementStats?.next && values.heatmapEnabled && values.clickmapsEnabled) {actions.getElementStats(null, ELEMENT_STATS_AUTO_LOAD_LIMIT)+ } else if (+ values.loadingAllElementStats &&+ elementStats?.next &&+ values.heatmapEnabled &&+ values.clickmapsEnabled+ ) {+ if (values.loadAllPagesLoaded >= LOAD_ALL_MAX_PAGES) {+ actions.stopLoadingAllElementStats()+ } else {+ actions.getElementStats(elementStats.next)+ }}},diff --git a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsxindex 4a00b036d4b0..63036dc707fa 100644--- a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx+++ b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx@@ -17,7 +17,7 @@ import { elementsLogic } from '~/toolbar/elements/elementsLogic'import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'import { heatmapCaptureLogic } from '~/toolbar/stats/heatmapCaptureLogic'-import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'+import { toolbarPosthogJS, useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'import { urls } from '~/toolbar/urls'import { joinWithUiHost } from '~/toolbar/utils'@@ -106,11 +106,14 @@ export const HeatmapToolbarMenu = (): JSX.Element => {processingProgress,areaSelectionActive,heatmapAreaFilter,+ loadingAllElementStats,+ loadAllPagesLoaded,} = useValues(heatmapToolbarMenuLogic)const {setCommonFilters,patchHeatmapFilters,- loadMoreElementStats,+ startLoadingAllElementStats,+ stopLoadingAllElementStats,setMatchLinksByHref,toggleClickmapsEnabled,setHeatmapFixedPositionMode,@@ -307,16 +310,34 @@ export const HeatmapToolbarMenu = (): JSX.Element => {</p><div className="flex items-center gap-2"><LemonButton- icon={<IconSync />}+ icon={loadingAllElementStats ? <Spinner textColored /> : <IconSync />}type="secondary"size="small"- onClick={loadMoreElementStats}- loading={elementStatsLoading}+ active={loadingAllElementStats}+ onClick={() => {+ if (loadingAllElementStats) {+ stopLoadingAllElementStats()+ toolbarPosthogJS.capture('toolbar heatmap load all stopped', {+ pages_loaded: loadAllPagesLoaded,+ element_count: loadedElementStatsCount,+ })+ return+ }+ startLoadingAllElementStats()+ toolbarPosthogJS.capture('toolbar heatmap load all started')+ }}+ // a loading button is disabled, and the run needs to stay stoppable+ loading={elementStatsLoading && !loadingAllElementStats}+ tooltip={+ loadingAllElementStats+ ? 'Stop after the page being loaded now. What loaded so far stays on the heatmap.'+ : 'Loads page after page of click data. A long date range or a busy site can take a while, and can need more than one run.'+ }disabledReason={canLoadMoreElementStats ? undefined : 'Loaded all elements in this data range.'}>- Load more+ {loadingAllElementStats ? 'Stop loading' : 'Load all'}</LemonButton><Tooltiptitle={