: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): add copy as CSV to the dashboard insight card menu (#80852)
coryslater31bd421a0e41
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex 539c38fa24e0..7a5c572e722e 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -1,6 +1,6 @@import clsx from 'clsx'import { useActions, useValues } from 'kea'-import React, { useCallback, useEffect, useRef, useState } from 'react'+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { IconClock, IconInfo, IconPulse, IconThumbsDown, IconThumbsUp, IconWarning } from '@posthog/icons'import { lemonToast } from '@posthog/lemon-ui'@@ -48,9 +48,15 @@ import { urls } from 'scenes/urls'import { insightsModel } from '~/models/insightsModel'import { queryScanHasActionableFinding } from '~/queries/nodes/DataNode/queryScan'import { QueryScanTileTooltip } from '~/queries/nodes/DataNode/QueryScanTileTooltip'+import { copyTableData, getInsightExportAdapter } from '~/queries/nodes/InsightViz/exportAdapters'import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'import { Node, ProductKey } from '~/queries/schema/schema-general'-import { isDataVisualizationNode, isDataVisualizationNodeWithHogQLQuery } from '~/queries/utils'+import {+ isDataVisualizationNode,+ isDataVisualizationNodeWithHogQLQuery,+ isInsightVizNode,+ isTrendsQuery,+} from '~/queries/utils'import {AccessControlLevel,AccessControlResourceType,@@ -168,8 +174,15 @@ export function InsightMeta({}const { insightFeedback } = useValues(insightLogic(insightLogicProps))const { setInsightFeedback } = useActions(insightLogic(insightLogicProps))- const { exportContext, insightData, query, savingDisplayOptions, savingSqlVisualization, sqlVisualizationVersion } =- useValues(insightDataLogic(insightLogicProps))+ const {+ exportContext,+ insightData,+ insightDataRaw,+ query,+ savingDisplayOptions,+ savingSqlVisualization,+ sqlVisualizationVersion,+ } = useValues(insightDataLogic(insightLogicProps))const { persistSqlVisualization } = useActions(insightDataLogic(insightLogicProps))const [isManageAlertsModalOpen, setIsManageAlertsModalOpen] = useState(false)const { loadAlerts: loadDeferredInsightAlerts } = useActions(@@ -191,7 +204,7 @@ export function InsightMeta({const { copyImage } = useActions(captureImageLogic)const { isCapturing: isCapturingImage } = useValues(captureImageLogic)const { updateInsightDirect } = useActions(insightsModel)- const { reportDashboardInsightMetaUpdated } = useActions(eventUsageLogic)+ const { reportDashboardInsightMetaUpdated, reportInsightResultsCopiedToClipboard } = useActions(eventUsageLogic)const { featureFlags } = useValues(featureFlagLogic)const showCompactTile =@@ -260,6 +273,9 @@ export function InsightMeta({})const canCreateAnomalyAlertForInsight = areAnomalyAlertsSupportedForInsight(query)+ const showCopyTableData = isInsightVizNode(query) && isTrendsQuery(query.source)+ const copyTableAdapter = useMemo(() => getInsightExportAdapter(insightDataRaw, query), [insightDataRaw, query])+const showDisplayOptionsMenu = isUsedAsDashboardTile && canEditInsight && !!persistDisplayOptions// Hoist the hooks out of the More overlay so kea logics they mount don't do so lazily inside a// portal, which cascades into closing the dropdown before the user can interact with it.@@ -671,6 +687,33 @@ export function InsightMeta({export_context: exportContext,},]}+ copyToClipboardItems={+ showCopyTableData+ ? [+ {+ title: 'CSV',+ onClick: () => {+ if (!copyTableAdapter) {+ return+ }+ copyTableData(+ copyTableAdapter.toTableData(),+ ExporterFormat.CSV+ )+ reportInsightResultsCopiedToClipboard(+ 'csv',+ insight.id ?? null,+ dashboardId ?? null+ )+ },+ disabledReason: copyTableAdapter+ ? undefined+ : 'No data to copy yet',+ 'data-attr': 'insight-card-copy-as-csv',+ },+ ]+ : undefined+ }/></>) : null}diff --git a/frontend/src/lib/components/ExportButton/ExportButton.tsx b/frontend/src/lib/components/ExportButton/ExportButton.tsxindex c438502b49fa..676cc469018d 100644--- a/frontend/src/lib/components/ExportButton/ExportButton.tsx+++ b/frontend/src/lib/components/ExportButton/ExportButton.tsx@@ -18,17 +18,26 @@ export interface ExportButtonItem {insight?: number}+/** A client-side copy action rendered in a "Copy to clipboard" section below the export formats. */+export interface ExportButtonCopyToClipboardItem {+ title: string+ onClick: () => void+ disabledReason?: string+ 'data-attr'?: string+}+export interface ExportButtonProps extends Pick<LemonButtonProps,'disabledReason' | 'icon' | 'sideIcon' | 'id' | 'type' | 'fullWidth'> {items: ExportButtonItem[]+ copyToClipboardItems?: ExportButtonCopyToClipboardItem[]buttonCopy?: stringsize?: LemonButtonProps['size']}export const ExportButton: React.FunctionComponent<ExportButtonProps & React.RefAttributes<HTMLButtonElement>> =- forwardRef(function ExportButton({ items, buttonCopy, ...buttonProps }, ref): JSX.Element {+ forwardRef(function ExportButton({ items, copyToClipboardItems, buttonCopy, ...buttonProps }, ref): JSX.Element {useMountedLogic(exportsLogic)const { actions } = exportsLogic@@ -95,6 +104,23 @@ export const ExportButton: React.FunctionComponent<ExportButtonProps & React.Ref</LemonButton>)})}+ {copyToClipboardItems && copyToClipboardItems.length > 0 ? (+ <>+ <h5 className="mt-2">Copy to clipboard</h5>+ <LemonDivider />+ {copyToClipboardItems.map((item, i) => (+ <LemonButton+ key={i}+ fullWidth+ onClick={item.onClick}+ disabledReason={item.disabledReason}+ data-attr={item['data-attr']}+ >+ {item.title}+ </LemonButton>+ ))}+ </>+ ) : null}</>),}}diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 5fc84580d57c..c47c0adc8e84 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -1975,6 +1975,15 @@ export interface eventUsageLogicActions {insightShortId: InsightShortIdloadingMilliseconds: number}+ reportInsightResultsCopiedToClipboard: (+ format: string,+ insightId: number | null,+ dashboardId: number | null+ ) => {+ dashboardId: number | null+ format: string+ insightId: number | null+ }reportInsightSaved: (insight: Partial<QueryBasedInsightModel> | null,query: Node | null,@@ -2921,6 +2930,11 @@ export const eventUsageLogic = kea<eventUsageLogicType>([toDashboardId: number,tileType: DashboardWidgetType) => ({ fromDashboardId, toDashboardId, tileType }),+ reportInsightResultsCopiedToClipboard: (+ format: string,+ insightId: number | null,+ dashboardId: number | null+ ) => ({ format, insightId, dashboardId }),reportSavedInsightTabChanged: (tab: string) => ({ tab }),reportSavedInsightFilterUsed: (filterKeys: string[]) => ({ filterKeys }),reportSavedInsightNewInsightClicked: (insightType: string, presetKey?: string) => ({@@ -4034,6 +4048,13 @@ export const eventUsageLogic = kea<eventUsageLogicType>([tile_type: tileType,})},+ reportInsightResultsCopiedToClipboard: async ({ format, insightId, dashboardId }) => {+ posthog.capture('insight results copied to clipboard', {+ format,+ insight_id: insightId,+ dashboard_id: dashboardId,+ })+ },reportInsightsTableCalcToggled: async (payload) => {posthog.capture('insights table calc toggled', payload)},diff --git a/frontend/src/queries/nodes/InsightViz/exportAdapters.test.ts b/frontend/src/queries/nodes/InsightViz/exportAdapters.test.tsnew file mode 100644index 000000000000..a0029bd28df6--- /dev/null+++ b/frontend/src/queries/nodes/InsightViz/exportAdapters.test.ts@@ -0,0 +1,522 @@+import { EventsHeatMapDataResult, InsightVizNode, NodeKind, TrendsQueryResponse } from '~/queries/schema/schema-general'++import {+ CalendarHeatmapAdapter,+ TrendsAdapter,+ WorldMapAdapter,+ csvFromTableData,+ getInsightExportAdapter,+} from './exportAdapters'++describe('insight export adapters', () => {+ const trendsQuery: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [],+ },+ }++ describe('csvFromTableData', () => {+ it.each(['=', '+', '-', '@'])(+ 'neutralizes a leading "%s" so spreadsheets do not evaluate the cell as a formula',+ (prefix) => {+ const csv = csvFromTableData([['header'], [`${prefix}cmd(1)`]])+ expect(csv).toContain(`'${prefix}cmd(1)`)+ expect(csv).not.toContain(`\n${prefix}cmd(1)`)+ }+ )+ })++ describe('getInsightExportAdapter', () => {+ it('normalizes cached insight models that carry the series under legacy `result`', () => {+ const cachedInsight = {+ result: [{ label: 'Pageview', data: [10, 15], labels: ['2024-01-01', '2024-01-02'] }],+ }++ const adapter = getInsightExportAdapter(cachedInsight, trendsQuery)++ expect(adapter?.toTableData()).toEqual([+ ['Date', 'Pageview'],+ ['2024-01-01', '10'],+ ['2024-01-02', '15'],+ ])+ })++ it('returns null for insight kinds without an adapter', () => {+ const funnelsQuery: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.FunnelsQuery,+ series: [],+ },+ }++ expect(getInsightExportAdapter({ results: [{ label: 'Step 1' }] }, funnelsQuery)).toBeNull()+ })+ })++ describe('CalendarHeatmapAdapter', () => {+ it('converts calendar heatmap data to table format', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ calendar_heatmap_data: {+ data: [+ { row: 0, column: 0, value: 10 },+ { row: 0, column: 1, value: 15 },+ { row: 1, column: 0, value: 20 },+ { row: 1, column: 1, value: 25 },+ ],+ rowAggregations: [+ { row: 0, value: 25 },+ { row: 1, value: 45 },+ ],+ columnAggregations: [+ { column: 0, value: 30 },+ { column: 1, value: 40 },+ ],+ allAggregations: 70,+ },+ },+ ],+ }++ const adapter = new CalendarHeatmapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toHaveLength(9) // 1 header + 7 data rows + 1 aggregation row+ expect(result[0]).toEqual(['', ...Array.from({ length: 24 }, (_, i) => String(i)), 'All'])+ expect(result[1][0]).toBe('Sun')+ expect(result[1][1]).toBe('10')+ expect(result[1][2]).toBe('15')+ expect(result[1][25]).toBe('25')+ expect(result[2][0]).toBe('Mon')+ expect(result[2][1]).toBe('20')+ expect(result[2][2]).toBe('25')+ expect(result[2][25]).toBe('45')+ expect(result[8][1]).toBe('30')+ expect(result[8][2]).toBe('40')+ expect(result[8][25]).toBe('70')+ })++ it('handles sparse data with missing cells', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ calendar_heatmap_data: {+ data: [{ row: 0, column: 1, value: 15 }],+ rowAggregations: [{ row: 0, value: 15 }],+ columnAggregations: [{ column: 1, value: 15 }],+ allAggregations: 15,+ },+ },+ ],+ }++ const adapter = new CalendarHeatmapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toHaveLength(9) // 1 header + 7 data rows + 1 aggregation row+ expect(result[0]).toHaveLength(26) // empty + 24 hours + All+ expect(result[1][1]).toBe('0') // Sun, hour 0+ expect(result[1][2]).toBe('15') // Sun, hour 1+ expect(result[1][25]).toBe('15') // Sun, row total+ })++ it('handles empty heatmap data', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ calendar_heatmap_data: {+ data: [],+ rowAggregations: [],+ columnAggregations: [],+ allAggregations: 0,+ },+ },+ ],+ }++ const adapter = new CalendarHeatmapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toHaveLength(9) // 1 header + 7 data rows + 1 aggregation row+ expect(result[0]).toHaveLength(26) // empty + 24 hours + All+ expect(result[8][25]).toBe('0') // All row, All column+ })++ it('returns empty array when heatmap data is missing', () => {+ const response: TrendsQueryResponse = {+ results: [{}],+ }++ const adapter = new CalendarHeatmapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([])+ })++ it('handles full day x hour matrix (7x24)', () => {+ const data: EventsHeatMapDataResult[] = []+ for (let row = 0; row < 7; row++) {+ for (let col = 0; col < 24; col++) {+ data.push({ row, column: col, value: row * 24 + col })+ }+ }++ const response: TrendsQueryResponse = {+ results: [+ {+ calendar_heatmap_data: {+ data,+ rowAggregations: Array.from({ length: 7 }, (_, i) => ({+ row: i,+ value: (i * 24 * (i * 24 + 23)) / 2,+ })),+ columnAggregations: Array.from({ length: 24 }, (_, i) => ({ column: i, value: i * 7 })),+ allAggregations: 19656,+ },+ },+ ],+ }++ const adapter = new CalendarHeatmapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result.length).toBe(9) // 1 header + 7 data rows + 1 aggregation row+ expect(result[0].length).toBe(26) // empty + 24 hours + All+ expect(result[0][0]).toBe('')+ expect(result[0][1]).toBe('0')+ expect(result[0][24]).toBe('23')+ expect(result[0][25]).toBe('All')+ })++ it('correctly converts ClickHouse day indices (1=Mon, 7=Sun) to standard format (0=Sun, 6=Sat)', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ calendar_heatmap_data: {+ data: [+ { row: 7, column: 0, value: 100 }, // Sunday+ { row: 7, column: 1, value: 110 },+ { row: 1, column: 0, value: 200 }, // Monday+ { row: 1, column: 1, value: 210 },+ { row: 6, column: 0, value: 600 }, // Saturday+ { row: 6, column: 1, value: 610 },+ ],+ rowAggregations: [+ { row: 7, value: 210 },+ { row: 1, value: 410 },+ { row: 6, value: 1210 },+ ],+ columnAggregations: [+ { column: 0, value: 900 },+ { column: 1, value: 930 },+ ],+ allAggregations: 1830,+ },+ },+ ],+ }++ const adapter = new CalendarHeatmapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result[1][0]).toBe('Sun')+ expect(result[1][1]).toBe('100')+ expect(result[1][2]).toBe('110')+ expect(result[1][25]).toBe('210')++ expect(result[2][0]).toBe('Mon')+ expect(result[2][1]).toBe('200')+ expect(result[2][2]).toBe('210')+ expect(result[2][25]).toBe('410')++ expect(result[7][0]).toBe('Sat')+ expect(result[7][1]).toBe('600')+ expect(result[7][2]).toBe('610')+ expect(result[7][25]).toBe('1210')++ expect(result[8][1]).toBe('900')+ expect(result[8][2]).toBe('930')+ expect(result[8][25]).toBe('1830')+ })+ })++ describe('TrendsAdapter', () => {+ it('converts trends data to table format', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Pageview',+ data: [10, 15, 20],+ labels: ['2024-01-01', '2024-01-02', '2024-01-03'],+ },+ {+ label: 'Button Click',+ data: [5, 8, 12],+ labels: ['2024-01-01', '2024-01-02', '2024-01-03'],+ },+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([+ ['Date', 'Pageview', 'Button Click'],+ ['2024-01-01', '10', '5'],+ ['2024-01-02', '15', '8'],+ ['2024-01-03', '20', '12'],+ ])+ })++ it('uses custom_name when available', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'pageview',+ action: { custom_name: 'Page Views' } as any,+ data: [10, 15],+ labels: ['2024-01-01', '2024-01-02'],+ },+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result[0]).toEqual(['Date', 'Page Views'])+ })++ it('includes compare_label when present', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Pageview',+ compare_label: 'current',+ data: [10, 15],+ labels: ['2024-01-01', '2024-01-02'],+ },+ {+ label: 'Pageview',+ compare_label: 'previous',+ data: [8, 12],+ labels: ['2024-01-01', '2024-01-02'],+ },+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result[0]).toEqual(['Date', 'Pageview (current)', 'Pageview (previous)'])+ })++ it('uses days as fallback for date labels', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Event',+ data: [10, 15],+ days: ['2024-01-01', '2024-01-02'],+ },+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result[1]).toEqual(['2024-01-01', '10'])+ expect(result[2]).toEqual(['2024-01-02', '15'])+ })++ it('returns empty array for empty results', () => {+ const response: TrendsQueryResponse = {+ results: [],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([])+ })++ it('returns empty array when there are no date labels and no aggregated values', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Event',+ data: [10, 15],+ },+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([])+ })++ it('falls back to one row per series for value-aggregated displays', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Chrome',+ aggregated_value: 100,+ data: [],+ days: [],+ labels: [],+ } as any,+ {+ label: 'Safari',+ aggregated_value: 50.5,+ data: [],+ days: [],+ labels: [],+ } as any,+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([+ ['Series', 'Total value'],+ ['Chrome', '100'],+ ['Safari', '50.5'],+ ])+ })++ it('handles null values in data', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Event',+ data: [10, null, 20] as any,+ labels: ['2024-01-01', '2024-01-02', '2024-01-03'],+ },+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([+ ['Date', 'Event'],+ ['2024-01-01', '10'],+ ['2024-01-02', ''],+ ['2024-01-03', '20'],+ ])+ })++ it('uses breakdown_value when available instead of label', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'Unique visitors',+ breakdown_value: 'Organic Search',+ data: [335, 348],+ labels: ['2024-01-01', '2024-01-02'],+ } as any,+ {+ label: 'Unique visitors',+ breakdown_value: 'Direct',+ data: [0, 0],+ labels: ['2024-01-01', '2024-01-02'],+ } as any,+ ],+ }++ const adapter = new TrendsAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result[0]).toEqual(['Date', 'Organic Search', 'Direct'])+ expect(result[1]).toEqual(['2024-01-01', '335', '0'])+ expect(result[2]).toEqual(['2024-01-02', '348', '0'])+ })+ })++ describe('WorldMapAdapter', () => {+ it('converts world map data to table format', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'US',+ aggregated_value: 45319,+ data: [],+ days: [],+ } as any,+ {+ label: 'GB',+ aggregated_value: 12345,+ data: [],+ days: [],+ } as any,+ ],+ }++ const adapter = new WorldMapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([+ ['Country', 'Visitors'],+ ['US', '45319'],+ ['GB', '12345'],+ ])+ })++ it('handles empty results', () => {+ const response: TrendsQueryResponse = {+ results: [],+ }++ const adapter = new WorldMapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([])+ })++ it('handles missing aggregated_value with fallback to count', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ label: 'US',+ count: 100,+ data: [],+ days: [],+ } as any,+ ],+ }++ const adapter = new WorldMapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([+ ['Country', 'Visitors'],+ ['US', '100'],+ ])+ })++ it('handles missing label', () => {+ const response: TrendsQueryResponse = {+ results: [+ {+ aggregated_value: 50,+ data: [],+ days: [],+ } as any,+ ],+ }++ const adapter = new WorldMapAdapter(response, trendsQuery)+ const result = adapter.toTableData()++ expect(result).toEqual([+ ['Country', 'Visitors'],+ ['', '50'],+ ])+ })+ })+})diff --git a/frontend/src/queries/nodes/InsightViz/exportAdapters.ts b/frontend/src/queries/nodes/InsightViz/exportAdapters.tsnew file mode 100644index 000000000000..ddfffc3af004--- /dev/null+++ b/frontend/src/queries/nodes/InsightViz/exportAdapters.ts@@ -0,0 +1,293 @@+import Papa from 'papaparse'++import { lemonToast } from '@posthog/lemon-ui'++import { copyToClipboard } from 'lib/utils/copyToClipboard'++import {+ EventsHeatMapColumnAggregationResult,+ EventsHeatMapDataResult,+ EventsHeatMapRowAggregationResult,+ InsightVizNode,+ Node,+ NodeKind,+ QuerySchema,+ TrendsQuery,+ TrendsQueryResponse,+} from '~/queries/schema/schema-general'+import { isTrendsQuery } from '~/queries/utils'+import { ChartDisplayType, ExporterFormat } from '~/types'++export interface ExportAdapter {+ toTableData(): string[][]+ canHandle(): boolean+}++export function csvFromTableData(tableData: string[][]): string {+ return Papa.unparse(tableData, { escapeFormulae: true })+}++export function copyTableData(tableData: string[][], format: ExporterFormat): void {+ if (tableData.length === 0) {+ lemonToast.warning('No data to copy yet')+ return+ }+ try {+ switch (format) {+ case ExporterFormat.CSV: {+ const csv = csvFromTableData(tableData)+ void copyToClipboard(csv, 'table')+ break+ }+ case ExporterFormat.JSON: {+ const [headers, ...rows] = tableData+ const jsonData = rows.map((row) =>+ headers.reduce(+ (acc, header, index) => {+ acc[header] = row[index]+ return acc+ },+ {} as Record<string, any>+ )+ )+ void copyToClipboard(JSON.stringify(jsonData, null, 4), 'table')+ break+ }+ case ExporterFormat.XLSX: {+ const tsv = Papa.unparse(tableData, { delimiter: '\t', escapeFormulae: true })+ void copyToClipboard(tsv, 'table')+ break+ }+ }+ } catch {+ lemonToast.error('Copy failed!')+ }+}++/**+ * Returns an adapter that converts a loaded insight response into tabular data, or null when the+ * insight kind isn't supported or no data is loaded yet.+ */+export function getInsightExportAdapter(insightDataRaw: unknown, query: Node | null | undefined): ExportAdapter | null {+ if (!insightDataRaw || !query) {+ return null+ }+ const raw = insightDataRaw as Record<string, any>+ // Cached insight models (dashboard tiles that haven't refreshed this session) carry the series+ // under the legacy `result` key, while fresh query responses use `results`.+ const response = (+ raw.results == null && Array.isArray(raw.result) ? { ...raw, results: raw.result } : raw+ ) as TrendsQueryResponse+ const adapters: ExportAdapter[] = [+ new CalendarHeatmapAdapter(response, query as QuerySchema),+ new WorldMapAdapter(response, query as QuerySchema),+ new TrendsAdapter(response, query as QuerySchema),+ ]+ return adapters.find((a) => a.canHandle()) ?? null+}++function convertClickHouseDayToStandard(clickHouseDay: number): number {+ // ClickHouse toDayOfWeek: 1=Mon, 2=Tue, ..., 7=Sun+ // Standard array indices: 0=Sun, 1=Mon, ..., 6=Sat+ return clickHouseDay % 7+}++export class CalendarHeatmapAdapter implements ExportAdapter {+ constructor(+ private response: TrendsQueryResponse,+ private query?: QuerySchema+ ) {}++ private getCalendarHeatmapTableData(rowLabels: string[], columnLabels: string[]): string[][] {+ const firstResult = (this.response as any)?.results?.[0]+ const heatmapData = firstResult?.calendar_heatmap_data++ if (!heatmapData || !heatmapData.data) {+ return []+ }++ const data = heatmapData.data+ const rowAggregations = heatmapData.rowAggregations || []+ const columnAggregations = heatmapData.columnAggregations || []+ const allAggregations = heatmapData.allAggregations || 0++ const numRows = rowLabels.length+ const numCols = columnLabels.length++ const matrix: number[][] = Array(numRows)+ .fill(0)+ .map(() => Array(numCols).fill(0))+ data.forEach((item: EventsHeatMapDataResult) => {+ const standardDay = convertClickHouseDayToStandard(item.row)+ if (standardDay < numRows && item.column < numCols) {+ matrix[standardDay][item.column] = item.value+ }+ })++ const rowAggMap: Record<number, number> = {}+ rowAggregations.forEach((item: EventsHeatMapRowAggregationResult) => {+ const standardDay = convertClickHouseDayToStandard(item.row)+ rowAggMap[standardDay] = item.value+ })++ const colAggArray: number[] = Array(numCols).fill(0)+ columnAggregations.forEach((item: EventsHeatMapColumnAggregationResult) => {+ if (item.column < numCols) {+ colAggArray[item.column] = item.value+ }+ })++ const headers = ['', ...columnLabels, 'All']+ const dataRows = rowLabels.map((rowLabel, rowIndex) => {+ const rowValues = matrix[rowIndex].map(String)+ const rowTotal = rowAggMap[rowIndex] != null ? String(rowAggMap[rowIndex]) : ''+ return [rowLabel, ...rowValues, rowTotal]+ })++ const aggregationRow = ['All', ...colAggArray.map(String), String(allAggregations)]++ return [headers, ...dataRows, aggregationRow]+ }++ toTableData(): string[][] {+ const dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']+ const hourLabels = Array.from({ length: 24 }, (_, i) => String(i))+ return this.getCalendarHeatmapTableData(dayLabels, hourLabels)+ }++ canHandle(): boolean {+ if (!this.query || this.query.kind !== NodeKind.InsightVizNode) {+ return false+ }+ const source = (this.query as InsightVizNode).source+ if (!isTrendsQuery(source)) {+ return false+ }+ const isHeatmap = (source as TrendsQuery)?.trendsFilter?.display === ChartDisplayType.CalendarHeatmap+ if (!isHeatmap) {+ return false+ }++ const firstResult = (this.response as any)?.results?.[0]+ const heatmapData = firstResult?.calendar_heatmap_data+ return heatmapData && heatmapData.data && heatmapData.data.length > 0+ }+}++export class WorldMapAdapter implements ExportAdapter {+ constructor(+ private response: TrendsQueryResponse,+ private query?: QuerySchema+ ) {}++ private getWorldMapTableData(): string[][] {+ if (!this.response.results || this.response.results.length === 0) {+ return []+ }++ const headers = ['Country', 'Visitors']+ const dataRows = this.response.results.map((series) => {+ const countryCode = series.label ?? ''+ const visitors = (series as any).aggregated_value ?? series.count ?? 0+ return [countryCode, String(visitors)]+ })++ return [headers, ...dataRows]+ }++ toTableData(): string[][] {+ return this.getWorldMapTableData()+ }++ canHandle(): boolean {+ if (!this.query || this.query.kind !== NodeKind.InsightVizNode) {+ return false+ }+ const source = (this.query as InsightVizNode).source+ if (!isTrendsQuery(source)) {+ return false+ }++ const isWorldMap = (source as TrendsQuery)?.trendsFilter?.display === ChartDisplayType.WorldMap+ if (!isWorldMap) {+ return false+ }++ return this.response.results && this.response.results.length > 0+ }+}++export class TrendsAdapter implements ExportAdapter {+ constructor(+ private response: TrendsQueryResponse,+ private query?: QuerySchema+ ) {}++ private getSeriesLabel(series: Record<string, any>): string {+ // Use breakdown value if available, otherwise use action name or label+ const breakdownValue = series.breakdown_value+ const baseName = breakdownValue ?? series.action?.custom_name ?? series.label ?? 'Series'+ const compareLabel = series.compare_label+ return compareLabel ? `${baseName} (${compareLabel})` : String(baseName)+ }++ // Value-aggregated displays (bold number, pie, total value bar) return a single number per+ // series and no date axis, so the table is one row per series instead of one row per date.+ private getAggregateTableData(): string[][] {+ const rows = this.response.results+ .filter((series) => (series as any).aggregated_value != null || series.count != null)+ .map((series) => [this.getSeriesLabel(series), String((series as any).aggregated_value ?? series.count)])++ return rows.length > 0 ? [['Series', 'Total value'], ...rows] : []+ }++ private getTrendsTableData(): string[][] {+ if (!this.response.results || this.response.results.length === 0) {+ return []+ }++ // Get date labels from the first series (all series should have the same labels)+ const firstSeries = this.response.results[0]+ const dateLabels = (firstSeries.labels || firstSeries.days || []) as string[]++ if (dateLabels.length === 0) {+ return this.getAggregateTableData()+ }++ const seriesLabels = this.response.results.map((series) => this.getSeriesLabel(series))+ const headers = ['Date', ...seriesLabels]++ const dataRows = dateLabels.map((date, dateIndex) => {+ const values = this.response.results.map((series) => {+ const data = series.data as number[]+ const value = data[dateIndex]+ return value != null ? String(value) : ''+ })+ return [date, ...values]+ })++ return [headers, ...dataRows]+ }++ toTableData(): string[][] {+ return this.getTrendsTableData()+ }++ canHandle(): boolean {+ if (!this.query || this.query.kind !== NodeKind.InsightVizNode) {+ return false+ }+ const source = (this.query as InsightVizNode).source+ if (!isTrendsQuery(source)) {+ return false+ }++ // Exclude calendar heatmaps and world maps (handled by their own adapters)+ const display = (source as TrendsQuery)?.trendsFilter?.display+ if (display === ChartDisplayType.CalendarHeatmap || display === ChartDisplayType.WorldMap) {+ return false+ }++ return this.response.results && this.response.results.length > 0+ }+}diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsxindex 5ca82e8ea129..bca8d6f65584 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsx@@ -1,38 +1,8 @@-import {- DataTableNode,- EventsHeatMapDataResult,- InsightVizNode,- NodeKind,- TrendsQueryResponse,- WebStatsBreakdown,- WebStatsTableQueryResponse,-} from '~/queries/schema/schema-general'+import { DataTableNode, NodeKind, WebStatsBreakdown, WebStatsTableQueryResponse } from '~/queries/schema/schema-general'-import {- CalendarHeatmapAdapter,- TrendsAdapter,- WebAnalyticsTableAdapter,- WorldMapAdapter,- buildCsvFilenames,- csvFromTableData,-} from './webAnalyticsExportUtils'+import { WebAnalyticsTableAdapter, buildCsvFilenames } from './webAnalyticsExportUtils'describe('WebAnalyticsExport adapters', () => {- beforeEach(() => {- jest.clearAllMocks()- })-- describe('csvFromTableData', () => {- it.each(['=', '+', '-', '@'])(- 'neutralizes a leading "%s" so spreadsheets do not evaluate the cell as a formula',- (prefix) => {- const csv = csvFromTableData([['header'], [`${prefix}cmd(1)`]])- expect(csv).toContain(`'${prefix}cmd(1)`)- expect(csv).not.toContain(`\n${prefix}cmd(1)`)- }- )- })-describe('buildCsvFilenames', () => {it('slugifies titles and de-duplicates colliding stems so no zip entry is overwritten', () => {expect(buildCsvFilenames(['Top paths', 'Sources', 'Sources', 'Referring domains: Sources'])).toEqual([@@ -48,477 +18,6 @@ describe('WebAnalyticsExport adapters', () => {})})- describe('CalendarHeatmapAdapter', () => {- it('converts calendar heatmap data to table format', () => {- const response: TrendsQueryResponse = {- results: [- {- calendar_heatmap_data: {- data: [- { row: 0, column: 0, value: 10 },- { row: 0, column: 1, value: 15 },- { row: 1, column: 0, value: 20 },- { row: 1, column: 1, value: 25 },- ],- rowAggregations: [- { row: 0, value: 25 },- { row: 1, value: 45 },- ],- columnAggregations: [- { column: 0, value: 30 },- { column: 1, value: 40 },- ],- allAggregations: 70,- },- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new CalendarHeatmapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([- [- '',- '0',- '1',- '2',- '3',- '4',- '5',- '6',- '7',- '8',- '9',- '10',- '11',- '12',- '13',- '14',- '15',- '16',- '17',- '18',- '19',- '20',- '21',- '22',- '23',- 'All',- ],- [- 'Sun',- '10',- '15',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '25',- ],- [- 'Mon',- '20',- '25',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '45',- ],- [- 'Tue',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '',- ],- [- 'Wed',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '',- ],- [- 'Thu',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '',- ],- [- 'Fri',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '',- ],- [- 'Sat',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '',- ],- [- 'All',- '30',- '40',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '0',- '70',- ],- ])- })-- it('handles sparse data with missing cells', () => {- const response: TrendsQueryResponse = {- results: [- {- calendar_heatmap_data: {- data: [{ row: 0, column: 1, value: 15 }],- rowAggregations: [{ row: 0, value: 15 }],- columnAggregations: [{ column: 1, value: 15 }],- allAggregations: 15,- },- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new CalendarHeatmapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toHaveLength(9) // 1 header + 7 data rows + 1 aggregation row- expect(result[0]).toHaveLength(26) // empty + 24 hours + All- expect(result[1][1]).toBe('0') // Sun, hour 0- expect(result[1][2]).toBe('15') // Sun, hour 1- expect(result[1][25]).toBe('15') // Sun, row total- })-- it('handles empty heatmap data', () => {- const response: TrendsQueryResponse = {- results: [- {- calendar_heatmap_data: {- data: [],- rowAggregations: [],- columnAggregations: [],- allAggregations: 0,- },- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new CalendarHeatmapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toHaveLength(9) // 1 header + 7 data rows + 1 aggregation row- expect(result[0]).toHaveLength(26) // empty + 24 hours + All- expect(result[8][25]).toBe('0') // All row, All column- })-- it('returns empty array when heatmap data is missing', () => {- const response: TrendsQueryResponse = {- results: [{}],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new CalendarHeatmapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([])- })-- it('handles full day x hour matrix (7x24)', () => {- const data: EventsHeatMapDataResult[] = []- for (let row = 0; row < 7; row++) {- for (let col = 0; col < 24; col++) {- data.push({ row, column: col, value: row * 24 + col })- }- }-- const response: TrendsQueryResponse = {- results: [- {- calendar_heatmap_data: {- data,- rowAggregations: Array.from({ length: 7 }, (_, i) => ({- row: i,- value: (i * 24 * (i * 24 + 23)) / 2,- })),- columnAggregations: Array.from({ length: 24 }, (_, i) => ({ column: i, value: i * 7 })),- allAggregations: 19656,- },- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new CalendarHeatmapAdapter(response, query)- const result = adapter.toTableData()-- expect(result.length).toBe(9) // 1 header + 7 data rows + 1 aggregation row- expect(result[0].length).toBe(26) // empty + 24 hours + All- expect(result[0][0]).toBe('')- expect(result[0][1]).toBe('0')- expect(result[0][24]).toBe('23')- expect(result[0][25]).toBe('All')- })-- it('correctly converts ClickHouse day indices (1=Mon, 7=Sun) to standard format (0=Sun, 6=Sat)', () => {- const response: TrendsQueryResponse = {- results: [- {- calendar_heatmap_data: {- data: [- { row: 7, column: 0, value: 100 }, // Sunday- { row: 7, column: 1, value: 110 },- { row: 1, column: 0, value: 200 }, // Monday- { row: 1, column: 1, value: 210 },- { row: 6, column: 0, value: 600 }, // Saturday- { row: 6, column: 1, value: 610 },- ],- rowAggregations: [- { row: 7, value: 210 },- { row: 1, value: 410 },- { row: 6, value: 1210 },- ],- columnAggregations: [- { column: 0, value: 900 },- { column: 1, value: 930 },- ],- allAggregations: 1830,- },- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new CalendarHeatmapAdapter(response, query)- const result = adapter.toTableData()-- expect(result[1][0]).toBe('Sun')- expect(result[1][1]).toBe('100')- expect(result[1][2]).toBe('110')- expect(result[1][25]).toBe('210')-- expect(result[2][0]).toBe('Mon')- expect(result[2][1]).toBe('200')- expect(result[2][2]).toBe('210')- expect(result[2][25]).toBe('410')-- expect(result[7][0]).toBe('Sat')- expect(result[7][1]).toBe('600')- expect(result[7][2]).toBe('610')- expect(result[7][25]).toBe('1210')-- expect(result[8][1]).toBe('900')- expect(result[8][2]).toBe('930')- expect(result[8][25]).toBe('1830')- })- })-describe('WebAnalyticsTableAdapter', () => {it('converts web analytics table data without comparison', () => {const response: WebStatsTableQueryResponse = {@@ -622,353 +121,4 @@ describe('WebAnalyticsExport adapters', () => {])})})-- describe('TrendsAdapter', () => {- it('converts trends data to table format', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'Pageview',- data: [10, 15, 20],- labels: ['2024-01-01', '2024-01-02', '2024-01-03'],- },- {- label: 'Button Click',- data: [5, 8, 12],- labels: ['2024-01-01', '2024-01-02', '2024-01-03'],- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([- ['Date', 'Pageview', 'Button Click'],- ['2024-01-01', '10', '5'],- ['2024-01-02', '15', '8'],- ['2024-01-03', '20', '12'],- ])- })-- it('uses custom_name when available', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'pageview',- action: { custom_name: 'Page Views' } as any,- data: [10, 15],- labels: ['2024-01-01', '2024-01-02'],- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result[0]).toEqual(['Date', 'Page Views'])- })-- it('includes compare_label when present', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'Pageview',- compare_label: 'current',- data: [10, 15],- labels: ['2024-01-01', '2024-01-02'],- },- {- label: 'Pageview',- compare_label: 'previous',- data: [8, 12],- labels: ['2024-01-01', '2024-01-02'],- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result[0]).toEqual(['Date', 'Pageview (current)', 'Pageview (previous)'])- })-- it('uses days as fallback for date labels', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'Event',- data: [10, 15],- days: ['2024-01-01', '2024-01-02'],- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result[1]).toEqual(['2024-01-01', '10'])- expect(result[2]).toEqual(['2024-01-02', '15'])- })-- it('returns empty array for empty results', () => {- const response: TrendsQueryResponse = {- results: [],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([])- })-- it('returns empty array when no date labels', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'Event',- data: [10, 15],- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([])- })-- it('handles null values in data', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'Event',- data: [10, null, 20] as any,- labels: ['2024-01-01', '2024-01-02', '2024-01-03'],- },- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([- ['Date', 'Event'],- ['2024-01-01', '10'],- ['2024-01-02', ''],- ['2024-01-03', '20'],- ])- })-- it('uses breakdown_value when available instead of label', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'Unique visitors',- breakdown_value: 'Organic Search',- data: [335, 348],- labels: ['2024-01-01', '2024-01-02'],- } as any,- {- label: 'Unique visitors',- breakdown_value: 'Unknown',- data: [133, 113],- labels: ['2024-01-01', '2024-01-02'],- } as any,- {- label: 'Unique visitors',- breakdown_value: 'Organic Video',- data: [1, 2],- labels: ['2024-01-01', '2024-01-02'],- } as any,- {- label: 'Unique visitors',- breakdown_value: 'Direct',- data: [0, 0],- labels: ['2024-01-01', '2024-01-02'],- } as any,- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new TrendsAdapter(response, query)- const result = adapter.toTableData()-- expect(result[0]).toEqual(['Date', 'Organic Search', 'Unknown', 'Organic Video', 'Direct'])- expect(result[1]).toEqual(['2024-01-01', '335', '133', '1', '0'])- expect(result[2]).toEqual(['2024-01-02', '348', '113', '2', '0'])- })- })-- describe('WorldMapAdapter', () => {- it('converts world map data to table format', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'US',- aggregated_value: 45319,- data: [],- days: [],- } as any,- {- label: 'GB',- aggregated_value: 12345,- data: [],- days: [],- } as any,- {- label: 'CA',- aggregated_value: 8765,- data: [],- days: [],- } as any,- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new WorldMapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([- ['Country', 'Visitors'],- ['US', '45319'],- ['GB', '12345'],- ['CA', '8765'],- ])- })-- it('handles empty results', () => {- const response: TrendsQueryResponse = {- results: [],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new WorldMapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([])- })-- it('handles missing aggregated_value with fallback to count', () => {- const response: TrendsQueryResponse = {- results: [- {- label: 'US',- count: 100,- data: [],- days: [],- } as any,- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new WorldMapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([- ['Country', 'Visitors'],- ['US', '100'],- ])- })-- it('handles missing label', () => {- const response: TrendsQueryResponse = {- results: [- {- aggregated_value: 50,- data: [],- days: [],- } as any,- ],- }- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: [],- },- }-- const adapter = new WorldMapAdapter(response, query)- const result = adapter.toTableData()-- expect(result).toEqual([- ['Country', 'Visitors'],- ['', '50'],- ])- })- })})diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsExport.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsExport.tsxindex eb9ed7ab8c08..f27c173de0ec 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsExport.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsExport.tsx@@ -5,10 +5,10 @@ import { LemonButton, LemonMenu } from '@posthog/lemon-ui'import { shareNudgeLogic } from 'scenes/web-analytics/shareNudgeLogic'+import { copyTableData } from '~/queries/nodes/InsightViz/exportAdapters'import { QuerySchema } from '~/queries/schema/schema-general'import { ExporterFormat, InsightLogicProps } from '~/types'-import { exportTableData } from './webAnalyticsExportUtils'import { useWebTileExportAdapter } from './webTileHeaderHooks'interface WebAnalyticsExportProps {@@ -26,7 +26,7 @@ export function WebAnalyticsExport({ query, insightProps }: WebAnalyticsExportPrconst handleCopy = (format: ExporterFormat): void => {const tableData = adapter.toTableData()- exportTableData(tableData, format)+ copyTableData(tableData, format)exportTriggered()}diff --git a/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.ts b/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.tsindex cad9b0323e5a..0adce15c8293 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.ts+++ b/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.ts@@ -1,46 +1,30 @@import { strToU8, zipSync } from 'fflate'-import Papa from 'papaparse'import { lemonToast } from '@posthog/lemon-ui'-import { copyToClipboard } from 'lib/utils/copyToClipboard'import { downloadFile } from 'lib/utils/dom'import { slugify } from 'lib/utils/strings'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { ExportAdapter, csvFromTableData, getInsightExportAdapter } from '~/queries/nodes/InsightViz/exportAdapters'import {DataTableNode,- EventsHeatMapColumnAggregationResult,- EventsHeatMapDataResult,- EventsHeatMapRowAggregationResult,- InsightVizNode,NodeKind,QuerySchema,- TrendsQuery,- TrendsQueryResponse,WebExternalClicksTableQuery,WebGoalsQuery,WebStatsTableQuery,WebStatsTableQueryResponse,} from '~/queries/schema/schema-general'-import { isTrendsQuery, isWebExternalClicksQuery, isWebGoalsQuery, isWebStatsTableQuery } from '~/queries/utils'+import { isWebExternalClicksQuery, isWebGoalsQuery, isWebStatsTableQuery } from '~/queries/utils'import { TabsTileTab, TILE_LABELS, WebAnalyticsTile, getDisplayColumnName } from '~/scenes/web-analytics/common'-import { ChartDisplayType, ExporterFormat, InsightLogicProps } from '~/types'--export interface ExportAdapter {- toTableData(): string[][]- canHandle(): boolean-}+import { InsightLogicProps } from '~/types'export interface TileExportSection {title: stringtableData: string[][]}-export function csvFromTableData(tableData: string[][]): string {- return Papa.unparse(tableData, { escapeFormulae: true })-}-export function downloadTableDataAsCsv(tableData: string[][], filename: string): boolean {if (tableData.length === 0) {lemonToast.warning('No data to export yet')@@ -91,13 +75,11 @@ export function getExportAdapter(insightDataRaw: unknown, query: QuerySchema | uif (!insightDataRaw || !query) {return null}- const adapters: ExportAdapter[] = [- new CalendarHeatmapAdapter(insightDataRaw as TrendsQueryResponse, query),- new WorldMapAdapter(insightDataRaw as TrendsQueryResponse, query),- new WebAnalyticsTableAdapter(insightDataRaw as WebStatsTableQueryResponse, query),- new TrendsAdapter(insightDataRaw as TrendsQueryResponse, query),- ]- return adapters.find((a) => a.canHandle()) ?? null+ const webAdapter = new WebAnalyticsTableAdapter(insightDataRaw as WebStatsTableQueryResponse, query)+ if (webAdapter.canHandle()) {+ return webAdapter+ }+ return getInsightExportAdapter(insightDataRaw, query)}function tileToTableData(query: QuerySchema, insightProps: InsightLogicProps): string[][] | null {@@ -176,128 +158,7 @@ export function collectAllTilesTableData(tiles: WebAnalyticsTile[]): TileExportSreturn sections}-export function exportTableData(tableData: string[][], format: ExporterFormat): void {- try {- switch (format) {- case ExporterFormat.CSV: {- const csv = csvFromTableData(tableData)- void copyToClipboard(csv, 'table')- break- }- case ExporterFormat.JSON: {- const [headers, ...rows] = tableData- const jsonData = rows.map((row) =>- headers.reduce(- (acc, header, index) => {- acc[header] = row[index]- return acc- },- {} as Record<string, any>- )- )- void copyToClipboard(JSON.stringify(jsonData, null, 4), 'table')- break- }- case ExporterFormat.XLSX: {- const tsv = Papa.unparse(tableData, { delimiter: '\t', escapeFormulae: true })- void copyToClipboard(tsv, 'table')- break- }- }- } catch {- lemonToast.error('Copy failed!')- }-}--function convertClickHouseDayToStandard(clickHouseDay: number): number {- // ClickHouse toDayOfWeek: 1=Mon, 2=Tue, ..., 7=Sun- // Standard array indices: 0=Sun, 1=Mon, ..., 6=Sat- return clickHouseDay % 7-}--class CalendarHeatmapAdapter implements ExportAdapter {- constructor(- private response: TrendsQueryResponse,- private query?: QuerySchema- ) {}-- private getCalendarHeatmapTableData(rowLabels: string[], columnLabels: string[]): string[][] {- const firstResult = (this.response as any)?.results?.[0]- const heatmapData = firstResult?.calendar_heatmap_data-- if (!heatmapData || !heatmapData.data) {- return []- }-- const data = heatmapData.data- const rowAggregations = heatmapData.rowAggregations || []- const columnAggregations = heatmapData.columnAggregations || []- const allAggregations = heatmapData.allAggregations || 0-- const numRows = rowLabels.length- const numCols = columnLabels.length-- const matrix: number[][] = Array(numRows)- .fill(0)- .map(() => Array(numCols).fill(0))- data.forEach((item: EventsHeatMapDataResult) => {- const standardDay = convertClickHouseDayToStandard(item.row)- if (standardDay < numRows && item.column < numCols) {- matrix[standardDay][item.column] = item.value- }- })-- const rowAggMap: Record<number, number> = {}- rowAggregations.forEach((item: EventsHeatMapRowAggregationResult) => {- const standardDay = convertClickHouseDayToStandard(item.row)- rowAggMap[standardDay] = item.value- })-- const colAggArray: number[] = Array(numCols).fill(0)- columnAggregations.forEach((item: EventsHeatMapColumnAggregationResult) => {- if (item.column < numCols) {- colAggArray[item.column] = item.value- }- })-- const headers = ['', ...columnLabels, 'All']- const dataRows = rowLabels.map((rowLabel, rowIndex) => {- const rowValues = matrix[rowIndex].map(String)- const rowTotal = rowAggMap[rowIndex] != null ? String(rowAggMap[rowIndex]) : ''- return [rowLabel, ...rowValues, rowTotal]- })-- const aggregationRow = ['All', ...colAggArray.map(String), String(allAggregations)]-- return [headers, ...dataRows, aggregationRow]- }-- toTableData(): string[][] {- const dayLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']- const hourLabels = Array.from({ length: 24 }, (_, i) => String(i))- return this.getCalendarHeatmapTableData(dayLabels, hourLabels)- }-- canHandle(): boolean {- if (!this.query || this.query.kind !== NodeKind.InsightVizNode) {- return false- }- const source = (this.query as InsightVizNode).source- if (!isTrendsQuery(source)) {- return false- }- const isHeatmap = (source as TrendsQuery)?.trendsFilter?.display === ChartDisplayType.CalendarHeatmap- if (!isHeatmap) {- return false- }-- const firstResult = (this.response as any)?.results?.[0]- const heatmapData = firstResult?.calendar_heatmap_data- return heatmapData && heatmapData.data && heatmapData.data.length > 0- }-}--class WebAnalyticsTableAdapter implements ExportAdapter {+export class WebAnalyticsTableAdapter implements ExportAdapter {constructor(private response: WebStatsTableQueryResponse,private query?: QuerySchema@@ -380,111 +241,3 @@ class WebAnalyticsTableAdapter implements ExportAdapter {return hasData && columns.length > 0}}--class WorldMapAdapter implements ExportAdapter {- constructor(- private response: TrendsQueryResponse,- private query?: QuerySchema- ) {}-- private getWorldMapTableData(): string[][] {- if (!this.response.results || this.response.results.length === 0) {- return []- }-- const headers = ['Country', 'Visitors']- const dataRows = this.response.results.map((series) => {- const countryCode = series.label ?? ''- const visitors = (series as any).aggregated_value ?? series.count ?? 0- return [countryCode, String(visitors)]- })-- return [headers, ...dataRows]- }-- toTableData(): string[][] {- return this.getWorldMapTableData()- }-- canHandle(): boolean {- if (!this.query || this.query.kind !== NodeKind.InsightVizNode) {- return false- }- const source = (this.query as InsightVizNode).source- if (!isTrendsQuery(source)) {- return false- }-- const isWorldMap = (source as TrendsQuery)?.trendsFilter?.display === ChartDisplayType.WorldMap- if (!isWorldMap) {- return false- }-- return this.response.results && this.response.results.length > 0- }-}--class TrendsAdapter implements ExportAdapter {- constructor(- private response: TrendsQueryResponse,- private query?: QuerySchema- ) {}-- private getTrendsTableData(): string[][] {- if (!this.response.results || this.response.results.length === 0) {- return []- }-- // Get date labels from the first series (all series should have the same labels)- const firstSeries = this.response.results[0]- const dateLabels = (firstSeries.labels || firstSeries.days || []) as string[]-- if (dateLabels.length === 0) {- return []- }-- const seriesLabels = this.response.results.map((series) => {- // Use breakdown value if available, otherwise use action name or label- const breakdownValue = (series as any).breakdown_value- const baseName = breakdownValue ?? series.action?.custom_name ?? series.label ?? 'Series'- const compareLabel = series.compare_label- return compareLabel ? `${baseName} (${compareLabel})` : baseName- })- const headers = ['Date', ...seriesLabels]-- const dataRows = dateLabels.map((date, dateIndex) => {- const values = this.response.results.map((series) => {- const data = series.data as number[]- const value = data[dateIndex]- return value != null ? String(value) : ''- })- return [date, ...values]- })-- return [headers, ...dataRows]- }-- toTableData(): string[][] {- return this.getTrendsTableData()- }-- canHandle(): boolean {- if (!this.query || this.query.kind !== NodeKind.InsightVizNode) {- return false- }- const source = (this.query as InsightVizNode).source- if (!isTrendsQuery(source)) {- return false- }-- // Exclude calendar heatmaps and world maps (handled by their own adapters)- const display = (source as TrendsQuery)?.trendsFilter?.display- if (display === ChartDisplayType.CalendarHeatmap || display === ChartDisplayType.WorldMap) {- return false- }-- return this.response.results && this.response.results.length > 0- }-}--export { CalendarHeatmapAdapter, WorldMapAdapter, WebAnalyticsTableAdapter, TrendsAdapter }diff --git a/frontend/src/scenes/web-analytics/webTileHeaderHooks.tsx b/frontend/src/scenes/web-analytics/webTileHeaderHooks.tsxindex 24f64c2c60b6..db0d0421b3fb 100644--- a/frontend/src/scenes/web-analytics/webTileHeaderHooks.tsx+++ b/frontend/src/scenes/web-analytics/webTileHeaderHooks.tsx@@ -9,13 +9,14 @@ import { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { ExportAdapter, copyTableData } from '~/queries/nodes/InsightViz/exportAdapters'import { insightVizDataCollectionId, insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'import { ProductIntentContext, ProductKey, QuerySchema } from '~/queries/schema/schema-general'import { ExporterFormat, InsightLogicProps } from '~/types'import { TileId, WEB_ANALYTICS_DATA_COLLECTION_NODE_ID } from './common'import { shareNudgeLogic } from './shareNudgeLogic'-import { ExportAdapter, downloadTableDataAsCsv, exportTableData, getExportAdapter } from './webAnalyticsExportUtils'+import { downloadTableDataAsCsv, getExportAdapter } from './webAnalyticsExportUtils'import { webAnalyticsModalLogic } from './webAnalyticsModalLogic'const NO_ACTIVE_TAB_INSIGHT_PROPS: InsightLogicProps = {@@ -91,7 +92,7 @@ export function useWebTileOverflowMenuItems({if (!adapter) {return}- exportTableData(adapter.toTableData(), ExporterFormat.CSV)+ copyTableData(adapter.toTableData(), ExporterFormat.CSV)exportTriggered()},},