: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(insights): copy an insight chart to the clipboard as an image (#90805)
Andrew Maguire9a36fb21e523
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0e21f7cfe213..cb41e3207cbb 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7213,13 +7213,13 @@ snapshots:scenes-app-insights-side-panel-actions--saved-hog-ql-data-table--light:hash: v1.k794b7964.5b4c6ba0ac07ba8ea0dc4d24a980821992ee75f62b2f885972e5d332394bed34.PnQhji05di1PUTIp8bvdzvWMfEmF0FfC_K5lAZiLAEEscenes-app-insights-side-panel-actions--saved-trends-insight--dark:- hash: v1.k794b7964.1683ee516831d01dc8dc1844da55bf77fbde1cafa1f6a3d736ab9dff68012bfa.bi59tFzDENljaxnWB7ZYRExvdplvuJZPpOxJyfrGRVo+ hash: v1.k794b7964.367281449c1d127133be3d10f1399ced5911fecf1fa0472b2b6c96f42cd59982.xtTNJEe-E_Cb8FGrcMmvhwGC6Xgt8-e0loICGBvSSvMscenes-app-insights-side-panel-actions--saved-trends-insight--light:- hash: v1.k794b7964.dd3d1a925e069a8bfc954516eeb5e734e789de93ef0648473fa5ad0b02458eb9.Mh8cuCvEcb8zR01c268DrxRiyEYA3Efyrmui6FZ1ZmM+ hash: v1.k794b7964.ae457c62363ca756235e3c518a25b61bfb23e65af80fde2e4ea73b69ce7b961c.9HK-y0iUK_31LwjHHDLvkGrfLuB67g1LQxwIo34JD68scenes-app-insights-side-panel-actions--unsaved-insight--dark:- hash: v1.k794b7964.e0482531b63e3c6c58bb438b0848b476db1ebadb82736444afb0004e5a7d9a2e.EgJaf86aq6hyYkPzdF8Aydv7rycYiRr_UV8fYh_LIL0+ hash: v1.k794b7964.27e7bb90a746914ab15ebdf82e5353bc54017d8d40c6c985acd836b3bfb068ae.ubmfp9aIuKwIOUk_KfFdd7bkRuv77pjb2nA13vH3fQoscenes-app-insights-side-panel-actions--unsaved-insight--light:- hash: v1.k794b7964.2b3ed2b5ffec763b0f7e13af74c9e9d57df96464976ae6014512a0d7def42ad3.paLp2yPHgkf2-ncauikOAUdR87k6-KhAh-Nm4uyQ380+ hash: v1.k794b7964.4d578bbdfaa1fc1273607e926b15daaffed027ec89dbfad45179410e7a208f6c.hjlOrgS-_brH3WWYD3R8RwnkJs2dmmiNFToArpB2bUcscenes-app-insights-sqlboxplot--edit-options--dark:hash: v1.k794b7964.70df9d8ffa57acac2d95f47d3298bb62ca009f1f4b556717ee0bbe319ab7754e.VwWfKL8TJDDpSmrV3mWOD0VkvzSnBrYJTFtSRpxlQcwscenes-app-insights-sqlboxplot--edit-options--light:diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsxnew file mode 100644index 000000000000..f53b2d86d67a--- /dev/null+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsx@@ -0,0 +1,112 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { ToastContainer } from 'react-toastify'++import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor'++import { initKeaTests } from '~/test/init'++import { SceneCopyImageButton } from './SceneCopyImageButton'++jest.mock('html-to-image', () => ({+ toBlob: jest.fn(() => Promise.resolve(new Blob(['png'], { type: 'image/png' }))),+}))++const TARGET = { selector: '[data-attr="insights-graph"]', screenshotKey: 'test' }++function renderButton(): void {+ render(+ <>+ <div data-attr="insights-graph">chart</div>+ <SceneCopyImageButton target={TARGET} dataAttrKey="insight" />+ <ScreenShotEditor screenshotKey={TARGET.screenshotKey} />+ <ToastContainer />+ </>+ )+}++describe('SceneCopyImageButton', () => {+ let write: jest.Mock++ beforeEach(() => {+ initKeaTests()++ write = jest.fn(() => Promise.resolve())+ Object.defineProperty(navigator, 'clipboard', { value: { write }, configurable: true })+ ;(global as any).ClipboardItem = jest.fn((items) => items)+ })++ afterEach(() => {+ cleanup()+ delete (global as any).ClipboardItem+ })++ it('says the image is on the clipboard and offers the screenshot editor', async () => {+ renderButton()++ await userEvent.click(screen.getByText('Copy as PNG'))++ expect(await screen.findByText('Image copied to clipboard')).toBeInTheDocument()+ expect(write).toHaveBeenCalledTimes(1)++ await userEvent.click(screen.getByText('Edit image'))++ expect(await screen.findByText('Edit Screenshot')).toBeInTheDocument()+ })++ it('points at Export when the clipboard write fails, and stays clickable', async () => {+ write.mockRejectedValueOnce(new Error('denied'))+ renderButton()++ await userEvent.click(screen.getByText('Copy as PNG'))++ expect(await screen.findByText(/Could not copy the image/)).toBeInTheDocument()+ expect(screen.getByText('Copy as PNG')).toBeEnabled()+ })++ it('reports a browser that cannot put images on the clipboard', async () => {+ delete (global as any).ClipboardItem+ renderButton()++ await userEvent.click(screen.getByText('Copy as PNG'))++ expect(await screen.findByText(/This browser cannot copy images/)).toBeInTheDocument()+ expect(write).not.toHaveBeenCalled()+ })++ it('captures nothing while a disabled reason holds', async () => {+ render(+ <>+ <div data-attr="insights-graph">chart</div>+ <SceneCopyImageButton+ target={TARGET}+ dataAttrKey="insight"+ disabledReasons={{ 'Wait for the insight to finish loading': true }}+ />+ </>+ )++ const button = screen.getByText('Copy as PNG')+ expect(button).toBeDisabled()++ await userEvent.click(button)++ expect(write).not.toHaveBeenCalled()+ })++ it('reports a missing target instead of copying an empty image', async () => {+ render(+ <>+ <SceneCopyImageButton target={TARGET} dataAttrKey="insight" />+ <ToastContainer />+ </>+ )++ await userEvent.click(screen.getByText('Copy as PNG'))++ expect(await screen.findByText(/Could not find anything to capture/)).toBeInTheDocument()+ expect(write).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.tsxnew file mode 100644index 000000000000..2816a675fcaf--- /dev/null+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.tsx@@ -0,0 +1,31 @@+import { useActions, useValues } from 'kea'++import { IconImage } from '@posthog/icons'++import { ButtonPrimitive, DisabledReasonsObject } from 'lib/ui/Button/ButtonPrimitives'++import { CaptureImageTarget, captureImageLogic } from './captureImageLogic'++interface SceneCopyImageButtonProps {+ target: CaptureImageTarget+ dataAttrKey: string+ disabledReasons?: DisabledReasonsObject+}++export function SceneCopyImageButton({ target, dataAttrKey, disabledReasons }: SceneCopyImageButtonProps): JSX.Element {+ const { copyImage } = useActions(captureImageLogic)+ const { isCapturing } = useValues(captureImageLogic)++ return (+ <ButtonPrimitive+ menuItem+ onClick={() => copyImage(target)}+ data-attr={`${dataAttrKey}-copy-image`}+ tooltip="Copy the chart to your clipboard as a PNG"+ disabledReasons={{ ...disabledReasons, 'Copying…': isCapturing }}+ >+ <IconImage />+ Copy as PNG+ </ButtonPrimitive>+ )+}diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.test.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.test.tsxnew file mode 100644index 000000000000..33df3ed07f94--- /dev/null+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.test.tsx@@ -0,0 +1,131 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { expectLogic } from 'kea-test-utils'+import { type ReactNode } from 'react'++import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'+import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { downloadFile } from 'lib/utils/dom'++import { initKeaTests } from '~/test/init'+import { ExporterFormat } from '~/types'++import { captureImageLogic } from './captureImageLogic'+import { SceneExportDropdownMenu } from './SceneExportDropdownMenu'++jest.mock('html-to-image', () => ({+ toBlob: jest.fn(() => Promise.resolve(new Blob(['png'], { type: 'image/png' }))),+}))+jest.mock('lib/utils/accessControlUtils', () => ({+ ...jest.requireActual('lib/utils/accessControlUtils'),+ getAccessControlDisabledReason: jest.fn(() => null),+}))+jest.mock('lib/utils/dom', () => ({+ ...jest.requireActual('lib/utils/dom'),+ downloadFile: jest.fn(),+}))++// Radix relies on pointer events that jsdom does not implement, so the menu renders inline here.+jest.mock('lib/ui/DropdownMenu/DropdownMenu', () => ({+ DropdownMenu: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DropdownMenuGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (+ <div onClick={onClick}>{children}</div>+ ),+ DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,+}))++const CSV_ITEM = { format: ExporterFormat.CSV, dataAttr: 'export-csv', context: { path: '/api/whatever' } }++describe('SceneExportDropdownMenu', () => {+ let logic: ReturnType<typeof exportsLogic.build>++ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ logic = exportsLogic()+ logic.mount()+ captureImageLogic.mount()+ })++ afterEach(() => {+ cleanup()+ captureImageLogic.unmount()+ logic.unmount()+ })++ it('runs a browser-side handler instead of asking the server to render the file', async () => {+ const onClick = jest.fn()+ render(+ <SceneExportDropdownMenu+ dropdownMenuItems={[{ format: ExporterFormat.PNG, dataAttr: 'export-png', onClick }, CSV_ITEM]}+ />+ )++ await userEvent.click(screen.getByText('.png'))++ expect(onClick).toHaveBeenCalledTimes(1)+ await expectLogic(logic).toNotHaveDispatchedActions(['startExport'])+ })++ it('still asks the server for a format with no browser-side handler', async () => {+ render(<SceneExportDropdownMenu dropdownMenuItems={[CSV_ITEM]} />)++ await userEvent.click(screen.getByText('.csv'))++ await expectLogic(logic).toDispatchActions(['startExport'])+ })++ it('downloads the browser-rendered PNG in one click, without opening the editor', async () => {+ const target = { selector: '[data-attr="insights-graph"]', screenshotKey: 'test', name: 'Weekly pageviews' }+ render(+ <>+ <div data-attr="insights-graph">chart</div>+ <SceneExportDropdownMenu+ dropdownMenuItems={[+ {+ format: ExporterFormat.PNG,+ dataAttr: 'export-png',+ onClick: () => captureImageLogic.actions.downloadImage(target),+ },+ ]}+ />+ <ScreenShotEditor screenshotKey={target.screenshotKey} />+ </>+ )++ await userEvent.click(screen.getByText('.png'))++ await waitFor(() => expect(downloadFile).toHaveBeenCalledTimes(1))+ expect(jest.mocked(downloadFile).mock.calls[0][0].name).toBe('weekly-pageviews.png')+ expect(screen.queryByText('Edit Screenshot')).not.toBeInTheDocument()+ })++ it.each([+ ['only server-rendered formats', false, true],+ ['a browser-rendered format', true, false],+ ])('handles export access when the menu has %s', (_name, hasBrowserRenderedFormat, exportMenuDisabled) => {+ jest.mocked(getAccessControlDisabledReason).mockReturnValue('You do not have export access')+ const onClick = jest.fn()+ const browserRenderedItem = {+ format: ExporterFormat.PNG,+ dataAttr: 'export-png',+ onClick,+ }+ render(+ <SceneExportDropdownMenu+ dropdownMenuItems={hasBrowserRenderedFormat ? [browserRenderedItem, CSV_ITEM] : [CSV_ITEM]}+ />+ )++ expect(screen.getByText('Export')).toHaveProperty('disabled', exportMenuDisabled)+ expect(screen.getByText('.csv')).toBeDisabled()+ if (hasBrowserRenderedFormat) {+ expect(screen.getByText('.png')).toBeEnabled()+ }+ })+})diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsxindex 8572f5845f4c..83670ef2a5cc 100644--- a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx@@ -35,6 +35,10 @@ interface SceneExportDropdownMenuProps extends SubscriptionBaseProps {insight?: numberdashboard?: numbercontext?: ExportContext+ /** Produce the file in the browser instead of asking the server to render an export. */+ onClick?: () => void+ /** Reasons this one format cannot be produced, keyed by the message to show. */+ disabledReasons?: DisabledReasonsObject}[]}@@ -49,14 +53,17 @@ export function SceneExportDropdownMenu({startExport(triggerExportProps)}- // Creating an export requires editor access to the export resource.+ // Creating an export requires editor access to the export resource. It is applied per format rather+ // than to the whole menu, because a format produced in the browser creates no export asset: it+ // rasterizes what the person is already looking at, which they can screenshot anyway.const accessControlDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Export,AccessControlLevel.Editor)+ const hasBrowserRenderedFormat = dropdownMenuItems.some((item) => !!item.onClick)const resolvedDisabledReasons: DisabledReasonsObject = {...disabledReasons,- ...(accessControlDisabledReason ? { [accessControlDisabledReason]: true } : {}),+ ...(!hasBrowserRenderedFormat && accessControlDisabledReason ? { [accessControlDisabledReason]: true } : {}),}const isDisabled = Object.values(resolvedDisabledReasons).some(Boolean)@@ -73,6 +80,14 @@ export function SceneExportDropdownMenu({<DropdownMenuContent align="start" matchTriggerWidth><DropdownMenuGroup>{dropdownMenuItems.map((item, index) => {+ const rendersInBrowser = !!item.onClick+ const itemDisabledReasons: DisabledReasonsObject = {+ ...item.disabledReasons,+ ...(!rendersInBrowser && accessControlDisabledReason+ ? { [accessControlDisabledReason]: true }+ : {}),+ }+ const itemDisabled = Object.values(itemDisabledReasons).some(Boolean)const exportFormatExtension = Object.keys(ExporterFormat).find((key) => ExporterFormat[key as keyof typeof ExporterFormat] === item.format)?.toLowerCase()@@ -93,7 +108,15 @@ export function SceneExportDropdownMenu({return (<DropdownMenuItemkey={index}- onClick={() =>+ disabled={itemDisabled}+ onClick={() => {+ if (itemDisabled) {+ return+ }+ if (item.onClick) {+ item.onClick()+ return+ }void onExportClick({export_format: item.format,...(item.insight && { insight: item.insight }),@@ -101,15 +124,15 @@ export function SceneExportDropdownMenu({...(item.dashboard && { dashboard: item.dashboard }),...(item.context && { export_context: item.context }),})- }+ }}data-attr={`export-button-${exportFormatExtension}`}- data-ph-capture-attribute-export-target={target}+ data-ph-capture-attribute-export-target={rendersInBrowser ? null : target}data-ph-capture-attribute-export-body={- exportBody.length ? JSON.stringify(exportBody) : null+ !rendersInBrowser && exportBody.length ? JSON.stringify(exportBody) : null}asChild>- <ButtonPrimitive menuItem>+ <ButtonPrimitive menuItem disabledReasons={itemDisabledReasons}>{item.label ? item.label : `.${exportFormatExtension}`}</ButtonPrimitive></DropdownMenuItem>diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.ts b/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.tsnew file mode 100644index 000000000000..8127d526dbc2--- /dev/null+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.ts@@ -0,0 +1,133 @@+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+ /** 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 {+ 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)+ } 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)+ 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)+ }+ },+ })),+])diff --git a/frontend/src/lib/utils/captureElementImage.test.ts b/frontend/src/lib/utils/captureElementImage.test.tsnew file mode 100644index 000000000000..5dd267ed0d17--- /dev/null+++ b/frontend/src/lib/utils/captureElementImage.test.ts@@ -0,0 +1,19 @@+import { toBlob } from 'html-to-image'++import { captureElementImage } from './captureElementImage'++jest.mock('html-to-image', () => ({+ toBlob: jest.fn(() => Promise.resolve(new Blob(['png'], { type: 'image/png' }))),+}))++describe('captureElementImage', () => {+ it('leaves CSS custom properties out of the copied style properties', async () => {+ document.documentElement.style.setProperty('--a-design-token', 'red')++ await captureElementImage(document.createElement('div'))++ const { includeStyleProperties } = (toBlob as jest.Mock).mock.calls[0][1]+ expect(includeStyleProperties).not.toBeUndefined()+ expect(includeStyleProperties.filter((name: string) => name.startsWith('--'))).toEqual([])+ })+})diff --git a/frontend/src/lib/utils/captureElementImage.ts b/frontend/src/lib/utils/captureElementImage.tsnew file mode 100644index 000000000000..6bcfbc561609--- /dev/null+++ b/frontend/src/lib/utils/captureElementImage.ts@@ -0,0 +1,42 @@+import { toBlob } 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+}++/** 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(),+ ...options,+ })++ if (!blob) {+ throw new Error('Rendering the element to an image produced no data')+ }++ return blob+}diff --git a/frontend/src/lib/utils/copyImageToClipboard.ts b/frontend/src/lib/utils/copyImageToClipboard.tsnew file mode 100644index 000000000000..bc39a258f3b9--- /dev/null+++ b/frontend/src/lib/utils/copyImageToClipboard.ts@@ -0,0 +1,47 @@+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): Promise<Blob> {+ return captureElementImage(element, {+ 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): 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)+ 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 }+ }+}diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsxindex af626ee6827c..50d73f3c012b 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx@@ -27,6 +27,7 @@ import {} from 'scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils'import { InsightAIAnalysis } from 'scenes/insights/InsightAIAnalysis'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { INSIGHT_GRAPH_DATA_ATTR } from 'scenes/insights/insightImageCapture'import { insightLogic } from 'scenes/insights/insightLogic'import { insightNavLogic } from 'scenes/insights/InsightNav/insightNavLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'@@ -508,7 +509,7 @@ export function InsightVizDisplay({`InsightVizDisplay InsightVizDisplay--type-${activeView.toLowerCase()}`,!embedded && 'border rounded bg-surface-primary')}- data-attr="insights-graph"+ data-attr={INSIGHT_GRAPH_DATA_ATTR}>{disableHeader ? null : <InsightDisplayConfig />}{showingResults && (diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsxindex 37d780292d2e..dc5da9e36301 100644--- a/frontend/src/scenes/insights/InsightModals.tsx+++ b/frontend/src/scenes/insights/InsightModals.tsx@@ -3,10 +3,12 @@ import { router } from 'kea-router'import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'import { SharingModal } from 'lib/components/Sharing/SharingModal'+import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor'import { TerraformExportModal } from 'lib/components/TerraformExporter/TerraformExportModal'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { INSIGHT_SCREENSHOT_KEY } from 'scenes/insights/insightImageCapture'import { insightLogic } from 'scenes/insights/insightLogic'import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'import { urls } from 'scenes/urls'@@ -41,6 +43,7 @@ export function InsightModals({ insightLogicProps }: { insightLogicProps: Insigh)}<InsightTerraformModalWrapper insightLogicProps={insightLogicProps} />+ <ScreenShotEditor screenshotKey={INSIGHT_SCREENSHOT_KEY} /></>)}diff --git a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsxindex dc38a8b2676e..51b829c6cade 100644--- a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx+++ b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx@@ -4,8 +4,10 @@ import { router } from 'kea-router'import { IconCode2, IconCopy, IconEndpoints, IconGraph, IconPencil, IconPeople } from '@posthog/icons'import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'+import { captureImageLogic } from 'lib/components/Scenes/InsightOrDashboard/captureImageLogic'import { SceneAddToDashboardButton } from 'lib/components/Scenes/InsightOrDashboard/SceneAddToDashboardButton'import { SceneAddToNotebookDropdownMenu } from 'lib/components/Scenes/InsightOrDashboard/SceneAddToNotebookDropdownMenu'+import { SceneCopyImageButton } from 'lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton'import { SceneExportDropdownMenu } from 'lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu'import { SceneAlertsButton } from 'lib/components/Scenes/SceneAlertsButton'import { SceneDuplicate } from 'lib/components/Scenes/SceneDuplicate'@@ -17,12 +19,19 @@ import { Link } from 'lib/lemon-ui/Link'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { INSIGHT_GRAPH_SELECTOR, INSIGHT_SCREENSHOT_KEY } from 'scenes/insights/insightImageCapture'import { insightLogic } from 'scenes/insights/insightLogic'import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopyLogic'import { urls } from 'scenes/urls'import { ScenePanelActionsSection } from '~/layout/scenes/SceneLayout'-import { isDataTableNode, isDataVisualizationNode, isEventsQuery, isHogQLQuery } from '~/queries/utils'+import {+ isDataTableNode,+ isDataVisualizationNode,+ isEventsQuery,+ isHogQLQuery,+ isInsightVizNode,+} from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -46,7 +55,8 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:const { duplicateInsight, setInsightMetadata } = useActions(theInsightLogic)const theInsightDataLogic = insightDataLogic(insightProps)- const { query, hogQL, exportContext, hogQLVariables, canEditInSqlEditor } = useValues(theInsightDataLogic)+ const { query, hogQL, exportContext, hogQLVariables, canEditInSqlEditor, insightDataLoading, insightDataError } =+ useValues(theInsightDataLogic)const { createStaticCohort } = useActions(exportsLogic)const { openCreateFromInsightModal } = useActions(endpointLogic)@@ -54,6 +64,7 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:const { openAddToDashboardModal, openTerraformModal } = useActions(insightModalsLogic(insightLogicProps))const { canCopyToProject } = useValues(interProjectCopyLogic)+ const { downloadImage } = useActions(captureImageLogic)const isSavedInsight = hasDashboardItemId && !!insight?.id && !!insight?.short_id@@ -67,6 +78,20 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:AccessControlLevel.Viewer)const canExport = exportContext != null && insight.short_id != null+ // Only an InsightViz renders the results card the browser-side capture targets. Anything else+ // still goes through the server-side PNG render.+ const canCaptureImage = isInsightVizNode(query)+ const captureTarget = {+ selector: INSIGHT_GRAPH_SELECTOR,+ screenshotKey: INSIGHT_SCREENSHOT_KEY,+ name: insight.name || insight.derived_name || undefined,+ }+ // A browser capture takes whatever is on screen. The results card renders before the chart does, so+ // capturing mid-load or after a failed query produces a valid PNG of an empty card.+ const captureDisabledReasons = {+ 'Wait for the insight to finish loading': insightDataLoading,+ 'The insight has no results to capture': !!insightDataError,+ }const showCohort =hogQL != null &&(isDataTableNode(query) || isDataVisualizationNode(query) || isHogQLQuery(query) || isEventsQuery(query))@@ -89,6 +114,13 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:Copy to another project</ButtonPrimitive>)}+ {canCaptureImage && (+ <SceneCopyImageButton+ target={captureTarget}+ dataAttrKey={RESOURCE_TYPE}+ disabledReasons={captureDisabledReasons}+ />+ )}<SceneFavoritedataAttrKey={RESOURCE_TYPE}onClick={() => setInsightMetadata({ favorited: !insight.favorited })}@@ -157,6 +189,8 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:insight: insight.id,context: exportContext,dataAttr: `${RESOURCE_TYPE}-export-png`,+ onClick: canCaptureImage ? () => downloadImage(captureTarget) : undefined,+ disabledReasons: canCaptureImage ? captureDisabledReasons : undefined,},{format: ExporterFormat.CSV,diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsxindex 361c685d9997..286a64539cc1 100644--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx@@ -8,6 +8,7 @@ import {IconDownload,IconEndpoints,IconGraph,+ IconImage,IconPencil,IconPeople,IconPlusSmall,@@ -21,6 +22,7 @@ import { Button } from '@posthog/quill'import { AccessControlAction } from 'lib/components/AccessControlAction'import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'import { metalyticsLogic } from 'lib/components/Metalytics/metalyticsLogic'+import { captureImageLogic } from 'lib/components/Scenes/InsightOrDashboard/captureImageLogic'import { SceneMenuBarAddToNotebook } from 'lib/components/Scenes/SceneMenuBarAddToNotebook'import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'import { SceneTagsCombobox } from 'lib/components/Scenes/SceneTagsCombobox'@@ -29,6 +31,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { INSIGHT_GRAPH_SELECTOR, INSIGHT_SCREENSHOT_KEY } from 'scenes/insights/insightImageCapture'import { insightLogic } from 'scenes/insights/insightLogic'import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'import { NotebookNodeType } from 'scenes/notebooks/types'@@ -49,7 +52,13 @@ import {} from '~/layout/scenes/components/SceneMenuBar'import { tagsModel } from '~/models/tagsModel'import { NodeKind } from '~/queries/schema/schema-general'-import { isDataTableNode, isDataVisualizationNode, isEventsQuery, isHogQLQuery } from '~/queries/utils'+import {+ isDataTableNode,+ isDataVisualizationNode,+ isEventsQuery,+ isHogQLQuery,+ isInsightVizNode,+} from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -90,8 +99,17 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: Inconst { duplicateInsight, deleteInsight, setInsightMetadata } = useActions(theInsightLogic)const theInsightDataLogic = insightDataLogic(insightProps)- const { query, hogQL, exportContext, hogQLVariables, canEditInSqlEditor, showQueryEditor, showDebugPanel } =- useValues(theInsightDataLogic)+ const {+ query,+ hogQL,+ exportContext,+ hogQLVariables,+ canEditInSqlEditor,+ showQueryEditor,+ showDebugPanel,+ insightDataLoading,+ insightDataError,+ } = useValues(theInsightDataLogic)const { toggleQueryEditorPanel, toggleDebugPanel } = useActions(theInsightDataLogic)const { insightMode, dashboardId } = useValues(insightSceneLogic)@@ -104,6 +122,8 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: Inconst { openTerraformModal, openAddToDashboardModal } = useActions(insightModalsLogic(insightLogicProps))const { canCopyToProject } = useValues(interProjectCopyLogic)+ const { copyImage, downloadImage } = useActions(captureImageLogic)+ const { isCapturing: isCapturingImage } = useValues(captureImageLogic)const { tags: allExistingTags } = useValues(tagsModel)const { user, hasAvailableFeature } = useValues(userLogic)@@ -112,7 +132,7 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: Inconst { instanceId: metalyticsInstanceId } = useValues(metalyticsLogic)// Creating an export requires editor access to the export resource.- const exportAccessControlDisabledReason = getAccessControlDisabledReason(+ const exportAssetAccessControlDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Export,AccessControlLevel.Editor)@@ -123,6 +143,22 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: Inconst isSavedInsight = hasDashboardItemId && !!insight?.id && !!insight?.short_idconst canExport = exportContext != null && insight.short_id != null+ // Only an InsightViz renders the results card the browser-side capture targets. Anything else+ // still goes through the server-side PNG render.+ const canCaptureImage = isInsightVizNode(query)+ const captureTarget = {+ selector: INSIGHT_GRAPH_SELECTOR,+ screenshotKey: INSIGHT_SCREENSHOT_KEY,+ name: insight.name || insight.derived_name || undefined,+ }+ // A browser capture takes whatever is on screen. The results card renders before the chart does, so+ // capturing mid-load or after a failed query produces a valid PNG of an empty card.+ const captureDisabledReason = insightDataLoading+ ? 'Wait for the insight to finish loading'+ : insightDataError+ ? 'The insight has no results to capture'+ : undefined+ const pngExportDisabledReason = canCaptureImage ? captureDisabledReason : exportAssetAccessControlDisabledReasonconst showCohort =hogQL != null &&(isDataTableNode(query) || isDataVisualizationNode(query) || isHogQLQuery(query) || isEventsQuery(query))@@ -259,6 +295,17 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: InCopy to another project</SceneMenuBarItem>)}+ {canCaptureImage && (+ <SceneMenuBarItem+ onClick={() => copyImage(captureTarget)}+ disabled={isCapturingImage || !!captureDisabledReason}+ tooltip={captureDisabledReason}+ data-attr={`${RESOURCE_TYPE}-menubar-copy-image`}+ >+ <IconImage />+ Copy as PNG+ </SceneMenuBarItem>+ )}<SceneMenuBarItemopensFloatingUionClick={openTerraformModal}@@ -270,15 +317,17 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In{canExport && (<SceneMenuBarSubMenu label="Export"><SceneMenuBarItem- disabled={!!exportAccessControlDisabledReason}- tooltip={exportAccessControlDisabledReason ?? undefined}+ disabled={(canCaptureImage && isCapturingImage) || !!pngExportDisabledReason}+ tooltip={pngExportDisabledReason}onClick={() =>- startExport({- export_format: ExporterFormat.PNG,- insight: insight.id,- insightShortId: insight.short_id,- export_context: exportContext,- })+ canCaptureImage+ ? downloadImage(captureTarget)+ : startExport({+ export_format: ExporterFormat.PNG,+ insight: insight.id,+ insightShortId: insight.short_id,+ export_context: exportContext,+ })}data-attr={`${RESOURCE_TYPE}-menubar-export-png`}>@@ -286,8 +335,8 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: InPNG</SceneMenuBarItem><SceneMenuBarItem- disabled={!!exportAccessControlDisabledReason}- tooltip={exportAccessControlDisabledReason ?? undefined}+ disabled={!!exportAssetAccessControlDisabledReason}+ tooltip={exportAssetAccessControlDisabledReason ?? undefined}onClick={() =>startExport({export_format: ExporterFormat.CSV,@@ -300,8 +349,8 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: InCSV</SceneMenuBarItem><SceneMenuBarItem- disabled={!!exportAccessControlDisabledReason}- tooltip={exportAccessControlDisabledReason ?? undefined}+ disabled={!!exportAssetAccessControlDisabledReason}+ tooltip={exportAssetAccessControlDisabledReason ?? undefined}onClick={() =>startExport({export_format: ExporterFormat.XLSX,diff --git a/frontend/src/scenes/insights/insightImageCapture.ts b/frontend/src/scenes/insights/insightImageCapture.tsnew file mode 100644index 000000000000..42d5ffd3f9e5--- /dev/null+++ b/frontend/src/scenes/insights/insightImageCapture.ts@@ -0,0 +1,10 @@+/**+ * Marks the card holding the chart and its legend. Playwright and the image capture actions both find+ * the results this way, so treat the value as a wire string and do not rename it.+ */+export const INSIGHT_GRAPH_DATA_ATTR = 'insights-graph'++export const INSIGHT_GRAPH_SELECTOR = `[data-attr="${INSIGHT_GRAPH_DATA_ATTR}"]`++/** Keys the screenshot editor instance that the insight scene mounts. */+export const INSIGHT_SCREENSHOT_KEY = 'insight'diff --git a/frontend/src/toolbar/utils/screenshot.ts b/frontend/src/toolbar/utils/screenshot.tsindex 824c9942edf0..656c583d818d 100644--- a/frontend/src/toolbar/utils/screenshot.ts+++ b/frontend/src/toolbar/utils/screenshot.ts@@ -1,4 +1,4 @@-import { toBlob } from 'html-to-image'+import { captureElementImage } from 'lib/utils/captureElementImage'import { toolbarUploadMedia } from '~/toolbar/toolbarFetch'import { TOOLBAR_ID } from '~/toolbar/utils'@@ -11,24 +11,6 @@ function screenshotFilter(node: Node): boolean {return !(node instanceof HTMLElement && node.id === TOOLBAR_ID)}-let cachedStylePropertyNames: string[] | null = null--const getAllStylePropertyNames = (): 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 interface CaptureOptions {pixelRatio?: numberwidth?: number@@ -37,19 +19,12 @@ export interface CaptureOptions {}export async function captureElementScreenshot(element: HTMLElement, options?: CaptureOptions): Promise<Blob> {- const blob = await toBlob(element, {+ return captureElementImage(element, {type: 'image/jpeg',- includeStyleProperties: getAllStylePropertyNames(),quality: 0.7,filter: screenshotFilter,...options,})-- if (!blob) {- throw new Error('Failed to capture element screenshot')- }-- return blob}export async function uploadScreenshot(blob: Blob): Promise<ElementScreenshot> {