: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 './Toolbar.scss'
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { PostHog } from 'posthog-js'
import { Suspense, lazy, useEffect, useRef, useState } from 'react'
import {
IconApp,
IconBolt,
IconCamera,
IconCheck,
IconCursorClick,
IconDay,
IconEye,
IconFlask,
IconHide,
IconLeave,
IconLive,
IconLock,
IconNight,
IconPieChart,
IconQuestion,
IconSearch,
IconSpotlight,
IconStethoscope,
IconToggle,
IconWarning,
IconX,
} from '@posthog/icons'
import { LemonBadge, LemonButton, Spinner } from '@posthog/lemon-ui'
import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { IconFlare, IconMenu } from 'lib/lemon-ui/icons'
import { LemonMenu, LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { Link } from 'lib/lemon-ui/Link'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { retryImport } from 'lib/utils/retryImport'
import { AnimatedLogomark } from '~/toolbar/floating/components/bar/AnimatedLogomark'
import { AuthConfirmModal } from '~/toolbar/floating/components/bar/AuthConfirmModal'
import { ToolbarLockedFeature } from '~/toolbar/floating/components/bar/ToolbarLockedFeature'
import { UiHostConfigModal } from '~/toolbar/floating/components/bar/UiHostConfigModal'
import { ScreenshotUploadModal } from '~/toolbar/floating/components/screenshot-upload/ScreenshotUploadModal'
import { PII_MASKING_PRESET_COLORS } from '~/toolbar/shared/bar/piiMaskingStyles'
import { toolbarLogic } from '~/toolbar/shared/bar/toolbarLogic'
import { readPosthogDebugInfo } from '~/toolbar/shared/debug/posthogDebugInfo'
import { fieldNotesLogic } from '~/toolbar/shared/field-notes/fieldNotesLogic'
import { productToursLogic } from '~/toolbar/shared/product-tours/productToursLogic'
import { screenshotUploadLogic } from '~/toolbar/shared/screenshot-upload/screenshotUploadLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import {
ToolbarFeatureGateStatus,
toolbarEntitlementsLogic,
useToolbarFeatureGateStatus,
} from '~/toolbar/shared/toolbarEntitlementsLogic'
import { useToolbarFeatureFlag } from '~/toolbar/shared/toolbarPosthogJS'
import { AvailableFeature } from '~/types'
import { ToolbarButton } from './ToolbarButton'
import { ToolbarMenu } from './ToolbarMenu'
// Each feature menu is a lazy split point: its component graph (and per-tab logics only it
// mounts, like the event debugger's 200KB+ taxonomy) is fetched when the tab first opens, not
// on toolbar boot. Styles are unaffected — the shadow root loads the entry stylesheet, and
// bin/check-toolbar-size.mjs fails the build if a lazy chunk holds CSS the entry doesn't.
const ActionsToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/actions/ActionsToolbarMenu')).then((m) => ({
default: m.ActionsToolbarMenu,
}))
)
const EventDebugMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/debug/EventDebugMenu')).then((m) => ({
default: m.EventDebugMenu,
}))
)
const ExperimentsToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/experiments/ExperimentsToolbarMenu')).then((m) => ({
default: m.ExperimentsToolbarMenu,
}))
)
const FieldNotesOverlay = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/field-notes/FieldNotesOverlay')).then((m) => ({
default: m.FieldNotesOverlay,
}))
)
const FieldNotesToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/field-notes/FieldNotesToolbarMenu')).then((m) => ({
default: m.FieldNotesToolbarMenu,
}))
)
const FlagsToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/flags/FlagsToolbarMenu')).then((m) => ({
default: m.FlagsToolbarMenu,
}))
)
const ProductToursSidebar = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/product-tours/ProductToursSidebar')).then((m) => ({
default: m.ProductToursSidebar,
}))
)
const ProductToursToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/product-tours/ProductToursToolbarMenu')).then((m) => ({
default: m.ProductToursToolbarMenu,
}))
)
const HeatmapToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/stats/HeatmapToolbarMenu')).then((m) => ({
default: m.HeatmapToolbarMenu,
}))
)
const WebVitalsToolbarMenu = lazy(() =>
retryImport(() => import('~/toolbar/floating/components/web-vitals/WebVitalsToolbarMenu')).then((m) => ({
default: m.WebVitalsToolbarMenu,
}))
)
const HELP_URL = 'https://posthog.com/docs/toolbar?utm_medium=in-product&utm_campaign=toolbar-help-button'
const HEATMAP_GATE_TITLES: Record<ToolbarFeatureGateStatus, string | undefined> = {
available: undefined,
checking: 'Heatmaps (checking plan access…)',
unknown: "Heatmaps (couldn't check plan access, click to try again)",
locked: 'Heatmaps (Pay-as-you-go subscription required)',
}
function LockableMenuIcon({ icon, locked }: { icon: JSX.Element; locked: boolean }): JSX.Element {
if (!locked) {
return icon
}
return (
<span
className="relative flex"
// eslint-disable-next-line react/forbid-dom-props
style={{ fontSize: '1.5rem' }}
>
{icon}
<IconLock className="absolute -top-1 -right-1 text-xs text-secondary" />
</span>
)
}
function EnabledStatusItem({ label, value }: { label: string; value: boolean }): JSX.Element {
return (
<div className="flex justify-between items-center w-full">
<div>{label}: </div>
<div>{value ? <IconCheck /> : <IconX />}</div>
</div>
)
}
function postHogDebugInfoMenuItem(
posthog: PostHog | null,
loadingSurveys: boolean,
surveysCount: number
): LemonMenuItem {
const info = readPosthogDebugInfo(posthog)
return {
icon: <IconStethoscope />,
label: 'Debug info',
items: [
{
label: (
<div className="flex justify-between items-center w-full">
<div>version: </div>
<div>{info.version || 'posthog not available'}</div>
</div>
),
},
{
label: (
<div className="flex justify-between items-center w-full">
<div>api host: </div>
<div>{info.apiHost}</div>
</div>
),
},
{
label: (
<div className="flex justify-between items-center w-full">
<div>ui host: </div>
<div>{info.uiHost || 'not set'}</div>
</div>
),
},
{ label: <EnabledStatusItem label="autocapture" value={info.autocapture} /> },
{ label: <EnabledStatusItem label="rageclicks" value={info.rageclicks} /> },
{ label: <EnabledStatusItem label="dead clicks" value={info.deadClicks} /> },
{ label: <EnabledStatusItem label="heatmaps" value={info.heatmaps} /> },
{
label: (
<div className="flex justify-between items-center w-full">
<div>surveys: </div>
<div>
{loadingSurveys ? <Spinner /> : <LemonBadge.Number showZero={true} count={surveysCount} />}
</div>
</div>
),
},
{ label: <EnabledStatusItem label="session recording" value={info.sessionRecordingStarted} /> },
{
label: (
<div className="flex justify-between items-center w-full">
<div>session recording status: </div>
<div>{info.sessionRecordingStatus || 'unknown'}</div>
</div>
),
},
{
label: (
<div className="flex items-center w-full">
<Link to={info.sessionReplayUrl ?? undefined} target="_blank">
View current session recording
</Link>
</div>
),
},
],
}
}
function piiMaskingMenuItem(
piiMaskingEnabled: boolean,
piiMaskingColor: string,
togglePiiMasking: () => void,
setPiiMaskingColor: (color: string) => void,
piiWarning: string[] | null
): LemonMenuItem[] {
return [
{
icon: piiMaskingEnabled ? <IconEye /> : <IconHide />,
label: piiMaskingEnabled ? 'Show PII' : 'Hide PII',
sideIcon: piiWarning && piiWarning.length > 0 ? <IconWarning className="text-warning" /> : undefined,
tooltip: piiWarning && piiWarning.length > 0 ? piiWarning.join('\n') : undefined,
onClick: (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
togglePiiMasking()
},
custom: true,
},
piiMaskingEnabled
? {
icon: (
<div
className="w-4 h-4 rounded border"
// eslint-disable-next-line react/forbid-dom-props
style={{ backgroundColor: piiMaskingColor }}
/>
),
label: 'PII masking color',
placement: 'right',
disabled: !piiMaskingEnabled,
items: PII_MASKING_PRESET_COLORS.map((preset) => ({
icon: (
<div
className="w-4 h-4 rounded border"
// eslint-disable-next-line react/forbid-dom-props
style={{ backgroundColor: preset.value }}
/>
),
label: preset.label,
onClick: () => {
setPiiMaskingColor(preset.value)
},
active: piiMaskingColor === preset.value,
custom: true,
})),
}
: undefined,
].filter(Boolean) as LemonMenuItem[]
}
function MoreMenu(): JSX.Element {
const {
hedgehogModeEnabled,
hedgehogModeAvailable,
theme,
posthog,
piiMaskingEnabled,
piiMaskingColor,
piiWarning,
} = useValues(toolbarLogic)
const {
setHedgehogModeEnabled,
toggleTheme,
togglePiiMasking,
setPiiMaskingColor,
startGracefulExit,
openHedgehogOptions,
} = useActions(toolbarLogic)
const { isAuthenticated } = useValues(toolbarConfigLogic)
const { logout } = useActions(toolbarConfigLogic)
const { isTakingScreenshot } = useValues(screenshotUploadLogic)
const { takeScreenshot } = useActions(screenshotUploadLogic)
const [loadingSurveys, setLoadingSurveys] = useState(true)
const [surveysCount, setSurveysCount] = useState(0)
useEffect(() => {
posthog?.surveys?.getSurveys((surveys: any[]) => {
setSurveysCount(surveys.length)
setLoadingSurveys(false)
}, false)
}, [posthog])
// KLUDGE: if there is no theme, assume light mode, which shouldn't be, but seems to be, necessary
const currentlyLightMode = !theme || theme === 'light'
return (
<>
<ScreenshotUploadModal />
<LemonMenu
placement="top-end"
fallbackPlacements={['bottom-end']}
items={
[
{
icon: <>🦔</>,
label: hedgehogModeEnabled ? 'Disable hedgehog mode' : 'Hedgehog mode',
disabledReason: !hedgehogModeAvailable
? "Hedgehog mode is disabled. Hedgehog mode uses `new Function` directives to render WebGL, and that requires 'unsafe-eval' in your Content Security Policy's script-src directive"
: undefined,
onClick: () => {
setHedgehogModeEnabled(!hedgehogModeEnabled)
},
},
hedgehogModeEnabled && hedgehogModeAvailable
? {
icon: <IconFlare />,
label: 'Hedgehog options',
onClick: () => {
openHedgehogOptions()
},
}
: undefined,
{
icon: currentlyLightMode ? <IconNight /> : <IconDay />,
label: `Switch to ${currentlyLightMode ? 'dark' : 'light'} mode`,
onClick: () => toggleTheme(),
},
{
icon: <IconCamera />,
label: 'Screenshot for event',
onClick: takeScreenshot,
disabled: isTakingScreenshot,
},
...piiMaskingMenuItem(
piiMaskingEnabled,
piiMaskingColor,
togglePiiMasking,
setPiiMaskingColor,
piiWarning
),
postHogDebugInfoMenuItem(posthog, loadingSurveys, surveysCount),
{
icon: <IconQuestion />,
label: 'Help',
onClick: () => {
window.open(HELP_URL, '_blank')?.focus()
},
},
isAuthenticated ? { icon: <IconLeave />, label: 'Sign out', onClick: logout } : undefined,
{ icon: <IconX />, label: 'Close toolbar', onClick: startGracefulExit },
].filter(Boolean) as LemonMenuItems
}
maxContentWidth={true}
>
<ToolbarButton>{isTakingScreenshot ? <Spinner /> : <IconMenu />}</ToolbarButton>
</LemonMenu>
</>
)
}
export function ToolbarInfoMenu(): JSX.Element | null {
const ref = useRef<HTMLDivElement | null>(null)
const { visibleMenu, isDragging, menuProperties, minimized, isBlurred } = useValues(toolbarLogic)
const { setMenu } = useActions(toolbarLogic)
const { loadEntitlements } = useActions(toolbarEntitlementsLogic)
const { isAuthenticated } = useValues(toolbarConfigLogic)
const productToursFlag = useToolbarFeatureFlag('product-tours-2025')
const showProductTours = inStorybook() || inStorybookTestRunner() || productToursFlag
const fieldNotesFlag = useToolbarFeatureFlag('field-notes')
const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlag
const heatmapGate = useToolbarFeatureGateStatus(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')
const content = minimized ? null : visibleMenu === 'flags' ? (
<FlagsToolbarMenu />
) : visibleMenu === 'heatmap' ? (
heatmapGate === 'checking' ? (
<ToolbarMenu>
<ToolbarMenu.Body>
<div className="flex items-center justify-center gap-2 py-4">
<Spinner />
<span>Checking plan access…</span>
</div>
</ToolbarMenu.Body>
</ToolbarMenu>
) : heatmapGate === 'unknown' ? (
<ToolbarMenu>
<ToolbarMenu.Body>
<p className="m-0">Couldn't check your plan access. Try again to use heatmaps.</p>
</ToolbarMenu.Body>
<ToolbarMenu.Footer>
<LemonButton
type="primary"
fullWidth
center
onClick={loadEntitlements}
data-attr="toolbar-entitlements-retry"
>
Try again
</LemonButton>
</ToolbarMenu.Footer>
</ToolbarMenu>
) : heatmapGate === 'locked' ? (
<ToolbarLockedFeature featureName="Heatmaps" />
) : (
<HeatmapToolbarMenu />
)
) : visibleMenu === 'actions' ? (
<ActionsToolbarMenu />
) : visibleMenu === 'debugger' ? (
<EventDebugMenu />
) : visibleMenu === 'web-vitals' ? (
<WebVitalsToolbarMenu />
) : visibleMenu === 'experiments' ? (
<ExperimentsToolbarMenu />
) : visibleMenu === 'product-tours' && showProductTours ? (
<ProductToursToolbarMenu />
) : visibleMenu === 'field-notes' && showFieldNotes ? (
<FieldNotesToolbarMenu />
) : null
useEffect(() => {
setMenu(ref.current)
return () => setMenu(null)
}, [ref.current]) // oxlint-disable-line react-hooks/exhaustive-deps
if (!isAuthenticated) {
return null
}
return (
<div
className={clsx(
'ToolbarMenu',
!!content && 'ToolbarMenu--visible',
isDragging && 'ToolbarMenu--dragging',
isBlurred && 'ToolbarMenu--blurred',
menuProperties.isBelow && 'ToolbarMenu--below'
)}
// eslint-disable-next-line react/forbid-dom-props
style={{
transform: menuProperties.transform,
}}
>
<div
ref={ref}
className="ToolbarMenu__content"
// eslint-disable-next-line react/forbid-dom-props
style={{
maxHeight: menuProperties.maxHeight,
}}
>
<Suspense
fallback={
<div className="flex items-center justify-center p-4">
<Spinner />
</div>
}
>
{content}
</Suspense>
</div>
</div>
)
}
export function Toolbar(): JSX.Element | null {
const ref = useRef<HTMLDivElement | null>(null)
const { minimized, position, isDragging, hedgehogMode, isEmbeddedInApp, isExiting, isLoading } =
useValues(toolbarLogic)
const { setVisibleMenu, toggleMinimized, onMouseOrTouchDown, setElement, setIsBlurred, completeGracefulExit } =
useActions(toolbarLogic)
const { isAuthenticated, userIntent, authStatus, uiHostConfigModalVisible, authConfirmModalVisible } =
useValues(toolbarConfigLogic)
const { authenticate, openUiHostConfigModal, closeUiHostConfigModal, closeAuthConfirmModal } =
useActions(toolbarConfigLogic)
const { selectedTourId, isPreviewing } = useValues(productToursLogic)
const productToursFlag = useToolbarFeatureFlag('product-tours-2025')
const showProductTours = inStorybook() || inStorybookTestRunner() || productToursFlag
const fieldNotesFlag = useToolbarFeatureFlag('field-notes')
const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlag
const { hasOpenedFieldNotes } = useValues(fieldNotesLogic)
const heatmapGate = useToolbarFeatureGateStatus(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')
useEffect(() => {
setElement(ref.current)
return () => setElement(null)
}, [ref.current]) // oxlint-disable-line react-hooks/exhaustive-deps
useKeyboardHotkeys(
{
escape: { action: () => setVisibleMenu('none'), willHandleEvent: true },
},
[]
)
useEffect(() => {
if (userIntent === 'add-action' || userIntent === 'edit-action') {
setVisibleMenu('actions')
}
if (userIntent === 'add-experiment' || userIntent === 'edit-experiment') {
setVisibleMenu('experiments')
}
if (userIntent === 'heatmaps') {
setVisibleMenu('heatmap')
}
if (userIntent === 'add-product-tour' || userIntent === 'edit-product-tour') {
setVisibleMenu('product-tours')
}
}, [userIntent]) // oxlint-disable-line react-hooks/exhaustive-deps
if (isEmbeddedInApp) {
return null
}
const showToursSidebar = selectedTourId !== null && !isPreviewing
return (
<>
<Suspense fallback={null}>
{showToursSidebar && <ProductToursSidebar />}
{showFieldNotes && <FieldNotesOverlay />}
</Suspense>
<ToolbarInfoMenu />
<div
ref={ref}
className={clsx('Toolbar', {
'Toolbar--minimized': minimized,
'Toolbar--hedgehog-mode': hedgehogMode,
'Toolbar--dragging': isDragging,
'Toolbar--extra-buttons-1': 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) === 1,
'Toolbar--extra-buttons-2': 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) === 2,
'Toolbar--extra-buttons-3': 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) === 3,
})}
onMouseDown={(e) => onMouseOrTouchDown(e.nativeEvent)}
onTouchStart={(e) => onMouseOrTouchDown(e.nativeEvent)}
onMouseOver={() => setIsBlurred(false)}
// eslint-disable-next-line react/forbid-dom-props
style={
{
'--toolbar-button-x': `${position.x}px`,
'--toolbar-button-y': `${position.y}px`,
} as any
}
>
<ToolbarButton
onClick={isAuthenticated ? toggleMinimized : authenticate}
title={isAuthenticated ? 'Minimize' : 'Authenticate the PostHog Toolbar'}
titleMinimized={isAuthenticated ? 'Expand the toolbar' : 'Authenticate the PostHog Toolbar'}
>
<AnimatedLogomark
animate={isLoading || authStatus === 'checking' || authStatus === 'authenticating'}
animateOnce={isExiting ? completeGracefulExit : undefined}
className="Toolbar__logomark"
/>
</ToolbarButton>
{isAuthenticated ? (
<>
<ToolbarButton menuId="inspect">
<IconSearch />
</ToolbarButton>
{/* When the field notes flag is on, field notes takes the heatmap slot + cursor icon */}
{showFieldNotes ? (
<ToolbarButton menuId="field-notes" title="Field notes">
{/* Inline font-size because the wrapper breaks the `button > svg` size rule */}
{/* eslint-disable-next-line react/forbid-dom-props */}
<span className="relative flex" style={{ fontSize: '1.5rem' }}>
<IconCursorClick />
{!hasOpenedFieldNotes && (
<span
className="absolute -top-1 -right-1 w-2 h-2 rounded-full"
// eslint-disable-next-line react/forbid-dom-props
style={{ backgroundColor: 'var(--primary-3000)' }}
/>
)}
</span>
</ToolbarButton>
) : (
<ToolbarButton menuId="heatmap" title={HEATMAP_GATE_TITLES[heatmapGate]}>
<LockableMenuIcon icon={<IconCursorClick />} locked={heatmapGate === 'locked'} />
</ToolbarButton>
)}
<ToolbarButton menuId="actions">
<IconBolt />
</ToolbarButton>
<ToolbarButton menuId="flags" title="Feature flags">
<IconToggle />
</ToolbarButton>
<ToolbarButton menuId="debugger" title="Event debugger">
<IconLive />
</ToolbarButton>
<ToolbarButton menuId="web-vitals" title="Web vitals">
<IconPieChart />
</ToolbarButton>
<ToolbarButton menuId="experiments" title="Experiments">
<IconFlask />
</ToolbarButton>
{showProductTours && (
<ToolbarButton menuId="product-tours" title="Product tours">
<IconSpotlight />
</ToolbarButton>
)}
{/* Heatmaps moves here and takes the app icon when field notes is enabled */}
{showFieldNotes && (
<ToolbarButton menuId="heatmap" title={HEATMAP_GATE_TITLES[heatmapGate] ?? 'Heatmaps'}>
<LockableMenuIcon icon={<IconApp />} locked={heatmapGate === 'locked'} />
</ToolbarButton>
)}
</>
) : authStatus === 'checking' || authStatus === 'authenticating' ? (
<ToolbarButton flex>
<span className="flex items-center gap-1">
<Spinner /> {authStatus === 'authenticating' ? 'Authenticating…' : 'Checking…'}
</span>
</ToolbarButton>
) : authStatus === 'error' ? (
<ToolbarButton
flex
onClick={openUiHostConfigModal}
title="PostHog app unreachable — click for help"
>
<span className="flex items-center gap-1">
Authenticate <IconWarning className="text-warning" />
</span>
</ToolbarButton>
) : (
<ToolbarButton flex onClick={authenticate}>
Authenticate
</ToolbarButton>
)}
<UiHostConfigModal visible={uiHostConfigModalVisible} onClose={closeUiHostConfigModal} />
<AuthConfirmModal visible={authConfirmModalVisible} onClose={closeAuthConfirmModal} />
<MoreMenu />
</div>
</>
)
}