All files / react-base/src/components/ui bar-chart.tsx

0% Statements 0/44
0% Branches 0/1
0% Functions 0/1
0% Lines 0/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                                                                                                                                         
import { Bar, BarChart as RechartsBarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import {
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/components/ui/chart";
import { cn } from "@/lib/utils";
 
export type BarChartDataPoint = Record<string, string | number>;
 
type BarChartProps = {
  data: BarChartDataPoint[];
  config: ChartConfig;
  dataKeys: string[];
  categoryKey: string;
  className?: string;
  showLegend?: boolean;
  layout?: "horizontal" | "vertical";
};
 
export function BarChart({
  data,
  config,
  dataKeys,
  categoryKey,
  className,
  showLegend = true,
  layout = "horizontal",
}: BarChartProps) {
  const isVertical = layout === "vertical";
 
  return (
    <ChartContainer config={config} className={cn("aspect-auto h-[300px] w-full", className)}>
      <RechartsBarChart
        accessibilityLayer
        data={data}
        layout={isVertical ? "vertical" : "horizontal"}
        margin={{ left: 12, right: 12, top: 12, bottom: 0 }}
      >
        <CartesianGrid vertical={false} strokeDasharray="3 3" />
        {isVertical ? (
          <>
            <XAxis type="number" tickLine={false} axisLine={false} tickMargin={8} />
            <YAxis
              dataKey={categoryKey}
              type="category"
              tickLine={false}
              axisLine={false}
              tickMargin={8}
              width={80}
            />
          </>
        ) : (
          <>
            <XAxis
              dataKey={categoryKey}
              tickLine={false}
              tickMargin={10}
              axisLine={false}
              tickFormatter={(value) => String(value).slice(0, 3)}
            />
            <YAxis tickLine={false} axisLine={false} tickMargin={8} />
          </>
        )}
        <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dashed" />} />
        {showLegend && <ChartLegend content={<ChartLegendContent />} />}
        {dataKeys.map((key) => (
          <Bar key={key} dataKey={key} fill={`var(--color-${key})`} radius={[4, 4, 0, 0]} />
        ))}
      </RechartsBarChart>
    </ChartContainer>
  );
}