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.

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

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

import { heatmapToolbarMenuLogic } from '~/toolbar/shared/elements/heatmapToolbarMenuLogic'
import { currentPageLogic } from '~/toolbar/shared/stats/currentPageLogic'
import { toolbarApi } from '~/toolbar/shared/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import { ToolbarRequestError } from '~/toolbar/shared/toolbarRequestError'
import { urls } from '~/toolbar/shared/urls'
import { joinWithUiHost } from '~/toolbar/shared/utils'
import {
    RESPONSIVE_CAPTURE_WIDTHS,
    WidthCapture,
    captureResponsiveScreenshots,
} from '~/toolbar/shared/utils/responsiveScreenshot'
import { captureElementScreenshot } from '~/toolbar/shared/utils/screenshot'

interface HeatmapCaptureResult {
    id: string
    short_id: string
}

export interface CaptureProgress {
    done: number
    total: number
}

export interface CaptureSummary {
    savedWidths: number
    totalWidths: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface heatmapCaptureLogicValues {
    href: string // currentPageLogic
    wildcardHref: string // currentPageLogic
    windowWidth: number // heatmapToolbarMenuLogic
    isAuthenticated: boolean // toolbarConfigLogic
    uiHost: string // toolbarConfigLogic
    captureProgress: CaptureProgress | null
    captureResult: HeatmapCaptureResult | null
    captureResultLoading: boolean
    captureSummary: CaptureSummary | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface heatmapCaptureLogicActions {
    saveToPostHog: () => any
    saveToPostHogFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveToPostHogSuccess: (
        captureResult: {
            id: string
            short_id: string
        },
        payload?: any
    ) => {
        captureResult: {
            id: string
            short_id: string
        }
        payload?: any
    }
    setCaptureProgress: (progress: CaptureProgress | null) => {
        progress: CaptureProgress | null
    }
    setCaptureSummary: (summary: CaptureSummary | null) => {
        summary: CaptureSummary | null
    }
}

export type heatmapCaptureLogicType = MakeLogicType<heatmapCaptureLogicValues, heatmapCaptureLogicActions>

function buildBaseFormData(href: string, dataUrl: string): FormData {
    const formData = new FormData()
    formData.append('url', href)
    formData.append('data_url', dataUrl)
    formData.append('name', document.title || href)
    return formData
}

function buildMultiWidthFormData(href: string, dataUrl: string, captures: WidthCapture[]): FormData {
    const formData = buildBaseFormData(href, dataUrl)
    for (const { width, blob } of captures) {
        formData.append('images', new File([blob], `heatmap-${width}.jpg`, { type: 'image/jpeg' }))
        formData.append('widths', String(width))
    }
    return formData
}

async function buildSingleWidthFormData(href: string, dataUrl: string, width: number): Promise<FormData> {
    const blob = await captureElementScreenshot(document.documentElement)
    const formData = buildBaseFormData(href, dataUrl)
    formData.append('image', new File([blob], `heatmap-${Date.now()}.jpg`, { type: 'image/jpeg' }))
    formData.append('width', String(width))
    return formData
}

export const heatmapCaptureLogic = kea<heatmapCaptureLogicType>([
    path(['toolbar', 'stats', 'heatmapCaptureLogic']),
    connect(() => ({
        values: [
            currentPageLogic,
            ['href', 'wildcardHref'],
            heatmapToolbarMenuLogic,
            ['windowWidth'],
            toolbarConfigLogic,
            ['uiHost', 'isAuthenticated'],
        ],
    })),
    actions({
        setCaptureProgress: (progress: CaptureProgress | null) => ({ progress }),
        setCaptureSummary: (summary: CaptureSummary | null) => ({ summary }),
    }),
    reducers({
        captureProgress: [
            null as CaptureProgress | null,
            {
                setCaptureProgress: (_, { progress }) => progress,
            },
        ],
        captureSummary: [
            null as CaptureSummary | null,
            {
                setCaptureSummary: (_, { summary }) => summary,
            },
        ],
    }),
    loaders(({ values, actions }) => ({
        captureResult: [
            null as HeatmapCaptureResult | null,
            {
                saveToPostHog: async () => {
                    actions.setCaptureProgress({ done: 0, total: RESPONSIVE_CAPTURE_WIDTHS.length })

                    const captures = await captureResponsiveScreenshots(RESPONSIVE_CAPTURE_WIDTHS, (done, total) =>
                        actions.setCaptureProgress({ done, total })
                    )
                    actions.setCaptureSummary({
                        savedWidths: captures.length,
                        totalWidths: RESPONSIVE_CAPTURE_WIDTHS.length,
                    })

                    const formData =
                        captures.length > 0
                            ? buildMultiWidthFormData(values.href, values.wildcardHref, captures)
                            : await buildSingleWidthFormData(values.href, values.wildcardHref, values.windowWidth)

                    const result = await toolbarApi.savedHeatmaps.capture(formData, {
                        context: 'capture_heatmap',
                        reauthenticateOnForbidden: true,
                    })
                    if (!result.ok) {
                        throw new ToolbarRequestError(result.error.detail, result.status)
                    }
                    return result.data
                },
            },
        ],
    })),
    listeners(({ values, actions }) => ({
        saveToPostHogSuccess: ({ captureResult }) => {
            actions.setCaptureProgress(null)
            if (!captureResult) {
                return
            }
            const button = {
                label: 'Open in PostHog',
                action: () =>
                    window.open(joinWithUiHost(values.uiHost, urls.heatmap(captureResult.short_id)), '_blank'),
            }
            // Without an explicit id, the toast id is a hash of the message, so two saves that produce
            // the same message share one id and react-toastify drops the second toast while the first
            // one is still on screen.
            const toastOptions = { button, toastId: `heatmap-saved-${captureResult.short_id}` }
            const summary = values.captureSummary
            if (!summary || summary.savedWidths === summary.totalWidths) {
                lemonToast.success('Heatmap saved', toastOptions)
            } else if (summary.savedWidths === 0) {
                lemonToast.warning(
                    'Heatmap saved at your current window width only. Saving again creates a new heatmap and retries all page widths.',
                    toastOptions
                )
            } else {
                lemonToast.warning(
                    `Heatmap saved with ${summary.savedWidths} of ${summary.totalWidths} page widths. Saving again creates a new heatmap and retries all page widths.`,
                    toastOptions
                )
            }
        },
        saveToPostHogFailure: ({ error }) => {
            actions.setCaptureProgress(null)
            lemonToast.error(`Couldn't save this heatmap: ${error}`)
        },
    })),
])