All files / components/hooks/gapChart useGapChartLegend.ts

0% Statements 0/15
0% Branches 0/22
0% Functions 0/3
0% Lines 0/14

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                                                                                                                                                                                   
import { useMemo } from "react";
 
export interface LegendItem {
  type: "value1" | "value2" | "gap";
  label: string;
  color?: string;
  shape?: "circle" | "square" | "triangle";
  visible?: boolean;
}
 
interface UseGapChartLegendProps {
  shapesLabelsMapping?: {
    value1?: string;
    value2?: string;
    gap?: string;
  };
  shapeValue1: "circle" | "square" | "triangle";
  shapeValue2: "circle" | "square" | "triangle";
  colorMode: "label" | "shape";
  shapeColorsMapping?: {
    value1?: string;
    value2?: string;
    gap?: string;
  };
  legendFormatter?: (items: LegendItem[]) => LegendItem[];
}
 
export const useGapChartLegend = ({
  shapesLabelsMapping,
  shapeValue1,
  shapeValue2,
  colorMode,
  shapeColorsMapping,
  legendFormatter,
}: UseGapChartLegendProps) => {
  const legendItems = useMemo(() => {
    if (!shapesLabelsMapping) return [];
 
    // Prepare default legend items
    const defaultLegendItems: LegendItem[] = [];
 
    if (shapesLabelsMapping.value1) {
      defaultLegendItems.push({
        type: "value1",
        label: shapesLabelsMapping.value1,
        shape: shapeValue1,
        color:
          colorMode === "shape" && shapeColorsMapping?.value1 ? shapeColorsMapping.value1 : "#666",
        visible: true,
      });
    }
 
    if (shapesLabelsMapping.gap) {
      defaultLegendItems.push({
        type: "gap",
        label: shapesLabelsMapping.gap,
        color: colorMode === "shape" && shapeColorsMapping?.gap ? shapeColorsMapping.gap : "#999",
        visible: true,
      });
    }
 
    if (shapesLabelsMapping.value2) {
      defaultLegendItems.push({
        type: "value2",
        label: shapesLabelsMapping.value2,
        shape: shapeValue2,
        color:
          colorMode === "shape" && shapeColorsMapping?.value2 ? shapeColorsMapping.value2 : "#666",
        visible: true,
      });
    }
 
    // Apply formatter if provided
    const items = legendFormatter
      ? legendFormatter(defaultLegendItems).filter(item => item.visible !== false)
      : defaultLegendItems;
 
    return items;
  }, [
    shapesLabelsMapping,
    shapeValue1,
    shapeValue2,
    colorMode,
    shapeColorsMapping,
    legendFormatter,
  ]);
 
  return { legendItems };
};