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.

feat(dashboards): copy a dashboard tile as a PNG (#93954)

Paul D'Ambrac36040df42cc
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index c5b2464a1303..84a4e0f600dd 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -47,6 +47,7 @@ import type { AlertType } from 'products/alerts/frontend/types'
import { DashboardResizeHandles } from '../handles'
import { EditModeEdge, EditModeEdgeOverlay } from './EditModeEdgeOverlay'
+import { INSIGHT_CARD_KEY_ATTR, insightCardKey } from './insightCardImageCapture'
import { InsightMeta } from './InsightMeta'
const IS_STORYBOOK = inStorybook() || inStorybookTestRunner()
@@ -439,6 +440,7 @@ function InsightCardInternal(
className
)}
data-attr="insight-card"
+ {...{ [INSIGHT_CARD_KEY_ATTR]: insightCardKey(insight, tile) }}
{...divProps}
// eslint-disable-next-line react/forbid-dom-props
style={{ ...divProps?.style, ...theme?.boxStyle }}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index f067401b1219..60b79b406ac0 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -12,6 +12,7 @@ import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'
import { EditableField } from 'lib/components/EditableField/EditableField'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
+import { captureImageLogic } from 'lib/components/Scenes/InsightOrDashboard/captureImageLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { IconLink } from 'lib/lemon-ui/icons'
@@ -74,6 +75,7 @@ import type { DashboardSqlVisualizationPersistence } from './dashboardVisualizat
import { dashboardWidgetMenusLogic } from './dashboardWidgetMenusLogic'
import { DashboardWidgetPlacementMenus } from './DashboardWidgetPlacementMenus'
import { InsightCardProps } from './InsightCard'
+import { insightCardCaptureTarget } from './insightCardImageCapture'
import { InsightDetails } from './InsightDetails'
interface InsightMetaProps extends Pick<
@@ -182,6 +184,8 @@ export function InsightMeta({
dashboard_tiles: insight.dashboard_tiles,
})
)
+ const { copyImage } = useActions(captureImageLogic)
+ const { isCapturing: isCapturingImage } = useValues(captureImageLogic)
const { updateInsightDirect } = useActions(insightsModel)
const { reportDashboardInsightMetaUpdated } = useActions(eventUsageLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -355,6 +359,14 @@ export function InsightMeta({
// icon (which hides while this tile refreshes) the menu item stays but disables.
const refreshMenuDisabledReason = tileRefreshing ? 'Refreshing…' : refreshDisabledReason
+ // A browser capture takes whatever is on screen, so a tile captured mid-load makes a valid PNG of an
+ // empty card.
+ const copyImageDisabledReason = isCapturingImage
+ ? 'Copying…'
+ : tileRefreshing
+ ? 'Wait for the insight to finish loading'
+ : undefined
+
// Gate the hover icon on `showEditingControls` so it doesn't appear on public/export
// dashboards, matching the "⋯" menu (which is already gated there).
const refreshControl =
@@ -651,6 +663,15 @@ export function InsightMeta({
/>
</>
) : null}
+ <LemonButton
+ onClick={() => copyImage(insightCardCaptureTarget(insight, tile, dashboardId))}
+ disabledReason={copyImageDisabledReason}
+ tooltip="Copy the tile to your clipboard as a PNG"
+ fullWidth
+ data-attr="insight-card-copy-image"
+ >
+ Copy as PNG
+ </LemonButton>
{refresh && (
<DashboardTileRefreshDataButton
onRefresh={refresh}
@@ -669,8 +690,8 @@ export function InsightMeta({
}
moreTooltip={
canEditInsight
- ? 'Rename, duplicate, export, refresh and more…'
- : 'Duplicate, export, refresh and more…'
+ ? 'Rename, duplicate, export, copy as PNG, refresh and more…'
+ : 'Duplicate, export, copy as PNG, refresh and more…'
}
extraControls={
placement !== DashboardPlacement.Public &&
diff --git a/frontend/src/lib/components/Cards/InsightCard/insightCardImageCapture.test.ts b/frontend/src/lib/components/Cards/InsightCard/insightCardImageCapture.test.ts
new file mode 100644
index 000000000000..111ace6fc8b1
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/insightCardImageCapture.test.ts
@@ -0,0 +1,52 @@
+import '@testing-library/jest-dom'
+
+import { InsightShortId } from '~/types'
+
+import { INSIGHT_CARD_KEY_ATTR, insightCardCaptureTarget } from './insightCardImageCapture'
+
+describe('insightCardCaptureTarget', () => {
+ const insight = { short_id: 'abc123' as InsightShortId, name: 'Weekly signups', derived_name: null }
+
+ function renderCards(keys: string[]): void {
+ document.body.innerHTML = keys.map((key) => `<div ${INSIGHT_CARD_KEY_ATTR}="${key}">${key}</div>`).join('')
+ }
+
+ it('finds the tile it was built for, not the first card on the page', () => {
+ renderCards(['tile-1', 'tile-2'])
+
+ const target = insightCardCaptureTarget(insight, { id: 2 })
+
+ expect(document.querySelector(target.selector)).toHaveTextContent('tile-2')
+ })
+
+ it('falls back to the insight when the card is not a dashboard tile', () => {
+ renderCards(['insight-abc123'])
+
+ const target = insightCardCaptureTarget(insight)
+
+ expect(document.querySelector(target.selector)).toHaveTextContent('insight-abc123')
+ })
+
+ it('keys the screenshot editor per dashboard, so two dashboards on one page do not share one', () => {
+ expect(insightCardCaptureTarget(insight, { id: 2 }, 7).screenshotKey).not.toEqual(
+ insightCardCaptureTarget(insight, { id: 3 }, 8).screenshotKey
+ )
+ })
+
+ it('leaves the card chrome out of the capture', () => {
+ document.body.innerHTML =
+ '<div class="CardMeta__controls">⋯</div><div class="handle top"></div><div class="chart">chart</div>'
+ const { excludeSelector } = insightCardCaptureTarget(insight)
+
+ expect(document.querySelector('.CardMeta__controls')!.matches(excludeSelector!)).toBe(true)
+ expect(document.querySelector('.handle')!.matches(excludeSelector!)).toBe(true)
+ expect(document.querySelector('.chart')!.matches(excludeSelector!)).toBe(false)
+ })
+
+ it('names the file after the insight', () => {
+ expect(insightCardCaptureTarget(insight).name).toBe('Weekly signups')
+ expect(insightCardCaptureTarget({ ...insight, name: '', derived_name: 'Pageview count' }).name).toBe(
+ 'Pageview count'
+ )
+ })
+})
diff --git a/frontend/src/lib/components/Cards/InsightCard/insightCardImageCapture.ts b/frontend/src/lib/components/Cards/InsightCard/insightCardImageCapture.ts
new file mode 100644
index 000000000000..8dddbd1b0764
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/insightCardImageCapture.ts
@@ -0,0 +1,48 @@
+import { CaptureImageTarget } from 'lib/components/Scenes/InsightOrDashboard/captureImageLogic'
+
+import { DashboardTile, QueryBasedInsightModel } from '~/types'
+
+/**
+ * Marks each card with a key of its own. A dashboard renders many cards, so a capture that looked for a
+ * card by class or by `data-attr` would always take the first one on the page.
+ */
+export const INSIGHT_CARD_KEY_ATTR = 'data-insight-card-key'
+
+/**
+ * Keys the screenshot editor instance that a dashboard mounts for its tiles. One page can hold several
+ * dashboards — a notebook with dashboard widgets, a feature flag's dashboard — and editors sharing a key
+ * share their open state, so the key is per dashboard.
+ */
+export function dashboardTileScreenshotKey(dashboardId?: number | null): string {
+ return `dashboard-tile-${dashboardId ?? 'standalone'}`
+}
+
+/** The card's own chrome: the controls in the corner, the resize handles, and the grid's own handles. */
+const CARD_CHROME_SELECTOR = '.CardMeta__controls, .handle, .react-resizable-handle'
+
+export function insightCardKey(
+ insight: Pick<QueryBasedInsightModel, 'short_id'>,
+ tile?: Pick<DashboardTile<QueryBasedInsightModel>, 'id'>
+): string {
+ // The same insight can sit on a dashboard more than once, so the tile identifies the card when there is one.
+ return tile?.id != null ? `tile-${tile.id}` : `insight-${insight.short_id}`
+}
+
+/**
+ * Captures the whole card, not only the chart inside it: the heading comes with the image, which is what
+ * makes a pasted tile readable on its own. A compact tile shows its date range only when it overrides the
+ * dashboard's, so the dashboard's own range stays outside the picture. The card's chrome is left out — the
+ * "⋯" menu sits in the corner at all times, and a picture of a menu helps nobody.
+ */
+export function insightCardCaptureTarget(
+ insight: Pick<QueryBasedInsightModel, 'short_id' | 'name' | 'derived_name'>,
+ tile?: Pick<DashboardTile<QueryBasedInsightModel>, 'id'>,
+ dashboardId?: number | null
+): CaptureImageTarget {
+ return {
+ selector: `[${INSIGHT_CARD_KEY_ATTR}="${insightCardKey(insight, tile)}"]`,
+ excludeSelector: CARD_CHROME_SELECTOR,
+ screenshotKey: dashboardTileScreenshotKey(dashboardId),
+ name: insight.name || insight.derived_name || undefined,
+ }
+}
diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsx
index f53b2d86d67a..ff4b8a4c25d5 100644
--- a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsx
+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneCopyImageButton.test.tsx
@@ -16,12 +16,12 @@ jest.mock('html-to-image', () => ({
const TARGET = { selector: '[data-attr="insights-graph"]', screenshotKey: 'test' }
-function renderButton(): void {
+function renderButton({ withEditor = true }: { withEditor?: boolean } = {}): void {
render(
<>
<div data-attr="insights-graph">chart</div>
<SceneCopyImageButton target={TARGET} dataAttrKey="insight" />
- <ScreenShotEditor screenshotKey={TARGET.screenshotKey} />
+ {withEditor && <ScreenShotEditor screenshotKey={TARGET.screenshotKey} />}
<ToastContainer />
</>
)
@@ -56,6 +56,15 @@ describe('SceneCopyImageButton', () => {
expect(await screen.findByText('Edit Screenshot')).toBeInTheDocument()
})
+ it('offers no editor button on a surface that mounts no editor', async () => {
+ renderButton({ withEditor: false })
+
+ await userEvent.click(screen.getByText('Copy as PNG'))
+
+ expect(await screen.findByText('Image copied to clipboard')).toBeInTheDocument()
+ expect(screen.queryByText('Edit image')).not.toBeInTheDocument()
+ })
+
it('points at Export when the clipboard write fails, and stays clickable', async () => {
write.mockRejectedValueOnce(new Error('denied'))
renderButton()
diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.ts b/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.ts
index 8127d526dbc2..31fd5929d84a 100644
--- a/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.ts
+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/captureImageLogic.ts
@@ -11,6 +11,8 @@ 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. */
@@ -50,7 +52,12 @@ function toFile(target: CaptureImageTarget, blob: Blob): File {
return new File([blob], `${name || 'export'}.png`, { type: 'image/png' })
}
-function editImageButton(target: CaptureImageTarget, blob: Blob): ToastButton {
+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),
@@ -93,7 +100,7 @@ export const captureImageLogic = kea<captureImageLogicType>([
actions.setIsCapturing(true)
let result: Awaited<ReturnType<typeof copyElementImageToClipboard>>
try {
- result = await copyElementImageToClipboard(element)
+ result = await copyElementImageToClipboard(element, target.excludeSelector)
} finally {
actions.setIsCapturing(false)
}
@@ -119,7 +126,7 @@ export const captureImageLogic = kea<captureImageLogicType>([
actions.setIsCapturing(true)
try {
- const blob = await captureElementAsPng(element)
+ 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 })
diff --git a/frontend/src/lib/utils/copyImageToClipboard.test.ts b/frontend/src/lib/utils/copyImageToClipboard.test.ts
new file mode 100644
index 000000000000..46d0ee70d7e4
--- /dev/null
+++ b/frontend/src/lib/utils/copyImageToClipboard.test.ts
@@ -0,0 +1,34 @@
+import { toBlob } from 'html-to-image'
+
+import { captureElementAsPng } from './copyImageToClipboard'
+
+jest.mock('html-to-image', () => ({
+ toBlob: jest.fn(() => Promise.resolve(new Blob(['png'], { type: 'image/png' }))),
+}))
+
+describe('captureElementAsPng', () => {
+ async function filterFor(excludeSelector?: string): Promise<((node: Node) => boolean) | undefined> {
+ await captureElementAsPng(document.createElement('div'), excludeSelector)
+ return (toBlob as jest.Mock).mock.calls[0][1].filter
+ }
+
+ it('keeps everything when nothing is excluded', async () => {
+ expect(await filterFor()).toBeUndefined()
+ })
+
+ it('draws the element at the origin, so a grid tile is not translated out of its own image', async () => {
+ await captureElementAsPng(document.createElement('div'))
+ const { style } = (toBlob as jest.Mock).mock.calls[0][1]
+
+ expect(style).toEqual({ transform: 'none', position: 'relative', inset: 'auto', margin: '0' })
+ })
+
+ it('drops the excluded elements and keeps the rest', async () => {
+ document.body.innerHTML = '<div class="CardMeta__controls">⋯</div><div class="chart">chart</div>'
+ const filter = await filterFor('.CardMeta__controls')
+
+ expect(filter!(document.querySelector('.CardMeta__controls')!)).toBe(false)
+ expect(filter!(document.querySelector('.chart')!)).toBe(true)
+ expect(filter!(document.createTextNode('a label'))).toBe(true)
+ })
+})
diff --git a/frontend/src/lib/utils/copyImageToClipboard.ts b/frontend/src/lib/utils/copyImageToClipboard.ts
index bc39a258f3b9..495fd7dd43a8 100644
--- a/frontend/src/lib/utils/copyImageToClipboard.ts
+++ b/frontend/src/lib/utils/copyImageToClipboard.ts
@@ -16,8 +16,14 @@ export function canCopyImageToClipboard(): boolean {
return typeof ClipboardItem !== 'undefined' && !!navigator.clipboard?.write
}
-export async function captureElementAsPng(element: HTMLElement): Promise<Blob> {
+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,
@@ -27,7 +33,10 @@ export async function captureElementAsPng(element: HTMLElement): Promise<Blob> {
})
}
-export async function copyElementImageToClipboard(element: HTMLElement): Promise<CopyImageResult> {
+export async function copyElementImageToClipboard(
+ element: HTMLElement,
+ excludeSelector?: string
+): Promise<CopyImageResult> {
if (!canCopyImageToClipboard()) {
return { outcome: 'unsupported', blob: null }
}
@@ -35,7 +44,7 @@ export async function copyElementImageToClipboard(element: HTMLElement): Promise
// 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)
+ const capture = captureElementAsPng(element, excludeSelector)
capture.catch(() => {})
try {
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index e4b1b2b6054f..8cb87533a192 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -3,7 +3,9 @@ import './Dashboard.scss'
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { AccessDenied } from 'lib/components/AccessDenied'
+import { dashboardTileScreenshotKey } from 'lib/components/Cards/InsightCard/insightCardImageCapture'
import { NotFound } from 'lib/components/NotFound'
+import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor'
import { useFileSystemLogView } from 'lib/hooks/useFileSystemLogView'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { Link } from 'lib/lemon-ui/Link'
@@ -161,6 +163,10 @@ function DashboardScene({
<DashboardSubscribeNudgeTrigger dashboardId={dashboard.id} />
)}
{canEditDashboard && addInsightToDashboardModalVisible && <AddInsightToDashboardModal />}
+ {/* Lets a tile copied as a PNG be annotated before it is shared. Export placement renders headlessly. */}
+ {placement !== DashboardPlacement.Export && (
+ <ScreenShotEditor screenshotKey={dashboardTileScreenshotKey(dashboard?.id)} />
+ )}
<DashboardPublicAccessBanner dashboard={dashboard} placement={placement} />
{dashboardFailedToLoad ? (