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.8 KB
Raw Blame
import { captureElementImage } from 'lib/utils/captureElementImage'

/**
 * `copied` — a PNG of the element is on the clipboard.
 * `unsupported` — the browser exposes no way to put an image on the clipboard.
 * `failed` — the capture or the clipboard write was attempted and did not land.
 */
export type CopyImageOutcome = 'copied' | 'unsupported' | 'failed'

/** The blob comes back so the caller can reuse the capture instead of rendering the element twice. */
export type CopyImageResult = { outcome: 'copied'; blob: Blob } | { outcome: 'unsupported' | 'failed'; blob: null }

const CLIPBOARD_IMAGE_TYPE = 'image/png'

export function canCopyImageToClipboard(): boolean {
    return typeof ClipboardItem !== 'undefined' && !!navigator.clipboard?.write
}

export async function captureElementAsPng(element: HTMLElement, excludeSelector?: string): Promise<Blob> {
    return captureElementImage(element, {
        // Hover controls and other chrome inside the element are part of the app, not of the picture.
        filter: excludeSelector ? (node) => !(node instanceof Element && node.matches(excludeSelector)) : undefined,
        // The capture keeps the element's own computed position, and the image is only as big as the
        // element. A dashboard tile carries react-grid-layout's translate to its slot in the grid, which
        // would push it straight out of that frame, so the element is put back at the origin to be drawn.
        style: { transform: 'none', position: 'relative', inset: 'auto', margin: '0' },
        type: CLIPBOARD_IMAGE_TYPE,
        // Charts are read at a glance after being pasted, so capture at 2x to keep text and lines sharp.
        pixelRatio: 2,
        // Anything the element leaves transparent shows the page behind it, which turns into a
        // checkerboard or a black box once pasted. Fill it with the page background instead.
        backgroundColor: getComputedStyle(document.body).backgroundColor || undefined,
    })
}

export async function copyElementImageToClipboard(
    element: HTMLElement,
    excludeSelector?: string
): Promise<CopyImageResult> {
    if (!canCopyImageToClipboard()) {
        return { outcome: 'unsupported', blob: null }
    }

    // Safari only accepts a clipboard write that starts in the same task as the click, so the pending
    // capture goes onto the ClipboardItem rather than being awaited first. Attach a no-op handler as
    // well, because the write never observes the promise if the ClipboardItem constructor throws.
    const capture = captureElementAsPng(element, excludeSelector)
    capture.catch(() => {})

    try {
        await navigator.clipboard.write([new ClipboardItem({ [CLIPBOARD_IMAGE_TYPE]: capture })])
        return { outcome: 'copied', blob: await capture }
    } catch {
        return { outcome: 'failed', blob: null }
    }
}