: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
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import type { PostHog } from 'posthog-js'
import type {
CommonFilters,
HeatmapFilters,
HeatmapFixedPositionMode,
ScrollDepthPosthogJsError,
} from 'lib/components/heatmaps/types'
import { elementsLogic } from '~/toolbar/shared/elements/elementsLogic'
import { heatmapToolbarMenuLogic } from '~/toolbar/shared/elements/heatmapToolbarMenuLogic'
import { currentPageLogic } from '~/toolbar/shared/stats/currentPageLogic'
import { heatmapCaptureLogic } from '~/toolbar/shared/stats/heatmapCaptureLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import type { CountedHTMLElement } from '~/toolbar/shared/types'
import type { CaptureProgress, CaptureSummary } from '../../../shared/stats/heatmapCaptureLogic'
import type { HeatmapSaveResult, PageToolbarHeatmapState } from '../../messaging/pageToolbarBridge'
export type PageHeatmapCommand =
| { type: 'set-wildcard-href'; href: string }
| { type: 'auto-wildcard-href' }
| { type: 'set-auto-wildcard-enabled'; enabled: boolean }
| { type: 'set-common-filters'; filters: CommonFilters }
| { type: 'patch-heatmap-filters'; filters: Partial<HeatmapFilters> }
| { type: 'set-clickmaps-enabled'; enabled: boolean }
| { type: 'set-match-links-by-href'; matchLinksByHref: boolean }
| { type: 'set-fixed-position-mode'; mode: HeatmapFixedPositionMode }
| { type: 'set-color-palette'; palette: string | null }
| { type: 'load-all-element-stats' }
| { type: 'stop-loading-all-element-stats' }
| { type: 'start-area-selection' }
| { type: 'cancel-area-selection' }
| { type: 'clear-area-filter' }
| { type: 'highlight-counted-element'; index: number | null }
| { type: 'select-counted-element'; index: number }
| { type: 'save-heatmap' }
const MAX_ELEMENT_TEXT_LENGTH = 255
type HeatmapFiltersState = Pick<
PageToolbarHeatmapState,
| 'wildcardHref'
| 'autoWildcardEnabled'
| 'wildcardHrefTooSpecific'
| 'wildcardHrefEndsWithSlash'
| 'commonFilters'
| 'heatmapFilters'
| 'heatmapColorPalette'
| 'heatmapFixedPositionMode'
| 'viewportRange'
| 'rawHeatmapLoading'
>
type HeatmapClickmapState = Pick<
PageToolbarHeatmapState,
| 'heatmapsCollection'
| 'scrollDepthPosthogJsError'
| 'clickmapsEnabled'
| 'clickmapLoading'
| 'processingProgress'
| 'matchLinksByHref'
| 'countedElements'
| 'clickCount'
| 'canLoadMoreElementStats'
>
type HeatmapAreaAndSaveState = Pick<
PageToolbarHeatmapState,
| 'loadedElementStatsCount'
| 'loadingAllElementStats'
| 'areaSelectionActive'
| 'areaFilter'
| 'savingHeatmap'
| 'saveProgress'
| 'saveResult'
>
type SaveOutcome = { status: 'saved'; shortId: string } | { status: 'failed'; error: string }
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageHeatmapLogicValues {
autoWildcardEnabled: boolean // currentPageLogic
wildcardHref: string // currentPageLogic
wildcardHrefEndsWithSlash: boolean // currentPageLogic
wildcardHrefTooSpecific: boolean // currentPageLogic
captureProgress: CaptureProgress | null // heatmapCaptureLogic
captureResultLoading: boolean // heatmapCaptureLogic
captureSummary: CaptureSummary | null // heatmapCaptureLogic
areaSelectionActive: boolean // heatmapToolbarMenuLogic
canLoadMoreElementStats: boolean // heatmapToolbarMenuLogic
clickCount: number // heatmapToolbarMenuLogic
clickmapsEnabled: boolean // heatmapToolbarMenuLogic
commonFilters: CommonFilters // heatmapToolbarMenuLogic
countedElements: CountedHTMLElement[] // heatmapToolbarMenuLogic
elementStatsLoading: boolean // heatmapToolbarMenuLogic
elementsLoading: boolean // heatmapToolbarMenuLogic
heatmapAreaFilter: {
element: HTMLElement
selector: string | null
} | null // heatmapToolbarMenuLogic
heatmapColorPalette: string | null // heatmapToolbarMenuLogic
heatmapFilters: HeatmapFilters // heatmapToolbarMenuLogic
heatmapFixedPositionMode: HeatmapFixedPositionMode // heatmapToolbarMenuLogic
loadedElementStatsCount: number // heatmapToolbarMenuLogic
loadingAllElementStats: boolean // heatmapToolbarMenuLogic
matchLinksByHref: boolean // heatmapToolbarMenuLogic
processingProgress: {
processed: number
total: number
} | null // heatmapToolbarMenuLogic
rawHeatmapLoading: boolean // heatmapToolbarMenuLogic
scrollDepthPosthogJsError: ScrollDepthPosthogJsError // heatmapToolbarMenuLogic
viewportRange: {
max: number
min: number
} // heatmapToolbarMenuLogic
posthog: PostHog | null // toolbarConfigLogic
areaAndSaveState: HeatmapAreaAndSaveState
clickmapState: HeatmapClickmapState
countedElementInfos: PageToolbarHeatmapState['countedElements']
filtersState: HeatmapFiltersState
heatmapsCollection: PageToolbarHeatmapState['heatmapsCollection']
pageState: PageToolbarHeatmapState
saveOutcome: SaveOutcome | null
saveResult: HeatmapSaveResult | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageHeatmapLogicActions {
saveToPostHogFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
} // heatmapCaptureLogic
saveToPostHogSuccess: (
captureResult: {
id: string
short_id: string
},
payload?: any
) => {
captureResult: {
id: string
short_id: string
}
payload?: any
} // heatmapCaptureLogic
handleCommand: (command: PageHeatmapCommand) => {
command: PageHeatmapCommand
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageHeatmapLogicMeta {
__keaTypeGenInternalSelectorTypes: {
heatmapsCollection: (posthog: PostHog | null) => PageToolbarHeatmapState['heatmapsCollection']
countedElementInfos: (countedElements: CountedHTMLElement[]) => PageToolbarHeatmapState['countedElements']
saveResult: (saveOutcome: SaveOutcome | null, captureSummary: CaptureSummary | null) => HeatmapSaveResult | null
filtersState: (
wildcardHref: string,
autoWildcardEnabled: boolean,
wildcardHrefTooSpecific: boolean,
wildcardHrefEndsWithSlash: boolean,
commonFilters: CommonFilters,
heatmapFilters: HeatmapFilters,
heatmapColorPalette: string | null,
heatmapFixedPositionMode: HeatmapFixedPositionMode,
viewportRange: {
max: number
min: number
},
rawHeatmapLoading: boolean
) => HeatmapFiltersState
clickmapState: (
heatmapsCollection: 'disabled' | 'enabled' | 'unknown' | 'unsupported',
scrollDepthPosthogJsError: ScrollDepthPosthogJsError,
clickmapsEnabled: boolean,
elementStatsLoading: boolean,
elementsLoading: boolean,
processingProgress: {
processed: number
total: number
} | null,
matchLinksByHref: boolean,
countedElementInfos: {
count: number
tagName: string
text: string
}[],
clickCount: number,
canLoadMoreElementStats: boolean
) => HeatmapClickmapState
areaAndSaveState: (
loadedElementStatsCount: number,
loadingAllElementStats: boolean,
areaSelectionActive: boolean,
heatmapAreaFilter: {
element: HTMLElement
selector: string | null
} | null,
captureResultLoading: boolean,
captureProgress: CaptureProgress | null,
saveResult: HeatmapSaveResult | null
) => HeatmapAreaAndSaveState
pageState: (
filtersState: HeatmapFiltersState,
clickmapState: HeatmapClickmapState,
areaAndSaveState: HeatmapAreaAndSaveState
) => PageToolbarHeatmapState
}
}
export type extensionPageHeatmapLogicType = MakeLogicType<
extensionPageHeatmapLogicValues,
extensionPageHeatmapLogicActions,
Record<string, any>,
extensionPageHeatmapLogicMeta
>
/** Runs in the content script, next to the toolbar's heatmap logics. */
export const extensionPageHeatmapLogic = kea<extensionPageHeatmapLogicType>([
path(['toolbar', 'extension', 'extensionPageHeatmapLogic']),
connect(() => ({
values: [
currentPageLogic,
['wildcardHref', 'autoWildcardEnabled', 'wildcardHrefTooSpecific', 'wildcardHrefEndsWithSlash'],
heatmapToolbarMenuLogic,
[
'commonFilters',
'heatmapFilters',
'heatmapColorPalette',
'heatmapFixedPositionMode',
'viewportRange',
'rawHeatmapLoading',
'scrollDepthPosthogJsError',
'clickmapsEnabled',
'elementStatsLoading',
'elementsLoading',
'processingProgress',
'matchLinksByHref',
'countedElements',
'clickCount',
'canLoadMoreElementStats',
'loadedElementStatsCount',
'loadingAllElementStats',
'areaSelectionActive',
'heatmapAreaFilter',
],
toolbarConfigLogic,
['posthog'],
heatmapCaptureLogic,
['captureResultLoading', 'captureProgress', 'captureSummary'],
],
actions: [heatmapCaptureLogic, ['saveToPostHogSuccess', 'saveToPostHogFailure']],
})),
actions({
handleCommand: (command: PageHeatmapCommand) => ({ command }),
}),
reducers({
saveOutcome: [
null as SaveOutcome | null,
{
saveToPostHogSuccess: (_, { captureResult }) =>
captureResult ? { status: 'saved', shortId: captureResult.short_id } : null,
saveToPostHogFailure: (_, { error }) => ({ status: 'failed', error }),
},
],
}),
selectors({
heatmapsCollection: [
(s) => [s.posthog],
(posthog: PostHog | null): PageToolbarHeatmapState['heatmapsCollection'] =>
!posthog
? 'unknown'
: !posthog.heatmaps
? 'unsupported'
: posthog.heatmaps.isEnabled
? 'enabled'
: 'disabled',
],
// Reading `innerText` lays out the page, so it runs only when the counted elements change.
countedElementInfos: [
(s) => [s.countedElements],
(countedElements: CountedHTMLElement[]): PageToolbarHeatmapState['countedElements'] =>
countedElements.map(({ element, count }) => ({
text: element.innerText?.trim().substring(0, MAX_ELEMENT_TEXT_LENGTH) ?? '',
tagName: element.tagName.toLowerCase(),
count,
})),
],
saveResult: [
(s) => [s.saveOutcome, s.captureSummary],
(
saveOutcome: SaveOutcome | null,
captureSummary: { savedWidths: number; totalWidths: number } | null
): HeatmapSaveResult | null =>
saveOutcome?.status === 'saved'
? {
...saveOutcome,
savedWidths: captureSummary?.savedWidths ?? 0,
totalWidths: captureSummary?.totalWidths ?? 0,
}
: saveOutcome,
],
// kea types a selector with up to about a dozen inputs, so the slice comes from three smaller ones.
filtersState: [
(s) => [
s.wildcardHref,
s.autoWildcardEnabled,
s.wildcardHrefTooSpecific,
s.wildcardHrefEndsWithSlash,
s.commonFilters,
s.heatmapFilters,
s.heatmapColorPalette,
s.heatmapFixedPositionMode,
s.viewportRange,
s.rawHeatmapLoading,
],
(
wildcardHref: string,
autoWildcardEnabled: boolean,
wildcardHrefTooSpecific: boolean,
wildcardHrefEndsWithSlash: boolean,
commonFilters: CommonFilters,
heatmapFilters: HeatmapFilters,
heatmapColorPalette: string | null,
heatmapFixedPositionMode: HeatmapFixedPositionMode,
viewportRange: { min: number; max: number },
rawHeatmapLoading: boolean
): HeatmapFiltersState => ({
wildcardHref,
autoWildcardEnabled,
wildcardHrefTooSpecific,
wildcardHrefEndsWithSlash,
commonFilters,
heatmapFilters,
heatmapColorPalette,
heatmapFixedPositionMode,
viewportRange,
rawHeatmapLoading,
}),
],
clickmapState: [
(s) => [
s.heatmapsCollection,
s.scrollDepthPosthogJsError,
s.clickmapsEnabled,
s.elementStatsLoading,
s.elementsLoading,
s.processingProgress,
s.matchLinksByHref,
s.countedElementInfos,
s.clickCount,
s.canLoadMoreElementStats,
],
(
heatmapsCollection: PageToolbarHeatmapState['heatmapsCollection'],
scrollDepthPosthogJsError: ScrollDepthPosthogJsError,
clickmapsEnabled: boolean,
elementStatsLoading: boolean,
elementsLoading: boolean,
processingProgress: PageToolbarHeatmapState['processingProgress'],
matchLinksByHref: boolean,
countedElementInfos: PageToolbarHeatmapState['countedElements'],
clickCount: number,
canLoadMoreElementStats: boolean
): HeatmapClickmapState => ({
heatmapsCollection,
scrollDepthPosthogJsError,
clickmapsEnabled,
clickmapLoading: elementStatsLoading || elementsLoading,
processingProgress,
matchLinksByHref,
countedElements: countedElementInfos,
clickCount,
canLoadMoreElementStats,
}),
],
areaAndSaveState: [
(s) => [
s.loadedElementStatsCount,
s.loadingAllElementStats,
s.areaSelectionActive,
s.heatmapAreaFilter,
s.captureResultLoading,
s.captureProgress,
s.saveResult,
],
(
loadedElementStatsCount: number,
loadingAllElementStats: boolean,
areaSelectionActive: boolean,
heatmapAreaFilter: { element: HTMLElement; selector: string | null } | null,
captureResultLoading: boolean,
captureProgress: PageToolbarHeatmapState['saveProgress'],
saveResult: HeatmapSaveResult | null
): HeatmapAreaAndSaveState => ({
loadedElementStatsCount,
loadingAllElementStats,
areaSelectionActive,
areaFilter: heatmapAreaFilter
? { selector: heatmapAreaFilter.selector, tagName: heatmapAreaFilter.element.tagName.toLowerCase() }
: null,
savingHeatmap: captureResultLoading,
saveProgress: captureProgress,
saveResult,
}),
],
pageState: [
(s) => [s.filtersState, s.clickmapState, s.areaAndSaveState],
(
filtersState: HeatmapFiltersState,
clickmapState: HeatmapClickmapState,
areaAndSaveState: HeatmapAreaAndSaveState
): PageToolbarHeatmapState => ({
...filtersState,
...clickmapState,
...areaAndSaveState,
}),
],
}),
listeners(({ values }) => ({
handleCommand: ({ command }) => {
const heatmap = heatmapToolbarMenuLogic.actions
const page = currentPageLogic.actions
switch (command.type) {
case 'set-wildcard-href':
page.setWildcardHref(command.href)
return
case 'auto-wildcard-href':
page.autoWildcardHref()
return
case 'set-auto-wildcard-enabled':
page.setAutoWildcardEnabled(command.enabled)
return
case 'set-common-filters':
heatmap.setCommonFilters(command.filters)
return
case 'patch-heatmap-filters':
heatmap.patchHeatmapFilters(command.filters)
return
case 'set-clickmaps-enabled':
heatmap.toggleClickmapsEnabled(command.enabled)
return
case 'set-match-links-by-href':
heatmap.setMatchLinksByHref(command.matchLinksByHref)
return
case 'set-fixed-position-mode':
heatmap.setHeatmapFixedPositionMode(command.mode)
return
case 'set-color-palette':
heatmap.setHeatmapColorPalette(command.palette)
return
case 'load-all-element-stats':
heatmap.startLoadingAllElementStats()
return
case 'stop-loading-all-element-stats':
heatmap.stopLoadingAllElementStats()
return
case 'start-area-selection':
heatmap.startAreaSelection()
return
case 'cancel-area-selection':
heatmap.cancelAreaSelection()
return
case 'clear-area-filter':
heatmap.selectHeatmapAreaFilter(null)
return
case 'highlight-counted-element':
elementsLogic.actions.setHighlightElement(
command.index === null ? null : (values.countedElements[command.index]?.element ?? null)
)
return
case 'select-counted-element': {
const element = values.countedElements[command.index]?.element
if (element) {
element.scrollIntoView({ block: 'center', behavior: 'smooth' })
elementsLogic.actions.setSelectedElement(element)
}
return
}
case 'save-heatmap':
heatmapCaptureLogic.actions.saveToPostHog()
return
}
},
})),
])