All files / src/components/Chart ComposedChart.tsx

96% Statements 192/200
79.41% Branches 27/34
100% Functions 8/8
96% Lines 192/200

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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 2731x 1x                           1x 1x 1x 1x 1x     1x     1x     1x                                                 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x   10x 1x 1x     10x 1x 1x 1x 1x     10x 10x   10x   10x 10x 10x 16x   16x 16x 4x 3x 3x 4x 16x 16x   16x 16x 7x 7x 7x   7x 7x 7x             7x 16x 16x   16x 1x 16x   16x 3x 16x   16x 16x 16x 15x 5x     16x 16x   16x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 15x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x     16x 16x 16x 16x 16x 16x 15x 15x 15x 15x 15x 15x 15x   16x 16x 16x 16x 16x 16x 16x 15x 15x 15x 15x 15x 15x 15x   16x     16x 16x 16x 16x 16x 16x 15x 15x 15x 15x 15x 15x 15x 15x   15x 16x 15x 15x 15x 15x 15x 15x 15x 15x   16x 16x 16x   16x 16x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   16x 16x   16x   1x  
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  ComposedChart as ReComposedChart,
  XAxis,
  YAxis,
  CartesianGrid,
  Bar,
  Line,
  DotProps,
  ReferenceLine,
  Layer,
  type BarProps,
} from 'recharts';
 
// Components
import CustomTooltip from './CustomTooltip';
import CustomXAxisTick from './CustomXAxisTick';
import CustomYAxisTick from './CustomYAxisTick';
import CustomShapeBar, { CustomShapeBarProps } from './CustomShapeBar';
import CustomDot from './CustomDot';
 
// Constants
import { CHART_FIELDS } from '@/constants/chart';
 
// Types
import { BarPosition, ChartMode, ChartRow } from '@/types/chart';
 
// Utils
import { isTruthy } from '@/utils/validation';
 
type OnMouseMove = NonNullable<
  React.ComponentProps<typeof ReComposedChart>['onMouseMove']
>;
type ExtractFn<T> = T extends (...args: unknown[]) => unknown ? T : never;
type ShapeFn = ExtractFn<NonNullable<BarProps['shape']>>;
type ShapeProps = Parameters<ShapeFn>[0];
 
interface ComposedChartProps {
  data: ChartRow[];
  colorsByKey?: Record<string, string>;
  spacing: number;
  roundedMax: number;
  ticks: number[];
  width?: number;
  height?: number;
  barSize?: number;
  gridColor?: string;
  activeIndex?: number | null;
  containerRef?: React.RefObject<HTMLDivElement | null>;
  mode?: ChartMode;
  onActiveIndexChange?: (i: number | null) => void;
}
 
const ComposedChart = ({
  data,
  colorsByKey,
  spacing,
  roundedMax,
  ticks,
  width = 300,
  height = 210,
  barSize = 12,
  gridColor = 'hsl(var(--primary-550))',
  activeIndex = null,
  containerRef,
  mode = ChartMode.Week,
  onActiveIndexChange,
}: ComposedChartProps) => {
  const dotRef = useRef<Record<number, { cx: number; cy: number }>>({});
  const [overlayX, setOverlayX] = useState<number | null>(null);
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);
 
  useEffect(() => {
    // Hide tooltip when user scrolls anywhere on the page
    const handleScroll = () => {
      onActiveIndexChange?.(null);
    };
 
    // Hide tooltip when user clicks outside of the chart container
    const handleClick = (e: MouseEvent) => {
      if (!containerRef?.current?.contains(e.target as Node)) {
        onActiveIndexChange?.(null);
      }
    };
 
    // Listen to scroll and click events
    window.addEventListener('scroll', handleScroll, true);
    document.addEventListener('click', handleClick);
 
    return () => {
      // Clean up listeners on unmount
      window.removeEventListener('scroll', handleScroll, true);
      document.removeEventListener('click', handleClick);
    };
  }, [onActiveIndexChange, containerRef]);
 
  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 widthYAxis = Math.max(...ticks).toString().length * 10;
  const hasDataRow = useMemo(
    () =>
      isTruthy(hoverIndex) &&
      (Number(data[hoverIndex]?.lunchRegistrations) > 0 ||
        Number(data[hoverIndex]?.likes) > 0 ||
        Number(data[hoverIndex]?.dislikes) > 0),
    [hoverIndex, data],
  );
 
  return (
    <ReComposedChart
      key={`${mode}-${data[0]?.title}`}
      data={data}
      width={width}
      height={height}
      margin={{ top: 16, right: 0, left: 0, bottom: 0 }}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      <CartesianGrid
        strokeDasharray="3 3"
        stroke={gridColor}
        strokeWidth={0.5}
        vertical={false}
      />
      <XAxis
        dataKey={CHART_FIELDS.label.key}
        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}
        domain={[0, roundedMax]}
        ticks={ticks}
        width={widthYAxis}
        tick={CustomYAxisTick}
      />
      <CustomTooltip
        colorsByKey={colorsByKey}
        containerRef={containerRef}
        activeIndex={activeIndex}
        dotRef={dotRef}
      />
      <ReferenceLine
        y={0}
        stroke={CHART_FIELDS.likes.color}
        strokeWidth={0.8}
      />
 
      {/* Bar stack: Likes + Dislikes */}
      <Bar
        dataKey={CHART_FIELDS.likes.key}
        name={CHART_FIELDS.likes.name}
        stackId="reactions"
        fill={CHART_FIELDS.likes.color}
        shape={(props: ShapeProps) => (
          <CustomShapeBar
            {...(props as CustomShapeBarProps)}
            position={BarPosition.BOTTOM}
            siblingKey={CHART_FIELDS.dislikes.key}
            barSize={barSize}
            dotCx={dotRef?.current[(props as CustomShapeBarProps).index!]?.cx}
          />
        )}
      />
      <Bar
        dataKey={CHART_FIELDS.dislikes.key}
        name={CHART_FIELDS.dislikes.name}
        stackId="reactions"
        fill={CHART_FIELDS.dislikes.color}
        shape={(props: ShapeProps) => (
          <CustomShapeBar
            {...(props as CustomShapeBarProps)}
            position={BarPosition.TOP}
            siblingKey={CHART_FIELDS.likes.key}
            barSize={barSize}
            dotCx={dotRef?.current[(props as CustomShapeBarProps).index!]?.cx}
          />
        )}
      />
 
      {/* Line = lunchRegistrations */}
      <Line
        type="linear"
        dataKey={CHART_FIELDS.lunchRegistrations.key}
        name={CHART_FIELDS.lunchRegistrations.name}
        stroke={CHART_FIELDS.lunchRegistrations.color}
        dot={(props) => {
          const { key, ...restProps } = props; // Destructure and remove `key`
          return (
            <CustomDot
              key={props.index}
              {...restProps}
              dotRef={dotRef}
              color={CHART_FIELDS.lunchRegistrations.color}
            />
          );
        }}
        activeDot={(p: DotProps & { index?: number }) => (
          <circle
            cx={p.cx}
            cy={p.cy}
            r={activeIndex === p.index ? 4 : 3}
            fill={CHART_FIELDS.lunchRegistrations.color}
            stroke={CHART_FIELDS.lunchRegistrations.color}
            className="cursor-pointer"
          />
        )}
        isAnimationActive={false}
        connectNulls={false}
      />
 
      <Layer>
        {isTruthy(overlayX) && hasDataRow && (
          <rect
            x={overlayX - barSize / 2}
            y={0}
            width={barSize}
            height={height}
            fill="none"
            pointerEvents="all"
            className={hasDataRow ? 'cursor-pointer' : 'cursor-default'}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
          />
        )}
      </Layer>
    </ReComposedChart>
  );
};
 
export default ComposedChart;