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.

8.0 KB
Raw Blame
import { MakeLogicType, actions, kea, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import { lemonToast } from 'lib/lemon-ui/LemonToast'

import { toolbarApi } from '~/toolbar/shared/toolbarApi'
import { toolbarPosthogJS } from '~/toolbar/shared/toolbarPosthogJS'
import { ToolbarRequestError } from '~/toolbar/shared/toolbarRequestError'
import { safeFetch } from '~/toolbar/shared/utils'
import { captureElementScreenshot, uploadScreenshot } from '~/toolbar/shared/utils/screenshot'
import { EventDefinition } from '~/types'

export interface ScreenshotUploadLogicProps {
    onSuccess?: () => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface screenshotUploadLogicValues {
    eventDefinitions: EventDefinition[]
    eventDefinitionsLoading: boolean
    eventName: string
    isModalOpen: boolean
    isTakingScreenshot: boolean
    previewUrl: string | null
    selectedDefinition: EventDefinition | null
    showSuggestions: boolean
    uploadResult: {
        success: boolean
    } | null
    uploadResultLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface screenshotUploadLogicActions {
    closeModal: () => {
        value: true
    }
    openModal: (previewUrl: string) => {
        previewUrl: string
    }
    searchEvents: ({ query }: { query: string }) => {
        query: string
    }
    searchEventsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    searchEventsSuccess: (
        eventDefinitions: EventDefinition[],
        payload?: {
            query: string
        }
    ) => {
        eventDefinitions: EventDefinition[]
        payload?: {
            query: string
        }
    }
    selectEvent: (definition: EventDefinition) => {
        definition: EventDefinition
    }
    setEventName: (name: string) => {
        name: string
    }
    setShowSuggestions: (show: boolean) => {
        show: boolean
    }
    submitUpload: (_: any) => any
    submitUploadFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    submitUploadSuccess: (
        uploadResult: {
            success: true
        },
        payload?: any
    ) => {
        uploadResult: {
            success: true
        }
        payload?: any
    }
    takeScreenshot: () => {
        value: true
    }
    takeScreenshotFailure: (error: string) => {
        error: string
    }
}

export type screenshotUploadLogicType = MakeLogicType<
    screenshotUploadLogicValues,
    screenshotUploadLogicActions,
    ScreenshotUploadLogicProps
>

export const screenshotUploadLogic = kea<screenshotUploadLogicType>([
    path(['toolbar', 'screenshot-upload', 'screenshotUploadLogic']),
    props({} as ScreenshotUploadLogicProps),

    actions({
        setEventName: (name: string) => ({ name }),
        selectEvent: (definition: EventDefinition) => ({ definition }),
        setShowSuggestions: (show: boolean) => ({ show }),
        takeScreenshot: true,
        takeScreenshotFailure: (error: string) => ({ error }),
        openModal: (previewUrl: string) => ({ previewUrl }),
        closeModal: true,
    }),

    reducers({
        isTakingScreenshot: [
            false,
            { takeScreenshot: () => true, openModal: () => false, takeScreenshotFailure: () => false },
        ],
        isModalOpen: [false, { openModal: () => true, closeModal: () => false }],
        previewUrl: [null as string | null, { openModal: (_, { previewUrl }) => previewUrl, closeModal: () => null }],
        eventName: [
            '',
            {
                setEventName: (_, { name }) => name,
                selectEvent: (_, { definition }) => definition.name,
                closeModal: () => '',
            },
        ],
        selectedDefinition: [
            null as EventDefinition | null,
            {
                selectEvent: (_, { definition }) => definition,
                setEventName: () => null,
                closeModal: () => null,
            },
        ],
        showSuggestions: [
            false,
            {
                setShowSuggestions: (_, { show }) => show,
                selectEvent: () => false,
                closeModal: () => false,
            },
        ],
    }),

    loaders({
        eventDefinitions: [
            [] as EventDefinition[],
            {
                searchEvents: async ({ query }: { query: string }, breakpoint) => {
                    if (!query.trim()) {
                        return []
                    }
                    await breakpoint(300)
                    const result = await toolbarApi.eventDefinitions.search(query, {
                        context: 'search_event_definitions',
                        reauthenticateOnForbidden: true,
                    })

                    breakpoint()
                    if (!result.ok) {
                        return []
                    }
                    return result.data.results ?? []
                },
            },
        ],
        uploadResult: [
            null as null | { success: boolean },
            {
                submitUpload: async (_, breakpoint) => {
                    const { previewUrl, selectedDefinition } = screenshotUploadLogic.values
                    if (!previewUrl || !selectedDefinition) {
                        throw new Error('Please select an event')
                    }

                    // safeFetch can hand back a synthetic 502 JSON response (customer fetch
                    // wrapper) - never upload that body as the screenshot.
                    const previewResponse = await safeFetch(previewUrl)
                    if (!previewResponse.ok) {
                        throw new ToolbarRequestError('Failed to read screenshot preview', previewResponse.status)
                    }
                    const blob = await previewResponse.blob()
                    const { mediaId } = await uploadScreenshot(blob)
                    breakpoint()

                    // Tagged throw drives submitUploadFailure (which surfaces the toast)
                    // without reporting the failed request as an exception.
                    const result = await toolbarApi.objectMediaPreviews.create(
                        {
                            uploaded_media_id: mediaId,
                            event_definition_id: selectedDefinition.id,
                        },
                        { context: 'create_object_media_preview' }
                    )
                    breakpoint()
                    if (!result.ok) {
                        throw new ToolbarRequestError(result.error.detail, result.status)
                    }

                    return { success: true }
                },
            },
        ],
    }),

    listeners(({ actions, props, values }) => ({
        takeScreenshot: async () => {
            try {
                const blob = await captureElementScreenshot(document.documentElement)
                actions.openModal(URL.createObjectURL(blob))
            } catch (error) {
                actions.takeScreenshotFailure(error instanceof Error ? error.message : String(error))
            }
        },
        takeScreenshotFailure: ({ error }) => {
            lemonToast.error(`Failed to take screenshot: ${error}`)
        },
        closeModal: () => {
            if (values.previewUrl) {
                URL.revokeObjectURL(values.previewUrl)
            }
        },
        setEventName: ({ name }) => {
            actions.setShowSuggestions(name.length > 0)
            actions.searchEvents({ query: name })
        },
        submitUploadSuccess: () => {
            toolbarPosthogJS.capture('media preview uploaded', { source: 'toolbar' })
            lemonToast.success('Screenshot uploaded successfully')
            actions.closeModal()
            props.onSuccess?.()
        },
        submitUploadFailure: ({ error }) => {
            lemonToast.error(`Failed to upload screenshot: ${error}`)
        },
    })),
])