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.

13.6 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import type { PostHog } from 'posthog-js'

import {
    DEFAULT_PII_MASKING_COLOR,
    applyPiiMaskingStylesheet,
    getPiiMaskingWarnings,
} from '~/toolbar/shared/bar/piiMaskingStyles'
import { screenshotUploadLogic } from '~/toolbar/shared/screenshot-upload/screenshotUploadLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'

import type { EventDefinition } from '../../../../types'
import type { PagePosthogBridge } from '../../messaging/pagePosthogBridge'
import type { PageDebugInfo, PageToolbarMoreState } from '../../messaging/pageToolbarBridge'

export type PageMoreCommand =
    | { type: 'reload-debug-info' }
    | { type: 'set-pii-masking'; enabled: boolean }
    | { type: 'set-pii-masking-color'; color: string }
    | { type: 'take-screenshot' }
    | { type: 'set-screenshot-event-name'; name: string }
    | { type: 'select-screenshot-event'; id: string }
    | { type: 'upload-screenshot' }
    | { type: 'close-screenshot' }

// The floating toolbar's PII masking stylesheet has another id, so the two never remove each other's.
const PII_MASKING_STYLESHEET_ID = 'posthog-toolbar-extension-pii-masking'

// The panel shows the screenshot at its own width, so a small copy keeps the message light.
const SCREENSHOT_PREVIEW_WIDTH = 640

type ScreenshotResult = PageToolbarMoreState['screenshot']['result']

async function previewDataUrl(objectUrl: string): Promise<string> {
    const image = new Image()
    image.src = objectUrl
    await image.decode()
    const scale = Math.min(1, SCREENSHOT_PREVIEW_WIDTH / image.naturalWidth)
    const canvas = document.createElement('canvas')
    canvas.width = Math.round(image.naturalWidth * scale)
    canvas.height = Math.round(image.naturalHeight * scale)
    canvas.getContext('2d')?.drawImage(image, 0, 0, canvas.width, canvas.height)
    return canvas.toDataURL('image/jpeg', 0.8)
}

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

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageMoreLogicValues {
    eventDefinitions: EventDefinition[] // screenshotUploadLogic
    eventDefinitionsLoading: boolean // screenshotUploadLogic
    eventName: string // screenshotUploadLogic
    isModalOpen: boolean // screenshotUploadLogic
    isTakingScreenshot: boolean // screenshotUploadLogic
    selectedDefinition: EventDefinition | null // screenshotUploadLogic
    uploadResultLoading: boolean // screenshotUploadLogic
    posthog: PostHog | null // toolbarConfigLogic
    debugInfo: PageDebugInfo | null
    debugInfoLoading: boolean
    pageState: PageToolbarMoreState
    piiMaskingColor: string
    piiMaskingEnabled: boolean
    piiWarnings: string[]
    screenshotPreview: string | null
    screenshotResult: ScreenshotResult
    suggestions: PageToolbarMoreState['screenshot']['suggestions']
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageMoreLogicActions {
    closeModal: () => {
        value: true
    } // screenshotUploadLogic
    openModal: (previewUrl: string) => {
        previewUrl: string
    } // screenshotUploadLogic
    submitUpload: (_: any) => any // screenshotUploadLogic
    submitUploadFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // screenshotUploadLogic
    submitUploadSuccess: (
        uploadResult: {
            success: true
        },
        payload?: any
    ) => {
        payload?: any
        uploadResult: {
            success: true
        }
    } // screenshotUploadLogic
    takeScreenshot: () => {
        value: true
    } // screenshotUploadLogic
    takeScreenshotFailure: (error: string) => {
        error: string
    } // screenshotUploadLogic
    handleCommand: (command: PageMoreCommand) => {
        command: PageMoreCommand
    }
    loadDebugInfo: () => any
    loadDebugInfoFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDebugInfoSuccess: (
        debugInfo: PageDebugInfo | null,
        payload?: any
    ) => {
        debugInfo: PageDebugInfo | null
        payload?: any
    }
    openMore: () => {
        value: true
    }
    setPiiMaskingColor: (color: string) => {
        color: string
    }
    setPiiMaskingEnabled: (enabled: boolean) => {
        enabled: boolean
    }
    setScreenshotPreview: (dataUrl: string | null) => {
        dataUrl: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageMoreLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        piiWarnings: (posthog: PostHog | null, piiMaskingEnabled: boolean) => string[]
        suggestions: (eventDefinitions: EventDefinition[]) => PageToolbarMoreState['screenshot']['suggestions']
        pageState: (
            debugInfo: PageDebugInfo | null,
            debugInfoLoading: boolean,
            piiMaskingEnabled: boolean,
            piiMaskingColor: string,
            piiWarnings: string[],
            isTakingScreenshot: boolean,
            isModalOpen: boolean,
            eventName: string,
            suggestions: {
                id: string
                name: string
            }[],
            eventDefinitionsLoading: boolean,
            selectedDefinition: EventDefinition | null,
            uploadResultLoading: boolean,
            screenshotResult:
                | {
                      status: 'uploaded'
                  }
                | {
                      error: string
                      status: 'failed'
                  }
                | null
        ) => PageToolbarMoreState
    }
}

export type extensionPageMoreLogicType = MakeLogicType<
    extensionPageMoreLogicValues,
    extensionPageMoreLogicActions,
    ExtensionPageMoreLogicProps,
    extensionPageMoreLogicMeta
>

/** Runs in the content script for the toolbar's "More" menu tools. */
export const extensionPageMoreLogic = kea<extensionPageMoreLogicType>([
    path(['toolbar', 'extension', 'extensionPageMoreLogic']),
    props({} as ExtensionPageMoreLogicProps),
    connect(() => ({
        values: [
            toolbarConfigLogic,
            ['posthog'],
            screenshotUploadLogic,
            [
                'isTakingScreenshot',
                'isModalOpen',
                'eventName',
                'eventDefinitions',
                'eventDefinitionsLoading',
                'selectedDefinition',
                'uploadResultLoading',
            ],
        ],
        actions: [
            screenshotUploadLogic,
            [
                'takeScreenshot',
                'takeScreenshotFailure',
                'openModal',
                'closeModal',
                'submitUpload',
                'submitUploadSuccess',
                'submitUploadFailure',
            ],
        ],
    })),
    actions({
        openMore: true,
        handleCommand: (command: PageMoreCommand) => ({ command }),
        setPiiMaskingEnabled: (enabled: boolean) => ({ enabled }),
        setPiiMaskingColor: (color: string) => ({ color }),
        setScreenshotPreview: (dataUrl: string | null) => ({ dataUrl }),
    }),
    loaders(({ props }) => ({
        debugInfo: [
            null as PageDebugInfo | null,
            {
                loadDebugInfo: async () => (await props.posthogBridge?.readDebugInfo()) ?? null,
            },
        ],
    })),
    reducers({
        piiMaskingEnabled: [false, { persist: true }, { setPiiMaskingEnabled: (_, { enabled }) => enabled }],
        piiMaskingColor: [
            DEFAULT_PII_MASKING_COLOR as string,
            { persist: true },
            { setPiiMaskingColor: (_, { color }) => color },
        ],
        // The host sends the preview in its own message, so it stays out of the state the panel gets on every change.
        screenshotPreview: [
            null as string | null,
            { setScreenshotPreview: (_, { dataUrl }) => dataUrl, closeModal: () => null },
        ],
        screenshotResult: [
            null as ScreenshotResult,
            {
                takeScreenshot: () => null,
                submitUpload: () => null,
                submitUploadSuccess: () => ({ status: 'uploaded' }),
                submitUploadFailure: (_, { error }) => ({ status: 'failed', error }),
                takeScreenshotFailure: (_, { error }) => ({ status: 'failed', error }),
            },
        ],
    }),
    selectors({
        piiWarnings: [
            (s) => [s.posthog, s.piiMaskingEnabled],
            (posthog: PostHog | null, piiMaskingEnabled: boolean): string[] =>
                posthog && piiMaskingEnabled ? getPiiMaskingWarnings(posthog) : [],
        ],
        suggestions: [
            (s) => [s.eventDefinitions],
            (eventDefinitions: EventDefinition[]): PageToolbarMoreState['screenshot']['suggestions'] =>
                eventDefinitions.map(({ id, name }) => ({ id, name })),
        ],
        pageState: [
            (s) => [
                s.debugInfo,
                s.debugInfoLoading,
                s.piiMaskingEnabled,
                s.piiMaskingColor,
                s.piiWarnings,
                s.isTakingScreenshot,
                s.isModalOpen,
                s.eventName,
                s.suggestions,
                s.eventDefinitionsLoading,
                s.selectedDefinition,
                s.uploadResultLoading,
                s.screenshotResult,
            ],
            (
                debugInfo: PageDebugInfo | null,
                debugInfoLoading: boolean,
                piiMaskingEnabled: boolean,
                piiMaskingColor: string,
                piiWarnings: string[],
                isTakingScreenshot: boolean,
                isModalOpen: boolean,
                eventName: string,
                suggestions: PageToolbarMoreState['screenshot']['suggestions'],
                eventDefinitionsLoading: boolean,
                selectedDefinition: EventDefinition | null,
                uploadResultLoading: boolean,
                screenshotResult: ScreenshotResult
            ): PageToolbarMoreState => ({
                debugInfo,
                debugInfoLoading,
                piiMaskingEnabled,
                piiMaskingColor,
                piiWarnings,
                screenshot: {
                    taking: isTakingScreenshot,
                    open: isModalOpen,
                    eventName,
                    suggestions,
                    suggestionsLoading: eventDefinitionsLoading,
                    selectedEventId: selectedDefinition?.id ?? null,
                    uploading: uploadResultLoading,
                    result: screenshotResult,
                },
            }),
        ],
    }),
    listeners(({ actions, values }) => {
        const applyPiiMasking = (): void =>
            applyPiiMaskingStylesheet(
                PII_MASKING_STYLESHEET_ID,
                values.piiMaskingEnabled,
                values.piiMaskingColor,
                values.posthog
            )
        return {
            openMore: () => {
                actions.loadDebugInfo()
            },
            setPiiMaskingEnabled: applyPiiMasking,
            setPiiMaskingColor: applyPiiMasking,
            openModal: async ({ previewUrl }) => {
                try {
                    actions.setScreenshotPreview(await previewDataUrl(previewUrl))
                } catch {
                    actions.takeScreenshotFailure("Couldn't read the screenshot")
                }
            },
            handleCommand: ({ command }) => {
                const screenshot = screenshotUploadLogic.actions
                switch (command.type) {
                    case 'reload-debug-info':
                        actions.loadDebugInfo()
                        return
                    case 'set-pii-masking':
                        actions.setPiiMaskingEnabled(command.enabled)
                        return
                    case 'set-pii-masking-color':
                        actions.setPiiMaskingColor(command.color)
                        return
                    case 'take-screenshot':
                        screenshot.takeScreenshot()
                        return
                    case 'set-screenshot-event-name':
                        screenshot.setEventName(command.name)
                        return
                    case 'select-screenshot-event': {
                        const definition = values.eventDefinitions.find(({ id }) => id === command.id)
                        if (definition) {
                            screenshot.selectEvent(definition)
                        }
                        return
                    }
                    case 'upload-screenshot':
                        screenshot.submitUpload(null)
                        return
                    case 'close-screenshot':
                        screenshot.closeModal()
                        return
                }
            },
        }
    }),
    afterMount(({ values, cache }) => {
        cache.disposables.add(() => {
            // A persisted preview comes back on with the page tools, like the floating toolbar's.
            applyPiiMaskingStylesheet(
                PII_MASKING_STYLESHEET_ID,
                values.piiMaskingEnabled,
                values.piiMaskingColor,
                values.posthog
            )
            return () => applyPiiMaskingStylesheet(PII_MASKING_STYLESHEET_ID, false, values.piiMaskingColor, null)
        }, 'piiMasking')
    }),
])