: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, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { windowValues } from 'kea-window-values'
import { PostHog } from 'posthog-js'
import { hedgehogModeLogic } from 'lib/components/HedgehogMode/hedgehogModeLogic'
import { HedgehogActor } from 'lib/components/HedgehogMode/types'
import { PostHogAppToolbarEvent } from 'lib/components/IframedToolbarBrowser/utils'
import { actionsLogic } from '~/toolbar/shared/actions/actionsLogic'
import { actionsTabLogic } from '~/toolbar/shared/actions/actionsTabLogic'
import { elementsLogic } from '~/toolbar/shared/elements/elementsLogic'
import { heatmapToolbarMenuLogic } from '~/toolbar/shared/elements/heatmapToolbarMenuLogic'
import { experimentsLogic } from '~/toolbar/shared/experiments/experimentsLogic'
import { experimentsTabLogic } from '~/toolbar/shared/experiments/experimentsTabLogic'
import { fieldNotesLogic } from '~/toolbar/shared/field-notes/fieldNotesLogic'
import { flagsToolbarLogic } from '~/toolbar/shared/flags/flagsToolbarLogic'
import { productToursLogic } from '~/toolbar/shared/product-tours/productToursLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import { isToolbarFeatureGated, toolbarEntitlementsLogic } from '~/toolbar/shared/toolbarEntitlementsLogic'
import { toolbarLogger } from '~/toolbar/shared/toolbarLogger'
import { toolbarPosthogJS } from '~/toolbar/shared/toolbarPosthogJS'
import { TOOLBAR_CONTAINER_CLASS, TOOLBAR_ID, inBounds, makeNavigateWrapper } from '~/toolbar/shared/utils'
import { webVitalsToolbarLogic } from '~/toolbar/shared/web-vitals/webVitalsToolbarLogic'
import { AvailableFeature } from '~/types'
import type { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from '../../../lib/components/heatmaps/types'
import type { HedgehogModeInterface } from '../../../lib/components/HedgehogMode/types'
import type { ActionType } from '../../../types'
import { DEFAULT_PII_MASKING_COLOR, applyPiiMaskingStylesheet, getPiiMaskingWarnings } from './piiMaskingStyles'
const MARGIN = 2
const HEDGEHOG_OFFSET = 80
const PII_MASKING_STYLESHEET_ID = 'posthog-pii-masking-styles'
export type MenuState =
| 'none'
| 'heatmap'
| 'actions'
| 'flags'
| 'inspect'
| 'hedgehog'
| 'debugger'
| 'experiments'
| 'web-vitals'
| 'product-tours'
| 'field-notes'
export type ToolbarPositionType =
| 'top-left'
| 'top-center'
| 'top-right'
| 'bottom-left'
| 'bottom-center'
| 'bottom-right'
| 'left-center'
| 'right-center'
export const TOOLBAR_FIXED_POSITION_HITBOX = 100
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarLogicValues {
allActionsLoading: boolean // actionsLogic
allExperimentsLoading: boolean // experimentsLogic
userFlagsLoading: boolean // flagsToolbarLogic
elementStatsLoading: boolean // heatmapToolbarMenuLogic
isRefreshing: boolean // heatmapToolbarMenuLogic
rawHeatmapLoading: boolean // heatmapToolbarMenuLogic
hedgehogMode: HedgehogModeInterface | null // hedgehogModeLogic
posthog: PostHog | null // toolbarConfigLogic
remoteWebVitalsLoading: boolean // webVitalsToolbarLogic
cspBlocksNewFunction: boolean
currentPathname: string
element: HTMLElement | null
fixedPosition: ToolbarPositionType
fixedPositions: Record<
ToolbarPositionType,
{
x: number
y: number
}
>
getHedgehogActor: () => HedgehogActor | null
hedgehogModeAvailable: boolean
hedgehogModeEnabled: boolean
isBlurred: boolean
isDragging: boolean
isEmbeddedInApp: boolean
isExiting: boolean
isLoading: boolean
lastDragPosition: {
x: number
y: number
} | null
menu: HTMLElement | null
menuProperties:
| {
isBelow: boolean
maxHeight: number
transform: string
}
| {
isBelow?: undefined
maxHeight?: undefined
transform?: undefined
}
minimized: boolean
piiMaskingColor: string
piiMaskingEnabled: boolean
piiWarning: string[] | null
position: {
x: number
y: number
}
theme: 'dark' | 'light'
visibleMenu: MenuState
windowHeight: number
windowWidth: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarLogicActions {
actionCreatedSuccess: (action: ActionType) => {
action: ActionType
} // actionsTabLogic
hideButtonActions: () => {
value: true
} // actionsTabLogic
selectAction: (id: number | null) => {
id: number | null
} // actionsTabLogic
setAutomaticActionCreationEnabled: (
enabled: boolean,
name?: string | undefined
) => {
enabled: boolean
name: string | undefined
} // actionsTabLogic
showButtonActions: () => {
value: true
} // actionsTabLogic
createAction: (element: HTMLElement) => {
element: HTMLElement
} // elementsLogic
disableInspect: () => {
value: true
} // elementsLogic
enableInspect: () => {
value: true
} // elementsLogic
showButtonExperiments: () => {
value: true
} // experimentsTabLogic
hideButtonFieldNotes: () => {
value: true
} // fieldNotesLogic
showButtonFieldNotes: () => {
value: true
} // fieldNotesLogic
disableHeatmap: () => {
value: true
} // heatmapToolbarMenuLogic
enableHeatmap: () => {
value: true
} // heatmapToolbarMenuLogic
patchHeatmapFilters: (filters: Partial<HeatmapFilters>) => {
filters: Partial<HeatmapFilters>
} // heatmapToolbarMenuLogic
setCommonFilters: (filters: CommonFilters) => {
filters: CommonFilters
} // heatmapToolbarMenuLogic
setHeatmapColorPalette: (palette: string | null) => {
palette: string | null
} // heatmapToolbarMenuLogic
setHeatmapFixedPositionMode: (mode: HeatmapFixedPositionMode) => {
mode: HeatmapFixedPositionMode
} // heatmapToolbarMenuLogic
toggleClickmapsEnabled: (enabled: boolean) => {
enabled: boolean
} // heatmapToolbarMenuLogic
hideButtonProductTours: () => {
value: true
} // productToursLogic
showButtonProductTours: () => {
value: true
} // productToursLogic
logout: () => {
value: true
} // toolbarConfigLogic
setOAuthTokens: (
accessToken: string,
refreshToken: string | null,
clientId: string
) => {
accessToken: string
clientId: string
refreshToken: string | null
} // toolbarConfigLogic
completeGracefulExit: () => {
value: true
}
maybeSendNavigationMessage: () => {
value: true
}
onMouseOrTouchDown: (event: MouseEvent | TouchEvent) => {
event: MouseEvent | TouchEvent
}
openHedgehogOptions: () => {
value: true
}
setCspBlocksNewFunction: (blocked: boolean) => {
blocked: boolean
}
setCurrentPathname: (pathname: string) => {
pathname: string
}
setDragPosition: (
x: number,
y: number
) => {
x: number
y: number
}
setDragging: (dragging?: any) => {
dragging: any
}
setElement: (element: HTMLElement | null) => {
element: HTMLElement | null
}
setFixedPosition: (position: ToolbarPositionType) => {
position: ToolbarPositionType
}
setHedgehogModeEnabled: (hedgehogModeEnabled: boolean) => {
hedgehogModeEnabled: boolean
}
setIsBlurred: (isBlurred: boolean) => {
isBlurred: boolean
}
setIsEmbeddedInApp: (isEmbedded: boolean) => {
isEmbedded: boolean
}
setMenu: (element: HTMLElement | null) => {
element: HTMLElement | null
}
setPiiMaskingColor: (color: string) => {
color: string
}
setVisibleMenu: (visibleMenu: MenuState) => {
visibleMenu: MenuState
}
startGracefulExit: () => {
value: true
}
syncHeatmapGate: () => {
value: true
}
syncWithHedgehog: () => {
value: true
}
toggleMinimized: (minimized?: boolean) => {
minimized: boolean | undefined
}
togglePiiMasking: (enabled?: boolean) => {
enabled: boolean | undefined
}
toggleTheme: (theme?: 'dark' | 'light') => {
theme: 'dark' | 'light' | undefined
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarLogicMeta {
__keaTypeGenInternalSelectorTypes: {
position: (
element: HTMLElement | null,
lastDragPosition: {
x: number
y: number
} | null,
windowWidth: number,
windowHeight: number,
fixedPosition: ToolbarPositionType,
fixedPositions: Record<
ToolbarPositionType,
{
x: number
y: number
}
>,
minimized: boolean
) => {
x: number
y: number
}
fixedPositions: (
windowWidth: number,
windowHeight: number
) => Record<
ToolbarPositionType,
{
x: number
y: number
}
>
menuProperties: (
element: HTMLElement | null,
menu: HTMLElement | null,
position: {
x: number
y: number
},
windowWidth: number,
windowHeight: number,
isBlurred: boolean
) =>
| {
isBelow: boolean
maxHeight: number
transform: string
}
| {
isBelow?: undefined
maxHeight?: undefined
transform?: undefined
}
getHedgehogActor: (hedgehogMode: HedgehogModeInterface | null) => () => HedgehogActor | null
piiWarning: (posthog: PostHog | null, piiMaskingEnabled: boolean) => string[] | null
isLoading: (
elementStatsLoading: boolean,
rawHeatmapLoading: boolean,
isRefreshing: boolean,
allActionsLoading: boolean,
userFlagsLoading: boolean,
allExperimentsLoading: boolean,
remoteWebVitalsLoading: boolean
) => boolean
hedgehogModeAvailable: (cspBlocksNewFunction: boolean) => boolean
}
}
export type toolbarLogicType = MakeLogicType<
toolbarLogicValues,
toolbarLogicActions,
Record<string, any>,
toolbarLogicMeta
>
export const toolbarLogic = kea<toolbarLogicType>([
path(['toolbar', 'bar', 'toolbarLogic']),
connect(() => ({
values: [
toolbarConfigLogic,
['posthog'],
heatmapToolbarMenuLogic,
['elementStatsLoading', 'rawHeatmapLoading', 'isRefreshing'],
actionsLogic,
['allActionsLoading'],
flagsToolbarLogic,
['userFlagsLoading'],
experimentsLogic,
['allExperimentsLoading'],
webVitalsToolbarLogic,
['remoteWebVitalsLoading'],
hedgehogModeLogic,
['hedgehogMode'],
],
actions: [
toolbarConfigLogic,
['logout', 'setOAuthTokens'],
actionsTabLogic,
[
'showButtonActions',
'hideButtonActions',
'selectAction',
'setAutomaticActionCreationEnabled',
'actionCreatedSuccess',
],
experimentsTabLogic,
['showButtonExperiments'],
elementsLogic,
['enableInspect', 'disableInspect', 'createAction'],
productToursLogic,
['showButtonProductTours', 'hideButtonProductTours'],
fieldNotesLogic,
['showButtonFieldNotes', 'hideButtonFieldNotes'],
heatmapToolbarMenuLogic,
[
'enableHeatmap',
'disableHeatmap',
'patchHeatmapFilters',
'setHeatmapFixedPositionMode',
'setHeatmapColorPalette',
'setCommonFilters',
'toggleClickmapsEnabled',
],
],
})),
actions(() => ({
toggleTheme: (theme?: 'light' | 'dark') => ({ theme }),
toggleMinimized: (minimized?: boolean) => ({ minimized }),
setHedgehogModeEnabled: (hedgehogModeEnabled: boolean) => ({ hedgehogModeEnabled }),
setDragPosition: (x: number, y: number) => ({ x, y }),
syncWithHedgehog: true,
syncHeatmapGate: true,
openHedgehogOptions: true,
setVisibleMenu: (visibleMenu: MenuState) => ({
visibleMenu,
}),
onMouseOrTouchDown: (event: MouseEvent | TouchEvent) => ({ event }),
setDragging: (dragging = true) => ({ dragging }),
setElement: (element: HTMLElement | null) => ({ element }),
setMenu: (element: HTMLElement | null) => ({ element }),
setIsBlurred: (isBlurred: boolean) => ({ isBlurred }),
setIsEmbeddedInApp: (isEmbedded: boolean) => ({ isEmbedded }),
setFixedPosition: (position: ToolbarPositionType) => ({ position }),
setCurrentPathname: (pathname: string) => ({ pathname }),
maybeSendNavigationMessage: true,
togglePiiMasking: (enabled?: boolean) => ({ enabled }),
setPiiMaskingColor: (color: string) => ({ color }),
startGracefulExit: true,
completeGracefulExit: true,
setCspBlocksNewFunction: (blocked: boolean) => ({ blocked }),
})),
windowValues(() => ({
windowHeight: (window: Window) => window.innerHeight,
windowWidth: (window: Window) =>
Math.min(window.innerWidth, window.document.body?.clientWidth ?? window.innerWidth),
})),
reducers(() => ({
element: [
null as HTMLElement | null,
{
setElement: (_, { element }) => element,
},
],
menu: [
null as HTMLElement | null,
{
setMenu: (_, { element }) => element,
},
],
visibleMenu: [
'none' as MenuState,
{
setVisibleMenu: (_, { visibleMenu }) => visibleMenu,
},
],
minimized: [
false,
{ persist: true },
{
toggleMinimized: (state, { minimized }) => minimized ?? !state,
},
],
// Whether the toolbar is not in focus anymore (typically due to clicking elsewhere)
isBlurred: [
false,
{
setIsBlurred: (_, { isBlurred }) => isBlurred,
setVisibleMenu: () => false,
},
],
theme: [
'dark' as 'light' | 'dark',
{ persist: true },
{
toggleTheme: (state, { theme }) => theme ?? (state === 'light' ? 'dark' : 'light'),
},
],
isDragging: [
false,
{
setDragging: (_, { dragging }) => dragging,
},
],
lastDragPosition: [
null as null | {
x: number
y: number
},
{ persist: true },
{
setDragPosition: (_, { x, y }) => ({ x, y }),
setFixedPosition: () => null,
},
],
fixedPosition: [
'bottom-center' as ToolbarPositionType,
{ persist: true },
{
setFixedPosition: (_, { position }) => position,
},
],
hedgehogModeEnabled: [
false,
{ persist: true },
{
setHedgehogModeEnabled: (_, { hedgehogModeEnabled }) => hedgehogModeEnabled,
setCspBlocksNewFunction: (state, { blocked }) => (blocked ? false : state), // if the CSP blocks new Function, disable hedgehod mode
},
],
isEmbeddedInApp: [
false,
{
setIsEmbeddedInApp: (_, { isEmbedded }) => isEmbedded,
},
],
currentPathname: [
'',
{
setCurrentPathname: (_, { pathname }) => pathname,
},
],
piiMaskingEnabled: [
false,
{ persist: true },
{
togglePiiMasking: (state, { enabled }) => enabled ?? !state,
},
],
piiMaskingColor: [
DEFAULT_PII_MASKING_COLOR as string,
{ persist: true },
{
setPiiMaskingColor: (_, { color }) => color,
},
],
isExiting: [
false,
{
startGracefulExit: () => true,
completeGracefulExit: () => false,
},
],
cspBlocksNewFunction: [
false,
{
setCspBlocksNewFunction: (_, { blocked }) => blocked,
},
],
})),
selectors({
position: [
(s) => [
s.element,
s.lastDragPosition,
s.windowWidth,
s.windowHeight,
s.fixedPosition,
s.fixedPositions,
s.minimized,
],
(
element: HTMLElement | null,
lastDragPosition: {
x: number
y: number
} | null,
windowWidth: number,
windowHeight: number,
fixedPosition: ToolbarPositionType,
fixedPositions: Record<
ToolbarPositionType,
{
x: number
y: number
}
>,
minimized: boolean
) => {
const position = lastDragPosition ?? fixedPositions[fixedPosition]
const width = element
? parseInt(
getComputedStyle(element)
.getPropertyValue(minimized ? '--toolbar-width-minimized' : '--toolbar-width-expanded')
.replace('px', '')
)
: 40
const height = element?.offsetHeight ?? 40
const xPadding = width * 0.5 + 10
const yPadding = height * 0.5 + 10
return {
x: inBounds(xPadding, position.x, windowWidth - xPadding),
y: inBounds(yPadding, position.y, windowHeight - yPadding),
}
},
],
fixedPositions: [
(s) => [s.windowWidth, s.windowHeight],
(windowWidth: number, windowHeight: number): Record<ToolbarPositionType, { x: number; y: number }> => {
return {
'top-left': {
x: 0,
y: 0,
},
'top-center': {
x: windowWidth / 2,
y: 0,
},
'top-right': {
x: windowWidth,
y: 0,
},
'bottom-left': {
x: 0,
y: windowHeight,
},
'bottom-center': {
x: windowWidth / 2,
y: windowHeight,
},
'bottom-right': {
x: windowWidth,
y: windowHeight,
},
'left-center': {
x: 0,
y: windowHeight / 2,
},
'right-center': {
x: windowWidth,
y: windowHeight / 2,
},
}
},
],
menuProperties: [
(s) => [s.element, s.menu, s.position, s.windowWidth, s.windowHeight, s.isBlurred],
(
element: HTMLElement | null,
menu: HTMLElement | null,
position: {
x: number
y: number
},
windowWidth: number,
windowHeight: number,
isBlurred: boolean
) => {
if (!element || !menu) {
return {}
}
const margin = 10
const marginFromPosition = element.offsetHeight * 0.5 + margin
const isBelow = position.y < windowHeight * 0.5
// Max space we could fill
const spaceAboveOrBelow = isBelow ? windowHeight - position.y : position.y
// Then we remove some margins and half the height of the element
const maxDesiredHeight = spaceAboveOrBelow - margin - marginFromPosition
// Finally we don't want it to end up too big
const finalHeight = isBlurred ? 0 : inBounds(0, maxDesiredHeight, windowHeight * 0.6)
const desiredY = isBelow ? position.y + marginFromPosition : position.y - marginFromPosition
const desiredX = position.x
const top = inBounds(MARGIN, desiredY, windowHeight)
const left = inBounds(
MARGIN + menu.clientWidth * 0.5,
desiredX,
windowWidth - menu.clientWidth * 0.5 - MARGIN
)
return {
transform: `translate(${left}px, ${top}px)`,
maxHeight: finalHeight,
isBelow,
}
},
],
getHedgehogActor: [
(s) => [s.hedgehogMode],
(
hedgehogMode: null | import('lib/components/HedgehogMode/types').HedgehogModeInterface
): (() => HedgehogActor | null) => {
return () => {
const player = hedgehogMode?.stateManager?.getPlayerHedgehogActor()
if (!player || !player.rigidBody) {
return null
}
return player
}
},
],
piiWarning: [
(s) => [s.posthog, s.piiMaskingEnabled],
(posthog: PostHog | null, piiMaskingEnabled: boolean) => {
if (!posthog || !piiMaskingEnabled) {
return null
}
return getPiiMaskingWarnings(posthog)
},
],
isLoading: [
(s) => [
s.elementStatsLoading,
s.rawHeatmapLoading,
s.isRefreshing,
s.allActionsLoading,
s.userFlagsLoading,
s.allExperimentsLoading,
s.remoteWebVitalsLoading,
],
(
elementStatsLoading: boolean,
rawHeatmapLoading: boolean,
isRefreshing: boolean,
allActionsLoading: boolean,
userFlagsLoading: boolean,
allExperimentsLoading: boolean,
remoteWebVitalsLoading: boolean
) =>
elementStatsLoading ||
rawHeatmapLoading ||
isRefreshing ||
allActionsLoading ||
userFlagsLoading ||
allExperimentsLoading ||
remoteWebVitalsLoading,
],
hedgehogModeAvailable: [
(s) => [s.cspBlocksNewFunction],
(cspBlocksNewFunction: boolean): boolean => !cspBlocksNewFunction,
],
}),
listeners(({ actions, values }) => ({
[toolbarEntitlementsLogic.actionTypes.loadEntitlements]: () => {
if (isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')) {
actions.disableHeatmap()
}
},
[toolbarEntitlementsLogic.actionTypes.loadEntitlementsSuccess]: () => {
actions.syncHeatmapGate()
},
// Both halves of the gate move on their own: the entitlement arrives as an action, the
// rollout flag as a posthog-js callback. An open heatmap has to follow either one.
syncHeatmapGate: () => {
if (values.visibleMenu !== 'heatmap') {
return
}
const gated = isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')
if (gated) {
actions.disableHeatmap()
} else {
actions.enableHeatmap()
}
values.getHedgehogActor()?.setOnFire(gated ? 0 : 1)
},
setOAuthTokens: () => {
if (values.minimized) {
actions.toggleMinimized(false)
}
},
setVisibleMenu: ({ visibleMenu }, _, __, previousState) => {
const previousMenu = toolbarLogic.selectors.visibleMenu(previousState)
if (visibleMenu !== 'none') {
toolbarPosthogJS.capture('toolbar menu opened', { menu: visibleMenu, previous_menu: previousMenu })
} else if (previousMenu !== 'none') {
toolbarPosthogJS.capture('toolbar menu closed', { menu: previousMenu })
}
actions.disableInspect()
actions.disableHeatmap()
actions.hideButtonActions()
actions.hideButtonProductTours()
actions.hideButtonFieldNotes()
if (visibleMenu === 'heatmap') {
if (!isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')) {
actions.enableHeatmap()
values.getHedgehogActor()?.setOnFire(1)
}
} else if (visibleMenu === 'actions') {
actions.showButtonActions()
} else if (visibleMenu === 'experiments') {
actions.showButtonExperiments()
} else if (visibleMenu === 'flags') {
} else if (visibleMenu === 'inspect') {
actions.enableInspect()
} else if (visibleMenu === 'product-tours') {
actions.showButtonProductTours()
} else if (visibleMenu === 'field-notes') {
actions.showButtonFieldNotes()
}
},
onMouseOrTouchDown: ({ event }) => {
const isTouchEvent = 'touches' in event
if (!values.element || (!isTouchEvent && event.button !== 0)) {
return
}
const touchX = isTouchEvent ? event.touches[0].pageX : event.pageX
const touchY = isTouchEvent ? event.touches[0].pageY : event.pageY
const offsetX = touchX - values.position.x
const offsetY = touchY - values.position.y
let movedCount = 0
const moveThreshold = 5
const onMove = (moveEvent: MouseEvent | TouchEvent): void => {
movedCount += 1
const isMoveTouchEvent = 'touches' in moveEvent
const moveTouchX = isMoveTouchEvent ? moveEvent.touches[0].pageX : moveEvent.pageX
const moveTouchY = isMoveTouchEvent ? moveEvent.touches[0].pageY : moveEvent.pageY
if (movedCount > moveThreshold) {
actions.setDragging(true)
// Set drag position offset by where we clicked and where the element is
// Check if near any of the fixed positions and set to them if so, otherwise set to mouse position
const fixedPositions = values.fixedPositions
let closestPosition: ToolbarPositionType | null = null
for (const [position, { x, y }] of Object.entries(fixedPositions)) {
const distance = Math.sqrt((moveTouchX - x) ** 2 + (moveTouchY - y) ** 2)
if (distance < TOOLBAR_FIXED_POSITION_HITBOX) {
closestPosition = position as ToolbarPositionType
break
}
}
if (closestPosition) {
actions.setFixedPosition(closestPosition)
} else {
actions.setDragPosition(moveTouchX - offsetX, moveTouchY - offsetY)
}
}
}
if (isTouchEvent) {
const onTouchEnd = (): void => {
actions.setDragging(false)
values.element?.removeEventListener('touchmove', onMove)
values.element?.removeEventListener('touchend', onTouchEnd)
}
values.element.addEventListener('touchmove', onMove, { passive: true })
values.element.addEventListener('touchend', onTouchEnd)
} else {
const onMouseUp = (e: MouseEvent): void => {
if (e.button === 0) {
actions.setDragging(false)
document.removeEventListener('mousemove', onMove)
document.removeEventListener('mouseup', onMouseUp)
}
}
document.addEventListener('mousemove', onMove)
document.addEventListener('mouseup', onMouseUp)
}
},
syncWithHedgehog: () => {
const player = values.getHedgehogActor()
if (!values.hedgehogModeEnabled || !player) {
return
}
if (values.minimized !== values.hedgehogMode?.gameUI?.visible) {
actions.toggleMinimized(values.hedgehogMode?.gameUI?.visible)
}
if (values.isDragging) {
// Set the hedgehog position instead
player.setPosition({
x: values.position.x,
y: values.position.y + HEDGEHOG_OFFSET,
})
return
}
const { x, y } = player.rigidBody.position
const newX = x
const newY = y - HEDGEHOG_OFFSET
actions.setDragPosition(newX, newY)
},
createAction: () => {
actions.setVisibleMenu('actions')
},
actionCreatedSuccess: (action) => {
// if embedded, we need to tell the parent window that a new action was created
// it's ok to use we use a wildcard for the origin bc data isn't sensitive
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration
window.parent.postMessage({ type: PostHogAppToolbarEvent.PH_NEW_ACTION_CREATED, payload: action }, '*')
},
maybeSendNavigationMessage: () => {
const currentPath = window.location.pathname
if (currentPath !== values.currentPathname) {
actions.setCurrentPathname(currentPath)
// it's ok to use we use a wildcard for the origin bc data isn't sensitive
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration
window.parent.postMessage(
{ type: PostHogAppToolbarEvent.PH_TOOLBAR_NAVIGATED, payload: { path: currentPath } },
'*'
)
}
},
openHedgehogOptions: () => {
values.hedgehogMode?.gameUI?.show({
screen: 'configuration',
messages: [],
actor: values.getHedgehogActor() ?? undefined,
})
},
togglePiiMasking: () => {
applyPiiMaskingStylesheet(
PII_MASKING_STYLESHEET_ID,
values.piiMaskingEnabled,
values.piiMaskingColor,
values.posthog
)
},
setPiiMaskingColor: ({ color }) => {
applyPiiMaskingStylesheet(PII_MASKING_STYLESHEET_ID, values.piiMaskingEnabled, color, values.posthog)
},
startGracefulExit: () => {
actions.setVisibleMenu('none')
actions.toggleMinimized(true)
},
completeGracefulExit: () => {
actions.logout()
},
})),
afterMount(({ actions, values, cache }) => {
// Detect whether the page's CSP blocks new Function() — if so, hedgehog mode
// (which relies on pixi.js) cannot work and should be disabled.
try {
new Function('return true')()
} catch {
actions.setCspBlocksNewFunction(true)
}
cache.disposables.add(
() => toolbarPosthogJS.onFeatureFlags(() => actions.syncHeatmapGate()),
'heatmapGateFlags'
)
// Add window event listeners using disposables
cache.disposables.add(() => {
const clickListener = (e: MouseEvent): void => {
const target = e.target as HTMLElement
const clickIsInToolbar = target?.id === TOOLBAR_ID || !!target.closest?.('.' + TOOLBAR_CONTAINER_CLASS)
// Don't blur when the debugger is open — it needs to stay pinned
// so users can interact with the page while watching events
if (!clickIsInToolbar && !values.isBlurred && values.visibleMenu !== 'debugger') {
actions.setIsBlurred(true)
}
}
window.addEventListener('mousedown', clickListener)
return () => window.removeEventListener('mousedown', clickListener)
}, 'clickListener')
cache.disposables.add(() => {
const popstateHandler = (): void => actions.maybeSendNavigationMessage()
window.addEventListener('popstate', popstateHandler)
return () => window.removeEventListener('popstate', popstateHandler)
}, 'popstateListener')
cache.disposables.add(
makeNavigateWrapper(actions.maybeSendNavigationMessage, '__ph_toolbar_logic_wrapped__'),
'historyProxy'
)
cache.disposables.add(() => {
const syncHedgehogLoop = setInterval(() => {
if (values.hedgehogModeEnabled && values.getHedgehogActor()) {
actions.syncWithHedgehog()
}
}, 100)
return () => clearInterval(syncHedgehogLoop)
}, 'syncHedgehogLoop')
// Initialize PII masking if already enabled
// Remove stylesheet on unmount
cache.disposables.add(() => {
applyPiiMaskingStylesheet(
PII_MASKING_STYLESHEET_ID,
values.piiMaskingEnabled,
values.piiMaskingColor,
values.posthog
)
return () => applyPiiMaskingStylesheet(PII_MASKING_STYLESHEET_ID, false, values.piiMaskingColor, null)
}, 'piiMasking')
// the toolbar can be run within the posthog parent app
// if it is then it listens to parent messages
const isInIframe = window !== window.parent
if (isInIframe) {
cache.disposables.add(() => {
const iframeEventListener = (e: MessageEvent): void => {
// Only the PostHog app at uiHost should be driving these actions.
const expectedOrigin = toolbarConfigLogic.findMounted()?.values.uiHost
if (!expectedOrigin || e.origin !== expectedOrigin) {
if (e?.data?.type && typeof e.data.type === 'string' && e.data.type.startsWith('ph-')) {
toolbarLogger.warn('iframe', 'Ignoring parent message from unexpected origin', {
got: e.origin,
expected: expectedOrigin,
})
}
return
}
const type: PostHogAppToolbarEvent = e?.data?.type
if (!type || !type.startsWith('ph-')) {
return
}
switch (type) {
case PostHogAppToolbarEvent.PH_APP_INIT: {
const payload = e.data.payload
actions.setIsEmbeddedInApp(true)
actions.toggleClickmapsEnabled(false)
if (payload?.filters != null) {
actions.patchHeatmapFilters(payload.filters)
}
if (payload?.colorPalette != null) {
actions.setHeatmapColorPalette(payload.colorPalette)
}
if (payload?.fixedPositionMode != null) {
actions.setHeatmapFixedPositionMode(payload.fixedPositionMode)
}
if (payload?.commonFilters != null) {
actions.setCommonFilters(payload.commonFilters)
}
// it's ok to use we use a wildcard for the origin bc data isn't sensitive
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration
window.parent.postMessage({ type: PostHogAppToolbarEvent.PH_TOOLBAR_READY }, '*')
return
}
case PostHogAppToolbarEvent.PH_ELEMENT_SELECTOR:
if (e.data.payload.enabled) {
actions.enableInspect()
} else {
actions.disableInspect()
actions.hideButtonActions()
}
return
case PostHogAppToolbarEvent.PH_NEW_ACTION_NAME:
actions.setAutomaticActionCreationEnabled(true, e.data.payload.name)
return
default:
toolbarLogger.warn('iframe', `Received unknown parent window message: ${type}`)
}
}
window.addEventListener('message', iframeEventListener, false)
return () => window.removeEventListener('message', iframeEventListener, false)
}, 'iframeEventListener')
// Post message up to parent in case we are embedded in an app
// Tell the parent window that we are ready
// we check if we're in an iframe before this setup to avoid logging warnings to the console
// it's ok to use we use a wildcard for the origin bc data isn't sensitive
// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configuration
window.parent.postMessage({ type: PostHogAppToolbarEvent.PH_TOOLBAR_INIT }, '*')
}
}),
])