All files / components/hooks/gapChart useGapChartMetadata.ts

0% Statements 0/15
0% Branches 0/9
0% Functions 0/5
0% Lines 0/15

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                                                                                                                     
import { useRef, useLayoutEffect } from "react";
import useDeepCompareEffect from "use-deep-compare-effect";
import { ChartMetadata, DataPoint } from "src/types/data";
 
interface DataItem {
  label: string;
  code?: string;
  value1: number;
  value2: number;
  difference: number;
  date: string;
}
 
interface UseGapChartMetadataProps {
  processedDataSet: DataItem[];
  xAxisDomain: [number, number];
  onChartDataProcessed?: (metadata: ChartMetadata) => void;
}
 
export const useGapChartMetadata = ({
  processedDataSet,
  xAxisDomain,
  onChartDataProcessed,
}: UseGapChartMetadataProps) => {
  const prevChartDataRef = useRef<ChartMetadata | null>(null);
  const renderCompleteRef = useRef(false);
 
  useLayoutEffect(() => {
    renderCompleteRef.current = true;
  }, []);
 
  useDeepCompareEffect(() => {
    if (onChartDataProcessed && renderCompleteRef.current && processedDataSet.length > 0) {
      const currentMetadata: ChartMetadata = {
        xAxisDomain: xAxisDomain.map(String),
        yAxisDomain: xAxisDomain as [number, number],
        visibleItems: processedDataSet.map(d => d.label),
        renderedData: processedDataSet.reduce(
          (acc, item) => {
            acc[item.label] = [item as unknown as DataPoint];
            return acc;
          },
          {} as { [key: string]: DataPoint[] }
        ),
        chartType: "line-chart" as ChartMetadata["chartType"],
      };
 
      const hasChanged =
        !prevChartDataRef.current ||
        JSON.stringify(prevChartDataRef.current) !== JSON.stringify(currentMetadata);
 
      if (hasChanged) {
        onChartDataProcessed(currentMetadata);
        prevChartDataRef.current = currentMetadata;
      }
    }
  }, [processedDataSet, xAxisDomain, onChartDataProcessed]);
};