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.

2.2 KB
Raw Blame
import { toBlob, toSvg } from 'html-to-image'

/** html-to-image does not re-export its options type. */
export type CaptureImageOptions = NonNullable<Parameters<typeof toBlob>[1]>

let cachedStylePropertyNames: string[] | null = null

/**
 * html-to-image copies every property in this list onto every cloned node. Its own default is the full
 * computed style of the document element, which in this app carries several hundred CSS custom properties
 * from the design tokens. Those resolve into the copied values already, so listing them only multiplies the
 * per-node work. The list is the same for every element, so it is built once.
 */
function getStylePropertyNames(): string[] {
    if (cachedStylePropertyNames) {
        return cachedStylePropertyNames
    }
    const names: string[] = []
    const style = getComputedStyle(document.documentElement)
    for (let i = 0; i < style.length; i++) {
        const name = style[i]
        if (!name.startsWith('--')) {
            names.push(name)
        }
    }
    cachedStylePropertyNames = names
    return names
}

export const BLANK_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'

const RESOURCE_FETCH_TIMEOUT_MS = 15000

/** Rasterizes a live DOM element to an image blob. Throws when the element renders to nothing. */
export async function captureElementImage(element: HTMLElement, options?: CaptureImageOptions): Promise<Blob> {
    const blob = await toBlob(element, {
        includeStyleProperties: getStylePropertyNames(),
        includeQueryParams: true,
        imagePlaceholder: BLANK_IMAGE,
        onImageErrorHandler: () => {},
        fetchRequestInit: { signal: AbortSignal.timeout(RESOURCE_FETCH_TIMEOUT_MS) },
        ...options,
    })

    if (!blob) {
        throw new Error('Rendering the element to an image produced no data')
    }

    return blob
}

/** Serializes a live DOM element to an SVG data URL, for callers that edit the clone before they rasterize it. */
export async function captureElementSvg(element: HTMLElement, options?: CaptureImageOptions): Promise<string> {
    return await toSvg(element, {
        includeStyleProperties: getStylePropertyNames(),
        ...options,
    })
}