From be1093adb92780ff24e7bf957ec5dde06a743a23 Mon Sep 17 00:00:00 2001 From: socallmebertille Date: Wed, 22 Jul 2026 18:27:57 +0200 Subject: [PATCH 1/2] add excel download for data --- apps/frontend/package.json | 3 +- .../src/components/data-table-card.tsx | 53 ++++--- .../src/components/export-data-menu.tsx | 59 ++++++++ .../components/tool-calls/display-chart.tsx | 66 +++++---- .../src/components/tool-calls/execute-sql.tsx | 43 +++--- .../tool-calls/tool-call-wrapper.tsx | 134 ++++++++++++------ apps/frontend/src/lib/table-export.ts | 30 +++- apps/shared/src/types.ts | 4 +- package-lock.json | 21 ++- 9 files changed, 296 insertions(+), 117 deletions(-) create mode 100644 apps/frontend/src/components/export-data-menu.tsx diff --git a/apps/frontend/package.json b/apps/frontend/package.json index cee04b892..ef34dfeb5 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -69,7 +69,8 @@ "superjson": "^2.2.6", "tailwind-merge": "^3.4.0", "tailwindcss": "^4.0.6", - "use-stick-to-bottom": "^1.1.1" + "use-stick-to-bottom": "^1.1.1", + "write-excel-file": "^4.1.1" }, "devDependencies": { "@tanstack/devtools-vite": "^0.3.11", diff --git a/apps/frontend/src/components/data-table-card.tsx b/apps/frontend/src/components/data-table-card.tsx index 3685fe85b..1bb932294 100644 --- a/apps/frontend/src/components/data-table-card.tsx +++ b/apps/frontend/src/components/data-table-card.tsx @@ -3,10 +3,12 @@ import { useMutation } from '@tanstack/react-query'; import { Copy, Download, Maximize2 } from 'lucide-react'; import type { ReactNode } from 'react'; import type { ColumnConditionalFormats } from '@nao/shared/conditional-formatting'; +import type { DataExportFormat } from '@/components/export-data-menu'; +import { ExportDataMenu } from '@/components/export-data-menu'; import { TableDisplay } from '@/components/tool-calls/display-table'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'; -import { downloadCsv, tableToCsv, tableToTsv } from '@/lib/table-export'; +import { tableToTsv } from '@/lib/table-export'; import { cn } from '@/lib/utils'; import { trpc } from '@/main'; @@ -44,10 +46,9 @@ export function DataTableCard({ } const handleCopy = () => navigator.clipboard.writeText(tableToTsv(resolvedColumns, data)); - const handleDownload = () => { - downloadCsv('table.csv', tableToCsv(resolvedColumns, data)); + const handleExport = (format: DataExportFormat) => { if (chatId) { - logDownload.mutate({ chatId, format: 'csv', title }); + logDownload.mutate({ chatId, format, title }); } }; @@ -66,15 +67,21 @@ export function DataTableCard({ > - + + - + + []; + filename: string; + onExport?: (format: DataExportFormat) => void; + align?: 'start' | 'end'; + children: ReactNode; +} + +export function ExportDataMenu({ columns, data, filename, onExport, align = 'end', children }: ExportDataMenuProps) { + const [open, setOpen] = useState(false); + const toolCallActions = useToolCallActions(); + + const handleOpenChange = (next: boolean) => { + setOpen(next); + toolCallActions?.setMenuOpen(next); + }; + + const handleExport = async (format: DataExportFormat) => { + if (format === 'csv') { + downloadCsv(`${filename}.csv`, tableToCsv(columns, data)); + } else { + await downloadXlsx(`${filename}.xlsx`, columns, data); + } + onExport?.(format); + }; + + return ( + + event.stopPropagation()}> + {children} + + + handleExport('csv')}> + + CSV + + handleExport('xlsx')}> + + Excel (XLSX) + + + + ); +} diff --git a/apps/frontend/src/components/tool-calls/display-chart.tsx b/apps/frontend/src/components/tool-calls/display-chart.tsx index 043f02e18..67dbd5d44 100644 --- a/apps/frontend/src/components/tool-calls/display-chart.tsx +++ b/apps/frontend/src/components/tool-calls/display-chart.tsx @@ -21,6 +21,7 @@ import type { ChartConfig } from '../ui/chart'; import type { executeSql } from '@nao/shared/tools'; import type { UIMessage } from '@nao/backend/chat'; import type { DateRange } from '@/lib/charts.utils'; +import type { DataExportFormat } from '@/components/export-data-menu'; import { trpc } from '@/main'; import { findStoryIds } from '@/lib/story.utils'; import { @@ -36,7 +37,7 @@ import { useChatId } from '@/hooks/use-chat-id'; import { useSidePanel } from '@/contexts/side-panel'; import { StoryViewer } from '@/components/side-panel/story-viewer'; import { cn } from '@/lib/utils'; -import { downloadCsv, tableToCsv } from '@/lib/table-export'; +import { ExportDataMenu } from '@/components/export-data-menu'; const Colors = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)']; const EMPTY_MESSAGES: UIMessage[] = []; @@ -97,23 +98,8 @@ export const DisplayChartToolCall = ({ const sourceData = sourceQuery?.output ?? null; const sqlQuery = sourceQuery?.input?.sql_query; - const handleDownload = async () => { - if (!chartConfig || !sourceData) { - return; - } - if (viewMode !== 'chart') { - downloadCsv( - `${chartConfig.title || 'chart'}.csv`, - tableToCsv(sourceData.columns, sourceData.data as Record[]), - ); - if (chatId) { - logDownload.mutate({ - chatId, - format: 'csv', - queryId: chartConfig.query_id, - title: chartConfig.title, - }); - } + const handleDownloadPng = async () => { + if (!chartConfig) { return; } @@ -131,6 +117,12 @@ export const DisplayChartToolCall = ({ } }; + const handleExportData = (format: DataExportFormat) => { + if (chatId) { + logDownload.mutate({ chatId, format, queryId: chartConfig?.query_id, title: chartConfig?.title }); + } + }; + const filteredData = useMemo(() => { if (!sourceData?.data || !chartConfig) { return []; @@ -310,17 +302,35 @@ export const DisplayChartToolCall = ({ )} - {(viewMode !== 'chart' || chartConfig.chart_type != 'kpi_card') && ( - + ) + ) : ( + []} + filename={chartConfig.title || 'chart'} + onExport={handleExportData} > - - + + )} {isEditable && ( diff --git a/apps/frontend/src/components/tool-calls/execute-sql.tsx b/apps/frontend/src/components/tool-calls/execute-sql.tsx index 4da63fc62..7c50cfb4e 100644 --- a/apps/frontend/src/components/tool-calls/execute-sql.tsx +++ b/apps/frontend/src/components/tool-calls/execute-sql.tsx @@ -5,13 +5,14 @@ import { ToolCallWrapper } from './tool-call-wrapper'; import { TableFormatEditDialog } from './display-table-edit-dialog'; import { SqlQueryDisplay } from './sql-query-display'; import { SqlResultDisplay } from './sql-result-display'; +import type { ActionButton } from './tool-call-wrapper'; import type { ToolCallComponentProps } from '.'; import type { ColumnConditionalFormats } from '@nao/shared/conditional-formatting'; +import type { DataExportFormat } from '@/components/export-data-menu'; import { useOptionalAgentContext } from '@/contexts/agent.provider'; import { useSidePanel } from '@/contexts/side-panel'; import { useToolCallContext } from '@/contexts/tool-call'; import { SidePanelContent } from '@/components/side-panel/sql-editor'; -import { downloadCsv, tableToCsv } from '@/lib/table-export'; import { trpc } from '@/main'; type ViewMode = 'results' | 'query'; @@ -27,7 +28,13 @@ export const ExecuteSqlToolCall = ({ const chatId = useOptionalAgentContext()?.chatId; const logDownload = useMutation(trpc.analyticsEvent.logChatDownload.mutationOptions()); - const actions = [ + const handleExport = (format: DataExportFormat) => { + if (chatId) { + logDownload.mutate({ chatId, format, queryId: toolCallId, title: input?.name }); + } + }; + + const actions: ActionButton[] = [ { id: 'results', label: , @@ -64,23 +71,21 @@ export const ExecuteSqlToolCall = ({ }, title: 'Copy query', }, - { - id: 'download', - label: , - onClick: () => { - if (!output) { - return; - } - downloadCsv( - `${input?.name || 'query'}.csv`, - tableToCsv(output.columns, output.data as Record[]), - ); - if (chatId) { - logDownload.mutate({ chatId, format: 'csv', queryId: toolCallId, title: input?.name }); - } - }, - title: 'Download results as CSV', - }, + ...(output + ? [ + { + id: 'download', + label: , + title: 'Export results', + export: { + columns: output.columns, + data: output.data as Record[], + filename: input?.name || 'query', + onExport: handleExport, + }, + }, + ] + : []), { id: 'expand', label: , diff --git a/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx b/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx index 11241174f..e650dec23 100644 --- a/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx +++ b/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx @@ -1,21 +1,43 @@ -import { useEffect, useRef, useState } from 'react'; +import { createContext, useContext, useEffect, useRef, useState } from 'react'; import { Button } from '../ui/button'; import type { ReactNode } from 'react'; +import type { DataExportFormat } from '@/components/export-data-menu'; import { cn } from '@/lib/utils'; import { Spinner } from '@/components/ui/spinner'; import { Expandable } from '@/components/ui/expandable'; import { useToolCallContext } from '@/contexts/tool-call'; import { useIsInToolGroup } from '@/contexts/tool-group'; +import { ExportDataMenu } from '@/components/export-data-menu'; -interface ActionButton { +const ToolCallActionsContext = createContext<{ setMenuOpen: (open: boolean) => void } | null>(null); + +export const useToolCallActions = () => useContext(ToolCallActionsContext); + +interface ExportAction { + columns: string[]; + data: Record[]; + filename: string; + onExport?: (format: DataExportFormat) => void; +} + +interface BaseAction { id: string; label: ReactNode; + title: string; isActive?: boolean; - onClick: () => void; expandOnClick?: boolean; - title: string; } +interface ButtonAction extends BaseAction { + onClick: () => void; +} + +interface ExportActionButton extends BaseAction { + export: ExportAction; +} + +export type ActionButton = ButtonAction | ExportActionButton; + interface ToolCallWrapperProps { title: ReactNode; badge?: ReactNode; @@ -37,6 +59,7 @@ export const ToolCallWrapper = ({ const isInToolGroup = useIsInToolGroup(); const [isExpanded, setIsExpanded] = useState(false); const [isHovering, setIsHovering] = useState(false); + const [isMenuOpen, setIsMenuOpen] = useState(false); const canExpand = Boolean(children || toolPart.errorText || toolPart.output); const hasInitialized = useRef(false); @@ -62,26 +85,45 @@ export const ToolCallWrapper = ({ ); const actionsContent = - (isHovering || isExpanded) && actions && actions.length > 0 ? ( + (isHovering || isExpanded || isMenuOpen) && actions && actions.length > 0 ? (
- {actions.map((action) => ( - - ))} + {actions.map((action) => { + if ('export' in action) { + return ( + e.stopPropagation()}> + + + + + ); + } + + return ( + + ); + })}
) : undefined; @@ -96,28 +138,30 @@ export const ToolCallWrapper = ({ const contentToShow = toolPart.errorText && !overrideError ? errorContent : children; return ( -
setIsHovering(true)} - onMouseLeave={() => setIsHovering(false)} - className={cn(isBordered && '-mx-3')} - {...(hasError && { - 'data-replay-nav': 'tool-error', - 'data-replay-bordered': isBordered ? 'true' : 'false', - })} - > - +
setIsHovering(true)} + onMouseLeave={() => setIsHovering(false)} + className={cn(isBordered && '-mx-3')} + {...(hasError && { + 'data-replay-nav': 'tool-error', + 'data-replay-bordered': isBordered ? 'true' : 'false', + })} > - {contentToShow} - -
+ + {contentToShow} + +
+ ); }; diff --git a/apps/frontend/src/lib/table-export.ts b/apps/frontend/src/lib/table-export.ts index 7c698a404..db934e87f 100644 --- a/apps/frontend/src/lib/table-export.ts +++ b/apps/frontend/src/lib/table-export.ts @@ -1,4 +1,6 @@ +import writeXlsxFile from 'write-excel-file/universal'; import { formatCellValue } from '@nao/shared/story-table-utils'; +import type { Cell, Row } from 'write-excel-file/universal'; type TableRow = Record; @@ -24,8 +26,34 @@ export function tableToTsv(columns: string[], rows: TableRow[]): string { ].join('\n'); } +function tableToXlsxBlob(columns: string[], rows: TableRow[]): Promise { + const header: Row = columns.map((column) => ({ value: column, fontWeight: 'bold' })); + const body: Row[] = rows.map((row) => columns.map((column) => toXlsxCell(row[column]))); + return writeXlsxFile([header, ...body]).toBlob(); +} + +function toXlsxCell(value: unknown): Cell { + if (value === null || value === undefined) { + return null; + } + if (typeof value === 'number') { + return Number.isFinite(value) ? { type: Number, value } : null; + } + if (typeof value === 'boolean') { + return { type: Boolean, value }; + } + return { type: String, value: formatCellValue(value) }; +} + export function downloadCsv(filename: string, csv: string): void { - const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); + triggerDownload(filename, new Blob([csv], { type: 'text/csv;charset=utf-8;' })); +} + +export async function downloadXlsx(filename: string, columns: string[], rows: TableRow[]): Promise { + triggerDownload(filename, await tableToXlsxBlob(columns, rows)); +} + +function triggerDownload(filename: string, blob: Blob): void { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; diff --git a/apps/shared/src/types.ts b/apps/shared/src/types.ts index 7e64936ac..93a401bc1 100644 --- a/apps/shared/src/types.ts +++ b/apps/shared/src/types.ts @@ -137,8 +137,8 @@ export type ProjectChatListItem = { export type DownloadFormat = 'pdf' | 'html'; export const DOWNLOAD_FORMATS = ['pdf', 'html'] as const satisfies readonly DownloadFormat[]; -export type ChatDownloadFormat = 'png' | 'csv'; -export const CHAT_DOWNLOAD_FORMATS = ['png', 'csv'] as const satisfies readonly ChatDownloadFormat[]; +export type ChatDownloadFormat = 'png' | 'csv' | 'xlsx'; +export const CHAT_DOWNLOAD_FORMATS = ['png', 'csv', 'xlsx'] as const satisfies readonly ChatDownloadFormat[]; export type AnalyticsDownloadFormat = DownloadFormat | ChatDownloadFormat; diff --git a/package-lock.json b/package-lock.json index 9b401f389..b814fb3e2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -306,7 +306,8 @@ "superjson": "^2.2.6", "tailwind-merge": "^3.4.0", "tailwindcss": "^4.0.6", - "use-stick-to-bottom": "^1.1.1" + "use-stick-to-bottom": "^1.1.1", + "write-excel-file": "^4.1.1" }, "devDependencies": { "@tanstack/devtools-vite": "^0.3.11", @@ -27479,6 +27480,24 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/write-excel-file": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz", + "integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==", + "license": "MIT", + "dependencies": { + "fflate": "^0.8.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/write-excel-file/node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, "node_modules/ws": { "version": "8.20.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", From ecec24773c9f313c2d7af307ae40faffef708af1 Mon Sep 17 00:00:00 2001 From: socallmebertille Date: Thu, 23 Jul 2026 09:19:30 +0200 Subject: [PATCH 2/2] fix from cubic review --- apps/frontend/src/components/export-data-menu.tsx | 6 +++--- .../src/components/tool-calls/tool-call-wrapper.tsx | 11 ++++------- apps/frontend/src/contexts/tool-call-actions.ts | 7 +++++++ 3 files changed, 14 insertions(+), 10 deletions(-) create mode 100644 apps/frontend/src/contexts/tool-call-actions.ts diff --git a/apps/frontend/src/components/export-data-menu.tsx b/apps/frontend/src/components/export-data-menu.tsx index 3c85d32ad..5e2617ff4 100644 --- a/apps/frontend/src/components/export-data-menu.tsx +++ b/apps/frontend/src/components/export-data-menu.tsx @@ -1,13 +1,13 @@ import { FileSpreadsheet } from 'lucide-react'; import { useState } from 'react'; -import type { ReactNode } from 'react'; +import type { ReactElement } from 'react'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; -import { useToolCallActions } from '@/components/tool-calls/tool-call-wrapper'; +import { useToolCallActions } from '@/contexts/tool-call-actions'; import { downloadCsv, downloadXlsx, tableToCsv } from '@/lib/table-export'; export type DataExportFormat = 'csv' | 'xlsx'; @@ -18,7 +18,7 @@ interface ExportDataMenuProps { filename: string; onExport?: (format: DataExportFormat) => void; align?: 'start' | 'end'; - children: ReactNode; + children: ReactElement; } export function ExportDataMenu({ columns, data, filename, onExport, align = 'end', children }: ExportDataMenuProps) { diff --git a/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx b/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx index e650dec23..84f0cd032 100644 --- a/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx +++ b/apps/frontend/src/components/tool-calls/tool-call-wrapper.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Button } from '../ui/button'; import type { ReactNode } from 'react'; import type { DataExportFormat } from '@/components/export-data-menu'; @@ -7,12 +7,9 @@ import { Spinner } from '@/components/ui/spinner'; import { Expandable } from '@/components/ui/expandable'; import { useToolCallContext } from '@/contexts/tool-call'; import { useIsInToolGroup } from '@/contexts/tool-group'; +import { ToolCallActionsProvider } from '@/contexts/tool-call-actions'; import { ExportDataMenu } from '@/components/export-data-menu'; -const ToolCallActionsContext = createContext<{ setMenuOpen: (open: boolean) => void } | null>(null); - -export const useToolCallActions = () => useContext(ToolCallActionsContext); - interface ExportAction { columns: string[]; data: Record[]; @@ -138,7 +135,7 @@ export const ToolCallWrapper = ({ const contentToShow = toolPart.errorText && !overrideError ? errorContent : children; return ( - +
setIsHovering(true)} onMouseLeave={() => setIsHovering(false)} @@ -162,6 +159,6 @@ export const ToolCallWrapper = ({ {contentToShow}
-
+ ); }; diff --git a/apps/frontend/src/contexts/tool-call-actions.ts b/apps/frontend/src/contexts/tool-call-actions.ts new file mode 100644 index 000000000..a525f3e54 --- /dev/null +++ b/apps/frontend/src/contexts/tool-call-actions.ts @@ -0,0 +1,7 @@ +import { createContext, useContext } from 'react'; + +const ToolCallActionsContext = createContext<{ setMenuOpen: (open: boolean) => void } | null>(null); + +export const ToolCallActionsProvider = ToolCallActionsContext.Provider; + +export const useToolCallActions = () => useContext(ToolCallActionsContext);