|
| 1 | +import { |
| 2 | + Bar, |
| 3 | + BarChart as RechartBarChart, |
| 4 | + Legend, |
| 5 | + ResponsiveContainer, |
| 6 | + Tooltip, |
| 7 | + XAxis, |
| 8 | + YAxis, |
| 9 | +} from "recharts"; |
| 10 | +import { useBentoConfig } from "../../BentoConfigContext"; |
| 11 | +import { bodyRecipe } from "../../Typography/Body/Body.css"; |
| 12 | +import { allColors } from "../../util/atoms"; |
| 13 | +import { vars } from "../../vars.css"; |
| 14 | +import { ChartProps } from "../ChartProps"; |
| 15 | +import { legendContent } from "../Legend/Legend"; |
| 16 | +import { tooltipContent } from "../Tooltip/Tooltip"; |
| 17 | + |
| 18 | +type Props<D extends string, C extends string> = ChartProps & { |
| 19 | + data: Record<D | C, unknown>[]; |
| 20 | + categories: C[]; |
| 21 | + dataKey: D; |
| 22 | + hideXAxis?: boolean; |
| 23 | + hideYAxis?: boolean; |
| 24 | + stacked?: boolean; |
| 25 | +}; |
| 26 | + |
| 27 | +export type { Props as BarChartProps }; |
| 28 | + |
| 29 | +export function BarChart<D extends string, C extends string>({ |
| 30 | + data, |
| 31 | + dataKey, |
| 32 | + categories, |
| 33 | + hideXAxis = false, |
| 34 | + hideYAxis = false, |
| 35 | + hideLegend = false, |
| 36 | + disableAnimation = false, |
| 37 | + hideTooltip = false, |
| 38 | + width = "100%", |
| 39 | + height, |
| 40 | + minWidth, |
| 41 | + minHeight, |
| 42 | + maxHeight, |
| 43 | + aspect, |
| 44 | + debounce, |
| 45 | + stacked = false, |
| 46 | + dataColors, |
| 47 | + children, |
| 48 | +}: Props<D, C>) { |
| 49 | + const config = useBentoConfig(); |
| 50 | + const colors = (dataColors ?? config.chart.defaultDataColors).map( |
| 51 | + (colorName) => allColors[colorName] |
| 52 | + ); |
| 53 | + |
| 54 | + return ( |
| 55 | + <ResponsiveContainer |
| 56 | + className={bodyRecipe({ size: "medium", weight: "default", color: "default" })} |
| 57 | + width={width} |
| 58 | + height={height} |
| 59 | + minWidth={minWidth} |
| 60 | + minHeight={minHeight} |
| 61 | + maxHeight={maxHeight} |
| 62 | + aspect={aspect} |
| 63 | + debounce={debounce} |
| 64 | + > |
| 65 | + <RechartBarChart data={data}> |
| 66 | + {!hideXAxis && <XAxis dataKey={dataKey} />} |
| 67 | + {!hideYAxis && <YAxis />} |
| 68 | + {!hideTooltip && ( |
| 69 | + <Tooltip |
| 70 | + content={tooltipContent} |
| 71 | + cursor={{ fill: vars.backgroundColor.backgroundSecondary }} |
| 72 | + /> |
| 73 | + )} |
| 74 | + {!hideLegend && <Legend content={legendContent} />} |
| 75 | + {categories.map((category, i) => ( |
| 76 | + <Bar |
| 77 | + key={category} |
| 78 | + dataKey={category} |
| 79 | + fill={colors[i % colors.length]} |
| 80 | + isAnimationActive={!disableAnimation} |
| 81 | + stackId={stacked ? "stack" : undefined} |
| 82 | + /> |
| 83 | + ))} |
| 84 | + {children} |
| 85 | + </RechartBarChart> |
| 86 | + </ResponsiveContainer> |
| 87 | + ); |
| 88 | +} |
0 commit comments