All files / src/components/Chart index.tsx

100% Statements 91/91
86.66% Branches 13/15
100% Functions 2/2
100% Lines 91/91

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 1391x 1x     1x 1x     1x     1x     1x     1x                                         1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x   36x 36x 36x 36x 36x 36x   36x 36x 34x 34x 34x 36x 36x       36x 36x 36x 36x 36x 36x         36x 36x   36x 36x   36x 36x 36x 36x 36x 36x 36x   36x 36x 36x 36x 36x 24x 24x   36x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   36x 36x 36x   36x   1x  
import { useState, useMemo, useRef } from 'react';
import { ResponsiveContainer } from 'recharts';
 
// Components
import LineChart from './LineChart';
import ComposedChart from './ComposedChart';
 
// Hooks
import { useWindowWidth } from '@shared/hooks';
 
// Utils
import { calculateChartConfig } from '@/utils/chart';
 
// Constants
import { CHART_COLORS, DEFAULT_CHART_COLORS } from '@/constants/chart';
 
// Types
import {
  ChartKey,
  ChartMode,
  ChartRow,
  ChartType,
  LineChartRow,
  Metric,
} from '@/types/chart';
 
interface ChartProps {
  data: (ChartRow | LineChartRow)[];
  metrics?: Metric[];
  type: ChartType | null;
  height?: number;
  mode?: ChartMode;
  modeKey?: ChartKey;
  isTotal?: boolean;
  colors?: string[];
  barSize?: number;
}
 
const Chart = ({
  data,
  metrics = [],
  type = ChartType.Composed,
  height = 210,
  mode = ChartMode.Week,
  modeKey = ChartKey.SLOT,
  isTotal = false,
  colors = DEFAULT_CHART_COLORS,
  barSize = 12,
}: ChartProps) => {
  const width = useWindowWidth();
  const containerRef = useRef<HTMLDivElement>(null);
  const [chartWidth, setChartWidth] = useState(0);
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
 
  const { spacing, roundedMax, ticks } = calculateChartConfig({
    mode,
    chartWidth,
    data,
    isTotal,
  });
 
  const colorsByKey = useMemo(
    () =>
      Object.fromEntries(
        metrics.map((m, i) => [m.key, colors[i] ?? CHART_COLORS.PRIMARY]),
      ),
    [metrics],
  );
 
  // Define bar size scaling factors relative to the base `barSize` (default: 12).
  // Instead of hardcoding values like 12, 18, 20, 24...
  const BAR_SIZE_MAP: Record<ChartMode, { normal: number; total: number }> = {
    [ChartMode.Week]: { normal: 1, total: 18 / barSize },
    [ChartMode.Month]: { normal: 1, total: 1 },
    [ChartMode.Quarter]: { normal: 20 / barSize, total: 24 / barSize },
    [ChartMode.Year]: { normal: 20 / barSize, total: 20 / barSize },
  };
 
  // Compute the actual bar size to be used in the chart.
  //   - If `isTotal` is true → use the `total` scaling factor
  //   - Otherwise → use the `normal` scaling factor
  const customBarSize =
    barSize * (isTotal ? BAR_SIZE_MAP[mode].total : BAR_SIZE_MAP[mode].normal);
 
  const estimatedWidth =
    mode === ChartMode.Month ? data.length * (customBarSize / 4 + spacing) : 0;
 
  return (
    <div
      ref={containerRef}
      className="w-full h-full small-scrollbar scroll-smooth snap-x snap-mandatory"
      style={{
        overflowX: estimatedWidth > (width * 4) / 5 ? 'auto' : 'hidden',
      }}
    >
      <div style={{ minWidth: estimatedWidth, overflow: 'visible' }}>
        <ResponsiveContainer
          width="100%"
          height={height}
          onResize={(w) => {
            setChartWidth((prev) => (prev !== w ? w : prev));
          }}
        >
          {type === ChartType.Composed ? (
            <ComposedChart
              data={data as ChartRow[]}
              colorsByKey={colorsByKey}
              spacing={spacing}
              roundedMax={roundedMax}
              ticks={ticks}
              barSize={customBarSize}
              activeIndex={hoveredIndex}
              containerRef={containerRef}
              mode={mode}
              onActiveIndexChange={setHoveredIndex}
            />
          ) : (
            <LineChart
              modeKey={modeKey}
              data={data as LineChartRow[]}
              metrics={metrics}
              colors={colors}
              colorsByKey={colorsByKey}
              spacing={spacing}
              roundedMax={roundedMax}
              ticks={ticks}
              activeIndex={hoveredIndex}
              containerRef={containerRef}
              onActiveIndexChange={setHoveredIndex}
            />
          )}
        </ResponsiveContainer>
      </div>
    </div>
  );
};
 
export default Chart;