All files / src/components/Chart LineChart.tsx

94.96% Statements 151/159
77.14% Branches 27/35
100% Functions 3/3
94.96% Lines 151/159

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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 2161x 1x                     1x 1x 1x     1x     1x     1x                                             1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 5x 4x 4x 5x 14x 14x   14x 14x 7x 7x 7x   7x 7x 7x             7x 14x 14x   14x 4x 14x   14x 1x 14x   14x 14x 13x 5x 5x 7x 5x 14x 14x 14x 8x 8x 14x   14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x 14x 14x 14x 14x 14x 14x 13x   14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 37x 37x 37x   37x 70x 70x 70x 37x     37x     37x   37x 37x 37x 37x 37x 37x 37x 37x   37x 40x 40x 40x   14x 14x 14x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   14x 14x   14x   1x  
import { useCallback, useMemo, useRef, useState } from 'react';
import {
  LineChart as ReLineChart,
  XAxis,
  YAxis,
  CartesianGrid,
  Line,
  DotProps,
  Layer,
} from 'recharts';
 
// Components
import CustomTooltip from './CustomTooltip';
import CustomXAxisTick from './CustomXAxisTick';
import CustomYAxisTick from './CustomYAxisTick';
 
// Constants
import { CHART_COLORS } from '@/constants/chart';
 
// Utils
import { isTruthy } from '@/utils/validation';
 
// Types
import { ChartKey, LineChartRow, Metric } from '@/types/chart';
 
type OnMouseMove = NonNullable<
  React.ComponentProps<typeof ReLineChart>['onMouseMove']
>;
 
interface LineChartProps {
  data: LineChartRow[];
  metrics: Metric[];
  spacing: number;
  roundedMax: number;
  ticks: number[];
  colors: string[];
  colorsByKey?: Record<string, string>;
  width?: number;
  height?: number;
  barSize?: number;
  activeIndex?: number | null;
  modeKey?: ChartKey;
  containerRef?: React.RefObject<HTMLDivElement | null>;
  onActiveIndexChange?: (i: number | null) => void;
}
 
const LineChart = ({
  data,
  metrics,
  spacing,
  roundedMax,
  ticks,
  colors,
  colorsByKey,
  width = 300,
  height = 200,
  barSize = 16,
  activeIndex = null,
  modeKey = ChartKey.SLOT,
  containerRef,
  onActiveIndexChange,
}: LineChartProps) => {
  const dotRef = useRef<Record<number, { cx: number; cy: number }>>({});
  const [overlayX, setOverlayX] = useState<number | null>(null);
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);
 
  const setActiveIndex = useCallback(
    (next: number | null) => {
      if (next !== activeIndex) {
        onActiveIndexChange?.(next);
      }
    },
    [activeIndex],
  );
 
  const handleMouseMove: OnMouseMove = useCallback(
    (state) => {
      if (state?.isTooltipActive && isTruthy(state.activeTooltipIndex)) {
        const idx = Number(state.activeTooltipIndex);
        const x = state.activeCoordinate?.x ?? 0;
 
        setOverlayX((prev) => (prev !== x ? x : prev));
        setHoverIndex((prev) => (prev !== idx ? idx : prev));
      } else {
        if (isTruthy(overlayX || hoverIndex)) {
          setOverlayX(null);
          setHoverIndex(null);
          setActiveIndex?.(null);
        }
      }
    },
    [overlayX, hoverIndex, setActiveIndex],
  );
 
  const handleMouseLeave = useCallback(() => {
    setActiveIndex?.(null);
  }, [setActiveIndex]);
 
  const handleMouseEnter = useCallback(() => {
    setActiveIndex?.(hoverIndex);
  }, [hoverIndex, setActiveIndex]);
 
  const hasDataRow = useMemo(
    () =>
      isTruthy(hoverIndex) &&
      data[hoverIndex] &&
      Object.entries(data[hoverIndex]).some(([key, value]) => {
        return !isNaN(Number(key)) && typeof value === 'number' && value > 0;
      }),
    [hoverIndex, data],
  );
  const widthYAxis = useMemo(() => {
    const dynamicWidth = Math.max(...ticks).toString().length * 10;
    return Math.max(dynamicWidth, 30); // 30 is min width
  }, [ticks]);
 
  return (
    <ReLineChart
      data={data}
      width={width}
      height={height}
      margin={{ top: 16, right: 0, left: 0, bottom: 0 }}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      <CartesianGrid strokeDasharray="3 3" vertical={false} />
      <XAxis
        dataKey="label"
        tickLine={false}
        axisLine={false}
        interval={0}
        scale="point"
        padding={{ left: spacing, right: spacing }}
        tick={(props) => (
          <CustomXAxisTick {...props} activeIndex={activeIndex} data={data} />
        )}
      />
      <YAxis
        axisLine={false}
        tickLine={false}
        width={widthYAxis}
        domain={[0, roundedMax]}
        ticks={ticks}
        tick={CustomYAxisTick}
      />
      <CustomTooltip
        modeKey={modeKey}
        colorsByKey={colorsByKey}
        activeIndex={activeIndex}
        containerRef={containerRef}
        dotRef={dotRef}
      />
      {metrics.map((m, idx) => {
        const color = colors[idx] ?? CHART_COLORS.PRIMARY;
        return (
          <Line
            key={m.key}
            type="linear"
            dataKey={m.key}
            name={m.label ?? m.key}
            stroke={color}
            dot={{ r: 3, fill: color }}
            strokeWidth={1.5}
            activeDot={(p) => {
              const { index, dataKey, cx, cy } = p;
              const row = data[index];
              if (row) {
                // Find the metric key with the maximum value in the current row
                const maxKey = metrics.reduce((prev, curr) => {
                  const prevVal = row[prev.key] ?? -Infinity;
                  const currVal = row[curr.key] ?? -Infinity;
                  return currVal > prevVal ? curr : prev;
                });
 
                // If the current dot matches the maximum metric → store its position in ref
                if (dataKey === maxKey.key) {
                  dotRef.current[index] = { cx: cx!, cy: cy! };
                }
              }
 
              return (
                <circle
                  cx={cx}
                  cy={cy}
                  r={activeIndex === index ? 4 : 3}
                  fill={color}
                  stroke={color}
                />
              );
            }}
            isAnimationActive={false}
            connectNulls={false}
          />
        );
      })}
      <Layer>
        {isTruthy(overlayX) && hasDataRow && (
          <rect
            x={overlayX - barSize / 2}
            y={0}
            width={barSize}
            height={height}
            fill="none"
            pointerEvents="all"
            className="cursor-pointer"
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
          />
        )}
      </Layer>
    </ReLineChart>
  );
};
 
export default LineChart;