Skip to content

πŸ“ˆ Open source, privacy-first web analytics β€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Allow exporting charts

Blue Moused931d0e665df
diff --git a/web/app/pages/Project/tabs/AskAI/AIChart.tsx b/web/app/pages/Project/tabs/AskAI/AIChart.tsx
index 8eb3d8f18..d8e25b5bf 100644
--- a/web/app/pages/Project/tabs/AskAI/AIChart.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AIChart.tsx
@@ -1,13 +1,37 @@
-import type { ChartOptions } from 'billboard.js'
+import {
+ Menu,
+ MenuButton,
+ MenuItem,
+ MenuItems,
+ Transition,
+} from '@headlessui/react'
+import type { Chart, ChartOptions } from 'billboard.js'
import { line, area, bar, spline, pie, donut } from 'billboard.js'
-import { ArrowSquareOutIcon } from '@phosphor-icons/react'
+import {
+ ArrowSquareOutIcon,
+ ChartBarIcon,
+ ChartDonutIcon,
+ ChartLineIcon,
+ ChartPieIcon,
+ CopyIcon,
+ DownloadSimpleIcon,
+ FileCsvIcon,
+} from '@phosphor-icons/react'
import dayjs from 'dayjs'
import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
-import React, { useMemo, memo } from 'react'
+import React, {
+ Fragment,
+ memo,
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
import BillboardChart from '~/ui/BillboardChart'
import { cn } from '~/utils/generic'
@@ -77,9 +101,11 @@ interface AIChartAnnotation {
kind?: 'spike' | 'dip'
}
+type AIChartType = 'line' | 'bar' | 'area' | 'spline' | 'pie' | 'donut'
+
interface AIChartData {
type: 'chart'
- chartType: 'line' | 'bar' | 'area' | 'spline' | 'pie' | 'donut'
+ chartType: AIChartType
title?: string
data: {
x?: string[]
@@ -91,6 +117,9 @@ interface AIChartData {
link?: AIChartLink
}
+const TIME_SERIES_TYPES: AIChartType[] = ['line', 'area', 'spline', 'bar']
+const CATEGORICAL_TYPES: AIChartType[] = ['pie', 'donut']
+
const ANNOTATION_LABEL_MAX = 40
const buildAnnotationLines = (
@@ -306,16 +335,241 @@ const isPieOrDonutChart = (chartType: string): boolean => {
return chartType === 'pie' || chartType === 'donut'
}
+const slugify = (str: string): string => {
+ const slug = str
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ return slug || 'chart'
+}
+
+const triggerBlobDownload = (blob: Blob, filename: string) => {
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ // Revoke on next tick so the download has time to kick off
+ setTimeout(() => URL.revokeObjectURL(url), 0)
+}
+
+const escapeCsvCell = (value: unknown): string => {
+ if (value === null || value === undefined) return ''
+ const str = String(value)
+ if (/[",\n\r]/.test(str)) {
+ return `"${str.replace(/"/g, '""')}"`
+ }
+ return str
+}
+
+const buildCsvFromChart = (
+ chart: AIChartData,
+ displayType: AIChartType,
+): string => {
+ const lines: string[] = []
+ if (isPieOrDonutChart(displayType)) {
+ const labels = (chart.data.labels as string[]) || []
+ const values = (chart.data.values as number[]) || []
+ lines.push(['label', 'value'].map(escapeCsvCell).join(','))
+ labels.forEach((label, idx) => {
+ lines.push(
+ [escapeCsvCell(label), escapeCsvCell(values[idx] ?? '')].join(','),
+ )
+ })
+ } else {
+ const xData = (chart.data.x as string[]) || []
+ const seriesKeys = _filter(
+ _keys(chart.data),
+ (key) => key !== 'x' && key !== 'labels' && key !== 'values',
+ )
+ lines.push(['x', ...seriesKeys].map(escapeCsvCell).join(','))
+ xData.forEach((xVal, idx) => {
+ const row = [
+ escapeCsvCell(xVal),
+ ...seriesKeys.map((key) => {
+ const series = chart.data[key]
+ return escapeCsvCell(Array.isArray(series) ? series[idx] : '')
+ }),
+ ]
+ lines.push(row.join(','))
+ })
+ }
+ return lines.join('\n')
+}
+
+// Subset of CSS properties that meaningfully affect rendered SVG output.
+// Inlining everything from getComputedStyle bloats the file and can break
+// gradient/marker references, so we cherry-pick the visual ones.
+const SVG_STYLE_PROPS = [
+ 'fill',
+ 'fill-opacity',
+ 'stroke',
+ 'stroke-width',
+ 'stroke-opacity',
+ 'stroke-linecap',
+ 'stroke-linejoin',
+ 'stroke-dasharray',
+ 'stroke-miterlimit',
+ 'opacity',
+ 'visibility',
+ 'display',
+ 'color',
+ 'font-family',
+ 'font-size',
+ 'font-weight',
+ 'font-style',
+ 'text-anchor',
+ 'dominant-baseline',
+ 'shape-rendering',
+ 'paint-order',
+] as const
+
+// Walk source + cloned trees in lockstep and copy the resolved styles onto the
+// clone so the rasterised SVG matches what the browser draws.
+const inlineComputedStyles = (source: SVGElement, target: SVGElement) => {
+ const sourceNodes: Element[] = [
+ source,
+ ...Array.from(source.querySelectorAll('*')),
+ ]
+ const targetNodes: Element[] = [
+ target,
+ ...Array.from(target.querySelectorAll('*')),
+ ]
+
+ const len = Math.min(sourceNodes.length, targetNodes.length)
+ for (let i = 0; i < len; i++) {
+ const computed = window.getComputedStyle(sourceNodes[i])
+ let styleStr = ''
+ for (const prop of SVG_STYLE_PROPS) {
+ const value = computed.getPropertyValue(prop)
+ if (!value) continue
+ styleStr += `${prop}:${value};`
+ }
+ if (styleStr) {
+ const existing =
+ (targetNodes[i] as HTMLElement).getAttribute('style') || ''
+ ;(targetNodes[i] as HTMLElement).setAttribute(
+ 'style',
+ `${styleStr}${existing}`,
+ )
+ }
+ }
+}
+
+// Billboard renders to SVG with styles applied via stylesheets; we inline the
+// computed styles, capture the bounding box, then rasterise via Image β†’
+// Canvas β†’ PNG blob.
+const exportChartAsPng = async (
+ container: HTMLElement,
+ filename: string,
+): Promise<void> => {
+ const svg = container.querySelector('svg')
+ if (!svg) throw new Error('svg not found')
+
+ const rect = svg.getBoundingClientRect()
+ const width = Math.max(1, Math.round(rect.width))
+ const height = Math.max(1, Math.round(rect.height))
+
+ const clone = svg.cloneNode(true) as SVGSVGElement
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
+ clone.setAttribute('width', String(width))
+ clone.setAttribute('height', String(height))
+ if (!clone.getAttribute('viewBox')) {
+ clone.setAttribute('viewBox', `0 0 ${width} ${height}`)
+ }
+
+ inlineComputedStyles(svg, clone)
+
+ const svgString = new XMLSerializer().serializeToString(clone)
+ const svgBlob = new Blob(
+ ['<?xml version="1.0" standalone="no"?>\n', svgString],
+ { type: 'image/svg+xml;charset=utf-8' },
+ )
+ const svgUrl = URL.createObjectURL(svgBlob)
+
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const img = new Image()
+ img.onload = () => {
+ try {
+ const dpr = window.devicePixelRatio || 1
+ const canvas = document.createElement('canvas')
+ canvas.width = width * dpr
+ canvas.height = height * dpr
+ const ctx = canvas.getContext('2d')
+ if (!ctx) throw new Error('canvas context unavailable')
+ ctx.fillStyle = '#ffffff'
+ ctx.fillRect(0, 0, canvas.width, canvas.height)
+ ctx.scale(dpr, dpr)
+ ctx.drawImage(img, 0, 0, width, height)
+ canvas.toBlob((pngBlob) => {
+ if (!pngBlob) {
+ reject(new Error('toBlob failed'))
+ return
+ }
+ triggerBlobDownload(pngBlob, filename)
+ resolve()
+ }, 'image/png')
+ } catch (err) {
+ reject(err)
+ }
+ }
+ img.onerror = () => reject(new Error('image load failed'))
+ img.src = svgUrl
+ })
+ } finally {
+ URL.revokeObjectURL(svgUrl)
+ }
+}
+
+const TYPE_ICONS: Record<
+ AIChartType,
+ React.ComponentType<{ className?: string }>
+> = {
+ line: ChartLineIcon,
+ area: ChartLineIcon,
+ spline: ChartLineIcon,
+ bar: ChartBarIcon,
+ pie: ChartPieIcon,
+ donut: ChartDonutIcon,
+}
+
const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
const { t } = useTranslation('common')
+ const containerRef = useRef<HTMLDivElement | null>(null)
+ const [displayType, setDisplayType] = useState<AIChartType>(chart.chartType)
+ const [chartReady, setChartReady] = useState(false)
+
+ const handleChartReady = useCallback((instance: Chart | null) => {
+ setChartReady(instance !== null)
+ }, [])
const dashboardHref = useMemo(() => {
if (!projectId || !chart.link) return null
return buildDashboardUrl(projectId, chart.link)
}, [projectId, chart.link])
+ const isPieDonutData =
+ !_isEmpty(chart.data.labels) && !_isEmpty(chart.data.values)
+ const isTimeSeriesData = !_isEmpty(chart.data.x)
+
+ const compatibleTypes = useMemo<AIChartType[]>(() => {
+ if (isPieDonutData) {
+ const labels = (chart.data.labels as string[]) || []
+ if (labels.length <= 1) return [displayType]
+ return CATEGORICAL_TYPES
+ }
+ if (isTimeSeriesData) {
+ return TIME_SERIES_TYPES
+ }
+ return [displayType]
+ }, [chart.data.labels, displayType, isPieDonutData, isTimeSeriesData])
+
const chartOptions = useMemo<ChartOptions>(() => {
- const isPieDonut = isPieOrDonutChart(chart.chartType)
+ const isPieDonut = isPieOrDonutChart(displayType)
if (isPieDonut) {
if (
@@ -342,11 +596,11 @@ const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
return {
data: {
columns,
- type: getChartType(chart.chartType),
+ type: getChartType(displayType),
colors,
},
donut:
- chart.chartType === 'donut'
+ displayType === 'donut'
? {
title: '',
label: {
@@ -356,7 +610,7 @@ const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
}
: undefined,
pie:
- chart.chartType === 'pie'
+ displayType === 'pie'
? {
label: {
format: (_value: number, ratio: number) =>
@@ -444,7 +698,7 @@ const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
seriesKeys.forEach((key, idx) => {
columns.push([key, ...chart.data[key]!])
- types[key] = getChartType(chart.chartType) as any
+ types[key] = getChartType(displayType) as any
colors[key] = CHART_COLORS[idx % CHART_COLORS.length]
})
@@ -463,7 +717,7 @@ const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
const optimalTicks =
allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
- const isBar = chart.chartType === 'bar'
+ const isBar = displayType === 'bar'
const annotationLines = isDateAxis
? buildAnnotationLines(chart.annotations, xData)
@@ -601,9 +855,38 @@ const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
right: 20,
},
}
- }, [chart])
+ }, [chart, displayType])
- const isPieDonut = isPieOrDonutChart(chart.chartType)
+ const filenameBase = useMemo(
+ () => slugify(chart.title || 'chart'),
+ [chart.title],
+ )
+
+ const handleDownloadPng = useCallback(async () => {
+ if (!containerRef.current || !chartReady) return
+ try {
+ await exportChartAsPng(containerRef.current, `${filenameBase}.png`)
+ } catch {
+ // swallow – download failed, nothing actionable to show
+ }
+ }, [chartReady, filenameBase])
+
+ const handleDownloadCsv = useCallback(() => {
+ const csv = buildCsvFromChart(chart, displayType)
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' })
+ triggerBlobDownload(blob, `${filenameBase}.csv`)
+ }, [chart, displayType, filenameBase])
+
+ const handleCopyData = useCallback(async () => {
+ try {
+ await navigator.clipboard.writeText(JSON.stringify(chart.data, null, 2))
+ toast.success(t('project.askAi.chart.dataCopied'))
+ } catch {
+ // ignore clipboard errors
+ }
+ }, [chart.data, t])
+
+ const isPieDonut = isPieOrDonutChart(displayType)
if (isPieDonut) {
if (
@@ -619,53 +902,136 @@ const AIChart: React.FC<AIChartProps> = ({ chart, projectId }) => {
}
}
+ const canChangeType = compatibleTypes.length > 1
+ const openInDashboardLabel = t('project.askAi.openInDashboard')
+
+ const toolbarButtonClass =
+ 'flex h-7 w-7 items-center justify-center rounded-md text-gray-500 bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm ring-1 ring-gray-200/80 dark:ring-slate-800/80 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-slate-800 dark:hover:text-gray-200 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-white/80 dark:disabled:hover:bg-slate-900/80'
+
+ const toolbar = (
+ <div className='absolute top-3 right-3 z-10 flex items-center gap-1 opacity-0 transition-opacity group-hover/chart:opacity-100 focus-within:opacity-100'>
+ {canChangeType ? (
+ <Menu as='div' className='relative'>
+ {({ open }) => (
+ <>
+ <MenuButton
+ className={toolbarButtonClass}
+ title={t('project.askAi.chart.changeType')}
+ aria-label={t('project.askAi.chart.changeType')}
+ >
+ <ChartLineIcon className='h-4 w-4' />
+ </MenuButton>
+ <Transition
+ show={open}
+ as={Fragment}
+ enter='transition ease-out duration-100'
+ enterFrom='transform opacity-0 scale-95'
+ enterTo='transform opacity-100 scale-100'
+ leave='transition ease-in duration-75'
+ leaveFrom='transform opacity-100 scale-100'
+ leaveTo='transform opacity-0 scale-95'
+ >
+ <MenuItems
+ anchor={{ to: 'bottom end', offset: 6 }}
+ modal={false}
+ className='z-50 w-36 rounded-md bg-white p-1 ring-1 ring-gray-200 focus:outline-hidden dark:bg-slate-900 dark:ring-slate-800'
+ >
+ {compatibleTypes.map((typeOption) => {
+ const Icon = TYPE_ICONS[typeOption]
+ const active = typeOption === displayType
+ return (
+ <MenuItem key={typeOption}>
+ <button
+ type='button'
+ onClick={() => setDisplayType(typeOption)}
+ className={cn(
+ 'flex w-full cursor-pointer items-center gap-2 rounded-md p-2 text-sm transition-colors',
+ active
+ ? 'bg-gray-100 text-gray-900 dark:bg-slate-800 dark:text-white'
+ : 'text-gray-700 hover:bg-gray-100 dark:text-gray-50 dark:hover:bg-slate-800',
+ )}
+ >
+ <Icon className='h-4 w-4' />
+ <span>
+ {t(`project.askAi.chart.types.${typeOption}`)}
+ </span>
+ </button>
+ </MenuItem>
+ )
+ })}
+ </MenuItems>
+ </Transition>
+ </>
+ )}
+ </Menu>
+ ) : null}
+ <button
+ type='button'
+ onClick={handleDownloadPng}
+ disabled={!chartReady}
+ className={toolbarButtonClass}
+ title={t('project.askAi.chart.downloadPng')}
+ aria-label={t('project.askAi.chart.downloadPng')}
+ >
+ <DownloadSimpleIcon className='h-4 w-4' />
+ </button>
+ <button
+ type='button'
+ onClick={handleDownloadCsv}
+ className={toolbarButtonClass}
+ title={t('project.askAi.chart.downloadCsv')}
+ aria-label={t('project.askAi.chart.downloadCsv')}
+ >
+ <FileCsvIcon className='h-4 w-4' />
+ </button>
+ <button
+ type='button'
+ onClick={handleCopyData}
+ className={toolbarButtonClass}
+ title={t('project.askAi.chart.copyData')}
+ aria-label={t('project.askAi.chart.copyData')}
+ >
+ <CopyIcon className='h-4 w-4' />
+ </button>
+ {dashboardHref ? (
+ <a
+ href={dashboardHref}
+ target='_blank'
+ rel='noopener noreferrer'
+ className={toolbarButtonClass}
+ title={openInDashboardLabel}
+ aria-label={openInDashboardLabel}
+ >
+ <ArrowSquareOutIcon className='h-4 w-4' />
+ </a>
+ ) : null}
+ </div>
+ )
+
const cardClassName = cn(
- 'ai-chart group/chart relative block rounded-lg border bg-white p-4 transition-colors dark:bg-slate-900',
- dashboardHref
- ? 'border-gray-200 hover:border-gray-300 dark:border-slate-800 dark:hover:border-slate-700'
- : 'border-gray-200 dark:border-slate-800',
+ 'ai-chart group/chart relative block rounded-lg border border-gray-200 bg-white p-4 transition-colors dark:border-slate-800 dark:bg-slate-900',
)
const titleNode = chart.title ? (
- <h4 className='mb-2 pr-8 text-sm font-medium text-gray-700 dark:text-gray-300'>
+ <h4 className='mb-2 pr-36 text-sm font-medium text-gray-700 dark:text-gray-300'>
{chart.title}
</h4>
) : null
- const chartBody = (
- <div className={isPieDonut ? 'h-[280px] w-full' : 'h-[220px] w-full'}>
- <BillboardChart options={chartOptions} className='h-full w-full' />
- </div>
- )
-
- const openInDashboardLabel = t('project.askAi.openInDashboard')
-
- if (dashboardHref) {
- return (
- <a
- href={dashboardHref}
- target='_blank'
- rel='noopener noreferrer'
- className={cardClassName}
- aria-label={openInDashboardLabel}
- title={openInDashboardLabel}
- >
- <span
- aria-hidden='true'
- className='absolute top-3 right-3 flex h-7 w-7 items-center justify-center rounded-md text-gray-400 transition-colors group-hover/chart:bg-gray-100 group-hover/chart:text-gray-700 dark:group-hover/chart:bg-slate-800 dark:group-hover/chart:text-gray-200'
- >
- <ArrowSquareOutIcon className='h-4 w-4' />
- </span>
- {titleNode}
- {chartBody}
- </a>
- )
- }
-
return (
<div className={cardClassName}>
+ {toolbar}
{titleNode}
- {chartBody}
+ <div
+ ref={containerRef}
+ className={isPieDonut ? 'h-[280px] w-full' : 'h-[220px] w-full'}
+ >
+ <BillboardChart
+ options={chartOptions}
+ className='h-full w-full'
+ onReady={handleChartReady}
+ />
+ </div>
</div>
)
}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index b06f2e5b0..6572c6f37 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2132,6 +2132,21 @@
"feedbackSent": "Thanks for the feedback!",
"untitledChat": "Untitled chat",
"openInDashboard": "Open in dashboard",
+ "chart": {
+ "changeType": "Change chart type",
+ "downloadPng": "Download as PNG",
+ "downloadCsv": "Download as CSV",
+ "copyData": "Copy data",
+ "dataCopied": "Chart data copied to clipboard",
+ "types": {
+ "line": "Line",
+ "area": "Area",
+ "spline": "Spline",
+ "bar": "Bar",
+ "pie": "Pie",
+ "donut": "Donut"
+ }
+ },
"tools": {
"getProjectInfo": "Fetched project info",
"getData": "Queried data",