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.

5.4 KB
Raw Blame
import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
import posthog from 'posthog-js'

import { takeScreenshotLogic } from 'lib/components/TakeScreenshot/takeScreenshotLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { ToastButton } from 'lib/lemon-ui/LemonToast/LemonToast'
import { captureElementAsPng, copyElementImageToClipboard } from 'lib/utils/copyImageToClipboard'
import { downloadFile } from 'lib/utils/dom'
import { slugify } from 'lib/utils/strings'

export interface CaptureImageTarget {
    /** CSS selector for the element to capture. */
    selector: string
    /** CSS selector for elements inside the capture to leave out of the image, such as hover controls. */
    excludeSelector?: string
    /** Keys the screenshot editor instance the image is handed to. */
    screenshotKey: string
    /** Name for the downloaded file, without the extension. */
    name?: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface captureImageLogicValues {
    isCapturing: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface captureImageLogicActions {
    copyImage: (target: CaptureImageTarget) => {
        target: CaptureImageTarget
    }
    downloadImage: (target: CaptureImageTarget) => {
        target: CaptureImageTarget
    }
    setIsCapturing: (isCapturing: boolean) => {
        isCapturing: boolean
    }
}

export type captureImageLogicType = MakeLogicType<captureImageLogicValues, captureImageLogicActions>

function findTarget(selector: string): HTMLElement | null {
    const element = document.querySelector<HTMLElement>(selector)
    if (!element) {
        lemonToast.error('Could not find anything to capture. Reload the page and try again.')
    }
    return element
}

function toFile(target: CaptureImageTarget, blob: Blob): File {
    const name = target.name ? slugify(target.name) : ''
    return new File([blob], `${name || 'export'}.png`, { type: 'image/png' })
}

function editImageButton(target: CaptureImageTarget, blob: Blob): ToastButton | undefined {
    // Only surfaces that mount the editor can open it, so elsewhere the toast carries no button at all
    // rather than one that fails on click.
    if (!takeScreenshotLogic.findMounted({ screenshotKey: target.screenshotKey })) {
        return undefined
    }
    return {
        label: 'Edit image',
        action: () => openScreenshotEditor(target.screenshotKey, blob),
        dataAttr: 'capture-image-edit',
    }
}

function openScreenshotEditor(screenshotKey: string, blob: Blob): void {
    // The editor renders its own modal, so it must already be on the page for this to do anything.
    const editor = takeScreenshotLogic.findMounted({ screenshotKey })
    if (!editor) {
        lemonToast.error('Could not open the image editor. Reload the page and try again.')
        return
    }
    editor.actions.setBlob(blob)
}

export const captureImageLogic = kea<captureImageLogicType>([
    path(['lib', 'components', 'Scenes', 'InsightOrDashboard', 'captureImageLogic']),
    actions({
        copyImage: (target: CaptureImageTarget) => ({ target }),
        downloadImage: (target: CaptureImageTarget) => ({ target }),
        setIsCapturing: (isCapturing: boolean) => ({ isCapturing }),
    }),
    reducers({
        isCapturing: [
            false,
            {
                setIsCapturing: (_, { isCapturing }) => isCapturing,
            },
        ],
    }),
    listeners(({ actions }) => ({
        copyImage: async ({ target }) => {
            const element = findTarget(target.selector)
            if (!element) {
                return
            }

            actions.setIsCapturing(true)
            let result: Awaited<ReturnType<typeof copyElementImageToClipboard>>
            try {
                result = await copyElementImageToClipboard(element, target.excludeSelector)
            } finally {
                actions.setIsCapturing(false)
            }

            if (result.outcome === 'copied') {
                lemonToast.success('Image copied to clipboard', { button: editImageButton(target, result.blob) })
            } else if (result.outcome === 'unsupported') {
                lemonToast.error('This browser cannot copy images. Use Export to download a PNG instead.')
            } else {
                lemonToast.error('Could not copy the image. Use Export to download a PNG instead.')
            }

            // Browsers vary in how well they render and accept an image built from the live DOM, so the
            // outcome is worth measuring rather than assuming.
            posthog.capture('copied element image', { outcome: result.outcome, selector: target.selector })
        },

        downloadImage: async ({ target }) => {
            const element = findTarget(target.selector)
            if (!element) {
                return
            }

            actions.setIsCapturing(true)
            try {
                const blob = await captureElementAsPng(element, target.excludeSelector)
                downloadFile(toFile(target, blob))
                lemonToast.success('Image downloaded', { button: editImageButton(target, blob) })
                posthog.capture('downloaded element image', { selector: target.selector })
            } catch {
                lemonToast.error('Could not create the image. Try again.')
            } finally {
                actions.setIsCapturing(false)
            }
        },
    })),
])