/**
* ChartDisplay Component
*
* Renders various chart types using Recharts based on configuration.
* Supports: bar, line, pie, scatter, area charts.
*/
import {
BarChart,
Bar,
LineChart,
Line,
PieChart,
Pie,
Cell,
ScatterChart,
Scatter,
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
import type { ChartConfig } from '../types';
interface ChartDisplayProps {
config: ChartConfig;
}
// Default color palette
const DEFAULT_COLORS = [
'#3B82F6', // blue-500
'#10B981', // emerald-500
'#F59E0B', // amber-500
'#EF4444', // red-500
'#8B5CF6', // violet-500
'#EC4899', // pink-500
'#06B6D4', // cyan-500
'#84CC16', // lime-500
];
export function ChartDisplay({ config }: ChartDisplayProps) {
const { type, data, xKey, yKey, title, colors: configColors } = config;
const colors = configColors && configColors.length > 0 ? configColors : DEFAULT_COLORS;
if (!data || data.length === 0) {
return (
No data available for chart
);
}
const renderChart = () => {
switch (type) {
case 'bar':
return renderBarChart();
case 'line':
return renderLineChart();
case 'pie':
return renderPieChart();
case 'scatter':
return renderScatterChart();
case 'area':
return renderAreaChart();
default:
return renderBarChart();
}
};
const renderBarChart = () => {
const yKeys = Array.isArray(yKey) ? yKey.filter(k => k) : (yKey ? [yKey] : []);
if (yKeys.length === 0) {
return (
No data key specified for chart
);
}
const isHorizontalBars = config.layout === 'vertical';
return (
{isHorizontalBars ? (
) : (
)}
{isHorizontalBars ? (
) : (
)}
{yKeys.map((key, index) => (
))}
);
};
const renderLineChart = () => {
const yKeys = Array.isArray(yKey) ? yKey.filter(k => k) : (yKey ? [yKey] : []);
if (yKeys.length === 0) {
return (
No data key specified for chart
);
}
return (
{yKeys.map((key, index) => (
))}
);
};
const renderPieChart = () => {
const dataKey = Array.isArray(yKey) ? yKey[0] : yKey;
if (!dataKey) {
return (
No data key specified for chart
);
}
return (
`${name}: ${(percent * 100).toFixed(1)}%`
}
labelLine={{ stroke: '#9CA3AF' }}
>
{data.map((_, index) => (
|
))}
);
};
const renderScatterChart = () => {
const yDataKey = Array.isArray(yKey) ? yKey[0] : yKey;
if (!yDataKey) {
return (
No data key specified for chart
);
}
return (
{data.map((_, index) => (
|
))}
);
};
const renderAreaChart = () => {
const yKeys = Array.isArray(yKey) ? yKey.filter(k => k) : (yKey ? [yKey] : []);
if (yKeys.length === 0) {
return (
No data key specified for chart
);
}
return (
{yKeys.map((key, index) => (
))}
);
};
return (
{title && (
{title}
)}
{renderChart()}
);
}
export default ChartDisplay;