Skip to content

: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.

14.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'

import { actionsLogic } from '~/toolbar/shared/actions/actionsLogic'
import { actionsTabLogic } from '~/toolbar/shared/actions/actionsTabLogic'
import { SelectorMatchCounts, countSelectorMatches } from '~/toolbar/shared/actions/SelectorCountContext'
import { elementsLogic } from '~/toolbar/shared/elements/elementsLogic'
import { heatmapToolbarMenuLogic } from '~/toolbar/shared/elements/heatmapToolbarMenuLogic'
import { experimentsTabLogic } from '~/toolbar/shared/experiments/experimentsTabLogic'
import { currentPageLogic } from '~/toolbar/shared/stats/currentPageLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import type { ElementWithMetadata } from '~/toolbar/shared/types'

import type { FragileSelectorResult } from '../../../shared/utils/selectorQuality'
import type { PagePosthogBridge } from '../../messaging/pagePosthogBridge'
import type {
    InspectedElementInfo,
    PageToolCommands,
    PageToolName,
    PageToolbarCommand,
    PageToolbarInspectState,
    PageToolbarMode,
    PageToolbarState,
    PageToolbarTokens,
} from '../../messaging/pageToolbarBridge'
import { extensionPageActionsLogic } from './extensionPageActionsLogic'
import { EMPTY_PAGE_EVENTS_STATE, extensionPageEventsLogic } from './extensionPageEventsLogic'
import { extensionPageExperimentsLogic } from './extensionPageExperimentsLogic'
import { extensionPageFlagsLogic } from './extensionPageFlagsLogic'
import { extensionPageHeatmapLogic } from './extensionPageHeatmapLogic'
import { extensionPageMoreLogic } from './extensionPageMoreLogic'
import { extensionPageWebVitalsLogic, getPageWebVitalsState } from './extensionPageWebVitalsLogic'

export type PageSessionCommand =
    | { type: 'set-mode'; mode: PageToolbarMode }
    | { type: 'set-tokens'; tokens: PageToolbarTokens }
    | { type: 'set-href'; href: string }

export type PageInspectCommand = { type: 'clear-selected-element' }

export type PageSelectorsCommand = { type: 'count-selectors'; selectors: string[] }

export interface ExtensionPageToolbarLogicProps {
    /** Null when the page has no `window.posthog`. */
    posthogBridge: PagePosthogBridge | null
}

type PanelMenuMode = Extract<PageToolbarMode, 'flags' | 'events' | 'web-vitals' | 'more'>

const PANEL_MENU_MODES: PanelMenuMode[] = ['flags', 'events', 'web-vitals', 'more']

// The panel asks about the selectors its open form shows, so a short list covers it.
const MAX_COUNTED_SELECTORS = 20

// Recounts the selectors once the page stops changing for this long.
const SELECTOR_RECOUNT_DEBOUNCE_MS = 300

function countMatches(selectors: string[]): Record<string, SelectorMatchCounts | null> {
    return Object.fromEntries(selectors.map((selector) => [selector, countSelectorMatches(selector)]))
}

function inspectedElementInfo(meta: ElementWithMetadata | null): InspectedElementInfo | null {
    if (!meta) {
        return null
    }
    return {
        tagName: meta.element.tagName.toLowerCase(),
        actionStep: meta.actionStep ?? null,
        stats: meta.position
            ? {
                  count: meta.count ?? 0,
                  clickCount: meta.clickCount ?? 0,
                  rageclickCount: meta.rageclickCount ?? 0,
                  deadclickCount: meta.deadclickCount ?? 0,
                  rank: meta.position,
              }
            : null,
        actions: (meta.actions ?? []).map(({ action }) => ({ id: action.id, name: action.name ?? null })),
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageToolbarLogicValues {
    buttonActionsVisible: boolean // actionsTabLogic
    activeMeta:
        | (ElementWithMetadata & {
              selectorQuality: FragileSelectorResult | null
          })
        | null // elementsLogic
    activeMetaIsSelected: boolean // elementsLogic
    inspectEnabled: boolean // elementsLogic
    selectedElement: HTMLElement | null // elementsLogic
    buttonExperimentsVisible: boolean // experimentsTabLogic
    heatmapEnabled: boolean // heatmapToolbarMenuLogic
    countedSelectors: string[]
    inspectState: PageToolbarInspectState
    mode: PageToolbarMode
    openMenu: PanelMenuMode | null
    selectorCounts: Record<string, SelectorMatchCounts | null>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageToolbarLogicActions {
    handleCommand: (message: PageToolbarCommand) => {
        message: PageToolbarCommand
    }
    recountSelectors: () => {
        value: true
    }
    setCountedSelectors: (selectors: string[]) => {
        selectors: string[]
    }
    setMode: (mode: PageToolbarMode) => {
        mode: PageToolbarMode
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageToolbarLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        mode: (
            buttonActionsVisible: boolean,
            buttonExperimentsVisible: boolean,
            openMenu: PanelMenuMode | null,
            inspectEnabled: boolean,
            heatmapEnabled: boolean
        ) => PageToolbarMode
        inspectState: (
            activeMeta:
                | (ElementWithMetadata & {
                      selectorQuality: FragileSelectorResult | null
                  })
                | null,
            activeMetaIsSelected: boolean
        ) => PageToolbarInspectState
    }
}

export type extensionPageToolbarLogicType = MakeLogicType<
    extensionPageToolbarLogicValues,
    extensionPageToolbarLogicActions,
    ExtensionPageToolbarLogicProps,
    extensionPageToolbarLogicMeta
>

/** Runs in the content script. Mount it after `toolbarConfigLogic`, because the connected logics read its tokens. */
export const extensionPageToolbarLogic = kea<extensionPageToolbarLogicType>([
    path(['toolbar', 'extension', 'extensionPageToolbarLogic']),
    props({} as ExtensionPageToolbarLogicProps),
    connect(() => ({
        values: [
            elementsLogic,
            ['inspectEnabled', 'activeMeta', 'activeMetaIsSelected', 'selectedElement'],
            heatmapToolbarMenuLogic,
            ['heatmapEnabled'],
            actionsTabLogic,
            ['buttonActionsVisible'],
            experimentsTabLogic,
            ['buttonExperimentsVisible'],
        ],
        logic: [
            extensionPageHeatmapLogic,
            extensionPageActionsLogic,
            extensionPageFlagsLogic,
            extensionPageWebVitalsLogic,
            extensionPageExperimentsLogic,
        ],
    })),
    actions({
        handleCommand: (message: PageToolbarCommand) => ({ message }),
        setMode: (mode: PageToolbarMode) => ({ mode }),
        setCountedSelectors: (selectors: string[]) => ({ selectors }),
        recountSelectors: true,
    }),
    reducers({
        // The panel-only menus. The other modes live in the toolbar logics that draw on the page.
        openMenu: [
            null as PanelMenuMode | null,
            {
                setMode: (_, { mode }) =>
                    PANEL_MENU_MODES.includes(mode as PanelMenuMode) ? (mode as PanelMenuMode) : null,
            },
        ],
        countedSelectors: [[] as string[], { setCountedSelectors: (_, { selectors }) => selectors }],
        selectorCounts: [
            {} as Record<string, SelectorMatchCounts | null>,
            {
                setCountedSelectors: (_, { selectors }) => countMatches(selectors),
                recountSelectors: (counts) => countMatches(Object.keys(counts)),
            },
        ],
    }),
    selectors({
        mode: [
            (s) => [s.buttonActionsVisible, s.buttonExperimentsVisible, s.openMenu, s.inspectEnabled, s.heatmapEnabled],
            (
                buttonActionsVisible: boolean,
                buttonExperimentsVisible: boolean,
                openMenu: PanelMenuMode | null,
                inspectEnabled: boolean,
                heatmapEnabled: boolean
            ): PageToolbarMode =>
                // Actions and experiments come first, because picking an element for them turns inspect on too.
                buttonActionsVisible
                    ? 'actions'
                    : buttonExperimentsVisible
                      ? 'experiments'
                      : openMenu
                        ? openMenu
                        : inspectEnabled
                          ? 'inspect'
                          : heatmapEnabled
                            ? 'heatmap'
                            : 'none',
        ],
        inspectState: [
            (s) => [s.activeMeta, s.activeMetaIsSelected],
            (activeMeta: ElementWithMetadata | null, activeMetaIsSelected: boolean): PageToolbarInspectState => ({
                element: inspectedElementInfo(activeMeta),
                isSelected: activeMetaIsSelected,
            }),
        ],
    }),
    listeners(({ actions, values, props, cache }) => ({
        setMode: ({ mode }) => {
            // The floating toolbar opens one menu at a time, and each menu turns the others' page modes off.
            elementsLogic.actions.disableInspect()
            heatmapToolbarMenuLogic.actions.disableHeatmap()
            actionsTabLogic.actions.inspectForElementWithIndex(null)
            actionsTabLogic.actions.hideButtonActions()
            if (values.buttonExperimentsVisible) {
                extensionPageExperimentsLogic.actions.closeExperiments()
            }
            extensionPageEventsLogic.findMounted()?.actions.setOpen(mode === 'events')
            // Each tool loads its data the first time it opens, and keeps it while the page tools run.
            const firstOpen = !cache.openedModes.has(mode)
            cache.openedModes.add(mode)
            if (mode === 'inspect') {
                elementsLogic.actions.enableInspect()
            } else if (mode === 'heatmap') {
                heatmapToolbarMenuLogic.actions.enableHeatmap()
            } else if (mode === 'actions') {
                actionsTabLogic.actions.showButtonActions()
                if (firstOpen) {
                    actionsLogic.actions.getActions()
                }
            } else if (mode === 'experiments') {
                // experimentsTabLogic loads the list when it mounts with the page tools.
                experimentsTabLogic.actions.showButtonExperiments()
            } else if (mode === 'flags') {
                if (firstOpen) {
                    extensionPageFlagsLogic.actions.openFlags()
                }
            } else if (mode === 'events') {
                // The debugger stays mounted once it opens, and keeps collecting events like the floating toolbar's.
                if (!extensionPageEventsLogic.findMounted()) {
                    extensionPageEventsLogic({ posthogBridge: props.posthogBridge }).mount()
                }
            } else if (mode === 'web-vitals') {
                extensionPageWebVitalsLogic.actions.openWebVitals()
            } else if (mode === 'more') {
                extensionPageMoreLogic.findMounted()?.actions.openMore()
            }
        },
        handleCommand: ({ message }) => {
            const handlers: { [Tool in PageToolName]: (command: PageToolCommands[Tool]) => void } = {
                session: (command) => {
                    if (command.type === 'set-mode') {
                        actions.setMode(command.mode)
                    } else if (command.type === 'set-href') {
                        currentPageLogic.actions.setHref(command.href)
                    } else {
                        const { accessToken, refreshToken, clientId } = command.tokens
                        toolbarConfigLogic.actions.setOAuthTokens(accessToken, refreshToken, clientId)
                    }
                },
                inspect: () => elementsLogic.actions.setSelectedElement(null),
                selectors: (command) => actions.setCountedSelectors(command.selectors.slice(-MAX_COUNTED_SELECTORS)),
                heatmap: (command) => extensionPageHeatmapLogic.actions.handleCommand(command),
                actions: (command) => {
                    if (command.type === 'new-action') {
                        // Switching modes clears the selection, so read the element first.
                        const element = command.fromSelectedElement ? values.selectedElement : null
                        actions.setMode('actions')
                        actionsTabLogic.actions.newAction(element ?? undefined)
                        return
                    }
                    extensionPageActionsLogic.actions.handleCommand(command)
                },
                flags: (command) => extensionPageFlagsLogic.actions.handleCommand(command),
                events: (command) => extensionPageEventsLogic.findMounted()?.actions.handleCommand(command),
                'web-vitals': () => extensionPageWebVitalsLogic.actions.reloadWebVitals(),
                more: (command) => extensionPageMoreLogic.findMounted()?.actions.handleCommand(command),
                experiments: (command) => extensionPageExperimentsLogic.actions.handleCommand(command),
            }
            ;(handlers[message.tool] as (command: PageToolbarCommand['command']) => void)(message.command)
        },
    })),
    afterMount(({ actions, values, cache }) => {
        cache.openedModes = new Set<PageToolbarMode>()
        cache.disposables.add(() => {
            let timeout: ReturnType<typeof setTimeout> | undefined
            const observer = new MutationObserver(() => {
                if (values.countedSelectors.length === 0) {
                    return
                }
                clearTimeout(timeout)
                timeout = setTimeout(actions.recountSelectors, SELECTOR_RECOUNT_DEBOUNCE_MS)
            })
            observer.observe(document.body, { childList: true, subtree: true, attributes: true })
            return () => {
                clearTimeout(timeout)
                observer.disconnect()
            }
        }, 'selectorRecount')
    }),
])

/** Every slice comes from a memoized selector, so the host posts only the slices whose reference changed. */
export function getPageToolbarState(): PageToolbarState {
    const { mode, inspectState, selectorCounts } = extensionPageToolbarLogic.values
    return {
        mode,
        inspect: inspectState,
        selectorCounts,
        heatmap: extensionPageHeatmapLogic.values.pageState,
        actions: extensionPageActionsLogic.values.pageState,
        flags: extensionPageFlagsLogic.values.pageState,
        events: extensionPageEventsLogic.findMounted()?.values.pageState ?? EMPTY_PAGE_EVENTS_STATE,
        webVitals: getPageWebVitalsState(extensionPageWebVitalsLogic.values.posthog),
        experiments: extensionPageExperimentsLogic.values.pageState,
        more: extensionPageMoreLogic.values.pageState,
    }
}