import { useMemo, useState } from 'react' import dayjs from 'dayjs' import { Bar, BarChart, CartesianGrid, Cell, Tooltip, XAxis, YAxis } from 'recharts' import { ChartContainer, ChartTooltipContent } from 'ui' import { CHART_COLORS } from 'components/ui/Charts/Charts.constants' import type { ChartConfig } from 'components/ui/QueryBlock/QueryBlock.types' interface SQLQueryChartProps { results: any[] chartConfig: ChartConfig } function getCumulativeResults(data: { rows: readonly any[] }, config: ChartConfig): any[] { const { xKey, yKey } = config if (!xKey || !yKey) return data.rows as any[] let cumulative = 0 return data.rows.map((row) => { cumulative += Number(row[yKey]) || 0 return { ...row, [yKey]: cumulative, } }) } export function SQLQueryChart({ results, chartConfig }: SQLQueryChartProps) { const { xKey, yKey, cumulative = false } = chartConfig const [focusDataIndex, setFocusDataIndex] = useState() const formattedQueryResult = useMemo(() => { return results?.map((row) => { return Object.fromEntries( Object.entries(row).map(([key, value]) => { if (key === yKey) return [key, Number(value)] return [key, value] }) ) }) }, [results, yKey]) const chartData = cumulative ? getCumulativeResults({ rows: formattedQueryResult ?? [] }, chartConfig) : formattedQueryResult const getDateFormat = (key: string) => { const value = chartData?.[0]?.[key] || '' if (typeof value === 'number') return 'number' if (dayjs(value).isValid()) return 'date' return 'string' } const xKeyDateFormat = getDateFormat(xKey) if (!xKey || !yKey) { return (

Select columns for the X and Y axes

) } return (
{ if (e.activeTooltipIndex !== focusDataIndex) { setFocusDataIndex(e.activeTooltipIndex) } }} onMouseLeave={() => setFocusDataIndex(undefined)} > xKeyDateFormat === 'date' ? dayjs(value).format('MMM D YYYY HH:mm') : value } /> } /> {chartData?.map((_: any, index: number) => ( ))}
) }