|
| 1 | +'use client' |
| 2 | + |
| 3 | +import React from 'react' |
| 4 | + |
| 5 | +import { ComposedChart, XAxis, YAxis, CartesianGrid, Area, Bar, Line } from 'recharts' |
| 6 | +import { |
| 7 | + ChartContainer, |
| 8 | + ChartLegend, |
| 9 | + ChartLegendContent, |
| 10 | + ChartTooltip, |
| 11 | + ChartTooltipContent, |
| 12 | +} from '@/components/ui/chart' |
| 13 | + |
| 14 | +type SeriesItem = { |
| 15 | + key: string |
| 16 | + label: string |
| 17 | + type: 'line' | 'bar' | 'area' |
| 18 | + color?: string | undefined |
| 19 | +} |
| 20 | + |
| 21 | +type SeriesConfigMap = Record<string, Partial<SeriesItem>> |
| 22 | + |
| 23 | +export type ComposedChartProps = { |
| 24 | + title: string |
| 25 | + description?: string |
| 26 | + xAxisKey: string |
| 27 | + series: SeriesItem[] |
| 28 | + config?: SeriesConfigMap |
| 29 | + dataset: [] |
| 30 | +} |
| 31 | + |
| 32 | +const Chart: React.FC<ComposedChartProps> = (props) => { |
| 33 | + const { dataset = [], xAxisKey, series = [], config = {} } = props |
| 34 | + |
| 35 | + const seriesConfig = series.reduce<Record<string, SeriesItem>>((prev, curr) => { |
| 36 | + const { key } = curr |
| 37 | + prev[key] = curr |
| 38 | + return prev |
| 39 | + }, {}) |
| 40 | + |
| 41 | + const chartConfig: Record<string, SeriesItem> = {} |
| 42 | + for (const key in seriesConfig) { |
| 43 | + if (!Object.hasOwn(seriesConfig, key)) continue |
| 44 | + const element = seriesConfig[key] |
| 45 | + chartConfig[key] = { |
| 46 | + ...element, |
| 47 | + ...config?.[key], |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + const renderSeries = (item: SeriesItem, idx: number) => { |
| 52 | + const { type, key, label } = item |
| 53 | + const color = chartConfig[key]?.color || `var(--chart-${idx + 1})` |
| 54 | + |
| 55 | + switch (type) { |
| 56 | + case 'line': |
| 57 | + return <Line dataKey={key} label={label} fill={color} stroke={color} type="monotone" /> |
| 58 | + case 'bar': |
| 59 | + return <Bar dataKey={key} label={label} fill={color} stroke={color} radius={4} /> |
| 60 | + case 'area': |
| 61 | + return <Area dataKey={key} label={label} fill={color} stroke={color} type="monotone" /> |
| 62 | + |
| 63 | + default: |
| 64 | + break |
| 65 | + } |
| 66 | + |
| 67 | + return null |
| 68 | + } |
| 69 | + |
| 70 | + return ( |
| 71 | + <ChartContainer config={chartConfig} className="min-h-[200px] w-full"> |
| 72 | + <ComposedChart data={dataset}> |
| 73 | + <CartesianGrid vertical={false} stroke="#f5f5f5" /> |
| 74 | + <XAxis dataKey={xAxisKey} /> |
| 75 | + <YAxis /> |
| 76 | + <ChartTooltip content={<ChartTooltipContent />} /> |
| 77 | + <ChartLegend content={<ChartLegendContent />} /> |
| 78 | + {series.map((item, idx) => renderSeries(item, idx))} |
| 79 | + </ComposedChart> |
| 80 | + </ChartContainer> |
| 81 | + ) |
| 82 | +} |
| 83 | + |
| 84 | +export default Chart |
0 commit comments