All files / packages/ui/src/components/DonutChart utils.ts

100% Statements 27/27
100% Branches 10/10
100% Functions 5/5
100% Lines 27/27

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                                    3x       7x 1x     6x 3x     3x     3x                     8x 3x     5x 5x   5x   5x 8x 8x 8x 8x 8x   8x   8x                     3x             7x 4x     3x 3x 3x   3x                
import type { DonutChartItem } from "./index";
 
export interface ChartArcSegment {
  key: string;
  color: string;
  length: number;
  offset: number;
  startArcLength: number;
  endArcLength: number;
}
 
export interface ChartTailOverlaySegment {
  key: string;
  color: string;
  length: number;
  offset: number;
}
 
export const formatDisplayTotal = (
  totalCount: number,
  formatter?: (total: number) => string,
): string => {
  if (formatter) {
    return formatter(totalCount);
  }
 
  if (totalCount === 0) {
    return "0";
  }
 
  return String(totalCount).padStart(2, "0");
};
 
export const createSegments = ({
  activeItems,
  totalCount,
  circumference,
  segmentGap,
}: {
  activeItems: DonutChartItem[];
  totalCount: number;
  circumference: number;
  segmentGap: number;
}): ChartArcSegment[] => {
  if (activeItems.length === 0) {
    return [];
  }
 
  const base = Math.max(totalCount, 1);
  const adjustedGap = activeItems.length > 1 ? Math.max(segmentGap, 0) : 0;
 
  let cumulativeLength = 0;
 
  return activeItems.map((item, index) => {
    const rawLength = (item.count / base) * circumference;
    const length = Math.max(rawLength - adjustedGap, 1);
    const startArcLength = cumulativeLength;
    const endArcLength = startArcLength + length;
    const offset = -startArcLength;
 
    cumulativeLength += rawLength;
 
    return {
      key: `${item.category}-${index}`,
      color: item.color,
      length,
      offset,
      startArcLength,
      endArcLength,
    };
  });
};
 
export const createTailOverlays = ({
  segments,
  strokeWidth,
}: {
  segments: ChartArcSegment[];
  strokeWidth: number;
}): ChartTailOverlaySegment[] => {
  if (segments.length <= 1) {
    return [];
  }
 
  return segments.slice(0, -1).map((segment) => {
    const overlayLength = Math.min(strokeWidth * 0.9, Math.max(segment.length, 1));
    const overlayStart = segment.endArcLength - overlayLength / 2;
 
    return {
      key: `${segment.key}-tail-overlay`,
      color: segment.color,
      length: overlayLength,
      offset: -overlayStart,
    };
  });
};